luci2: major changes to RPC implementation
[project/luci2/ui.git] / luci2 / htdocs / luci2 / luci2.js
1 /*
2 LuCI2 - OpenWrt Web Interface
3
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11 */
12
13 String.prototype.format = function()
14 {
15 var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
16 var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
17
18 function esc(s, r) {
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
21 return s;
22 }
23
24 var str = this;
25 var out = '';
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27 var a = b = [], numSubstitutions = 0, numMatches = 0;
28
29 while ((a = re.exec(str)) != null)
30 {
31 var m = a[1];
32 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33 var pPrecision = a[6], pType = a[7];
34
35 numMatches++;
36
37 if (pType == '%')
38 {
39 subst = '%';
40 }
41 else
42 {
43 if (numSubstitutions < arguments.length)
44 {
45 var param = arguments[numSubstitutions++];
46
47 var pad = '';
48 if (pPad && pPad.substr(0,1) == "'")
49 pad = leftpart.substr(1,1);
50 else if (pPad)
51 pad = pPad;
52
53 var justifyRight = true;
54 if (pJustify && pJustify === "-")
55 justifyRight = false;
56
57 var minLength = -1;
58 if (pMinLength)
59 minLength = parseInt(pMinLength);
60
61 var precision = -1;
62 if (pPrecision && pType == 'f')
63 precision = parseInt(pPrecision.substring(1));
64
65 var subst = param;
66
67 switch(pType)
68 {
69 case 'b':
70 subst = (parseInt(param) || 0).toString(2);
71 break;
72
73 case 'c':
74 subst = String.fromCharCode(parseInt(param) || 0);
75 break;
76
77 case 'd':
78 subst = (parseInt(param) || 0);
79 break;
80
81 case 'u':
82 subst = Math.abs(parseInt(param) || 0);
83 break;
84
85 case 'f':
86 subst = (precision > -1)
87 ? ((parseFloat(param) || 0.0)).toFixed(precision)
88 : (parseFloat(param) || 0.0);
89 break;
90
91 case 'o':
92 subst = (parseInt(param) || 0).toString(8);
93 break;
94
95 case 's':
96 subst = param;
97 break;
98
99 case 'x':
100 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
101 break;
102
103 case 'X':
104 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
105 break;
106
107 case 'h':
108 subst = esc(param, html_esc);
109 break;
110
111 case 'q':
112 subst = esc(param, quot_esc);
113 break;
114
115 case 'j':
116 subst = String.serialize(param);
117 break;
118
119 case 't':
120 var td = 0;
121 var th = 0;
122 var tm = 0;
123 var ts = (param || 0);
124
125 if (ts > 60) {
126 tm = Math.floor(ts / 60);
127 ts = (ts % 60);
128 }
129
130 if (tm > 60) {
131 th = Math.floor(tm / 60);
132 tm = (tm % 60);
133 }
134
135 if (th > 24) {
136 td = Math.floor(th / 24);
137 th = (th % 24);
138 }
139
140 subst = (td > 0)
141 ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142 : '%dh %dm %ds'.format(th, tm, ts);
143
144 break;
145
146 case 'm':
147 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
149
150 var i = 0;
151 var val = parseFloat(param || 0);
152 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
153
154 for (i = 0; (i < units.length) && (val > mf); i++)
155 val /= mf;
156
157 subst = val.toFixed(pr) + ' ' + units[i];
158 break;
159 }
160
161 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
162
163 if (minLength > 0 && pad.length > 0)
164 for (var i = 0; i < (minLength - subst.length); i++)
165 subst = justifyRight ? (pad + subst) : (subst + pad);
166 }
167 }
168
169 out += leftpart + subst;
170 str = str.substr(m.length);
171 }
172
173 return out + str;
174 }
175
176 function LuCI2()
177 {
178 var _luci2 = this;
179
180 var Class = function() { };
181
182 Class.extend = function(properties)
183 {
184 Class.initializing = true;
185
186 var prototype = new this();
187 var superprot = this.prototype;
188
189 Class.initializing = false;
190
191 $.extend(prototype, properties, {
192 callSuper: function() {
193 var args = [ ];
194 var meth = arguments[0];
195
196 if (typeof(superprot[meth]) != 'function')
197 return undefined;
198
199 for (var i = 1; i < arguments.length; i++)
200 args.push(arguments[i]);
201
202 return superprot[meth].apply(this, args);
203 }
204 });
205
206 function _class()
207 {
208 this.options = arguments[0] || { };
209
210 if (!Class.initializing && typeof(this.init) == 'function')
211 this.init.apply(this, arguments);
212 }
213
214 _class.prototype = prototype;
215 _class.prototype.constructor = _class;
216
217 _class.extend = arguments.callee;
218
219 return _class;
220 };
221
222 this.defaults = function(obj, def)
223 {
224 for (var key in def)
225 if (typeof(obj[key]) == 'undefined')
226 obj[key] = def[key];
227
228 return obj;
229 };
230
231 this.isDeferred = function(x)
232 {
233 return (typeof(x) == 'object' &&
234 typeof(x.then) == 'function' &&
235 typeof(x.promise) == 'function');
236 };
237
238 this.deferrable = function()
239 {
240 if (this.isDeferred(arguments[0]))
241 return arguments[0];
242
243 var d = $.Deferred();
244 d.resolve.apply(d, arguments);
245
246 return d.promise();
247 };
248
249 this.i18n = {
250
251 loaded: false,
252 catalog: { },
253 plural: function(n) { return 0 + (n != 1) },
254
255 init: function() {
256 if (_luci2.i18n.loaded)
257 return;
258
259 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
261
262 for (var i = 0; i < langs.length; i++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
264 async: false,
265 cache: true,
266 dataType: 'json',
267 success: function(data) {
268 $.extend(_luci2.i18n.catalog, data);
269
270 var pe = _luci2.i18n.catalog[''];
271 if (pe)
272 {
273 delete _luci2.i18n.catalog[''];
274 try {
275 var pf = new Function('n', 'return 0 + (' + pe + ')');
276 _luci2.i18n.plural = pf;
277 } catch (e) { };
278 }
279 }
280 });
281
282 _luci2.i18n.loaded = true;
283 }
284
285 };
286
287 this.tr = function(msgid)
288 {
289 _luci2.i18n.init();
290
291 var msgstr = _luci2.i18n.catalog[msgid];
292
293 if (typeof(msgstr) == 'undefined')
294 return msgid;
295 else if (typeof(msgstr) == 'string')
296 return msgstr;
297 else
298 return msgstr[0];
299 };
300
301 this.trp = function(msgid, msgid_plural, count)
302 {
303 _luci2.i18n.init();
304
305 var msgstr = _luci2.i18n.catalog[msgid];
306
307 if (typeof(msgstr) == 'undefined')
308 return (count == 1) ? msgid : msgid_plural;
309 else if (typeof(msgstr) == 'string')
310 return msgstr;
311 else
312 return msgstr[_luci2.i18n.plural(count)];
313 };
314
315 this.trc = function(msgctx, msgid)
316 {
317 _luci2.i18n.init();
318
319 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
320
321 if (typeof(msgstr) == 'undefined')
322 return msgid;
323 else if (typeof(msgstr) == 'string')
324 return msgstr;
325 else
326 return msgstr[0];
327 };
328
329 this.trcp = function(msgctx, msgid, msgid_plural, count)
330 {
331 _luci2.i18n.init();
332
333 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
334
335 if (typeof(msgstr) == 'undefined')
336 return (count == 1) ? msgid : msgid_plural;
337 else if (typeof(msgstr) == 'string')
338 return msgstr;
339 else
340 return msgstr[_luci2.i18n.plural(count)];
341 };
342
343 this.setHash = function(key, value)
344 {
345 var h = '';
346 var data = this.getHash(undefined);
347
348 if (typeof(value) == 'undefined')
349 delete data[key];
350 else
351 data[key] = value;
352
353 var keys = [ ];
354 for (var k in data)
355 keys.push(k);
356
357 keys.sort();
358
359 for (var i = 0; i < keys.length; i++)
360 {
361 if (i > 0)
362 h += ',';
363
364 h += keys[i] + ':' + data[keys[i]];
365 }
366
367 if (h)
368 location.hash = '#' + h;
369 };
370
371 this.getHash = function(key)
372 {
373 var data = { };
374 var tuples = (location.hash || '#').substring(1).split(/,/);
375
376 for (var i = 0; i < tuples.length; i++)
377 {
378 var tuple = tuples[i].split(/:/);
379 if (tuple.length == 2)
380 data[tuple[0]] = tuple[1];
381 }
382
383 if (typeof(key) != 'undefined')
384 return data[key];
385
386 return data;
387 };
388
389 this.globals = {
390 timeout: 3000,
391 resource: '/luci2',
392 sid: '00000000000000000000000000000000'
393 };
394
395 this.rpc = {
396
397 _id: 1,
398 _batch: undefined,
399 _requests: { },
400
401 _call: function(req, cb)
402 {
403 return $.ajax('/ubus', {
404 cache: false,
405 contentType: 'application/json',
406 data: JSON.stringify(req),
407 dataType: 'json',
408 type: 'POST',
409 timeout: _luci2.globals.timeout
410 }).then(cb);
411 },
412
413 _list_cb: function(msg)
414 {
415 /* verify message frame */
416 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
417 throw 'Invalid JSON response';
418
419 return msg.result;
420 },
421
422 _call_cb: function(msg)
423 {
424 var data = [ ];
425 var type = Object.prototype.toString;
426
427 if (!$.isArray(msg))
428 msg = [ msg ];
429
430 for (var i = 0; i < msg.length; i++)
431 {
432 /* verify message frame */
433 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
434 throw 'Invalid JSON response';
435
436 /* fetch related request info */
437 var req = _luci2.rpc._requests[msg[i].id];
438 if (typeof(req) != 'object')
439 throw 'No related request for JSON response';
440
441 /* fetch response attribute and verify returned type */
442 var ret = undefined;
443
444 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
445 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
446
447 if (req.expect)
448 {
449 for (var key in req.expect)
450 {
451 if (typeof(ret) != 'undefined' && key != '')
452 ret = ret[key];
453
454 if (type.call(ret) != type.call(req.expect[key]))
455 ret = req.expect[key];
456
457 break;
458 }
459 }
460
461 /* apply filter */
462 if (typeof(req.filter) == 'function')
463 {
464 req.priv[0] = ret;
465 req.priv[1] = req.params;
466 ret = req.filter.apply(_luci2.rpc, req.priv);
467 }
468
469 /* store response data */
470 if (typeof(req.index) == 'number')
471 data[req.index] = ret;
472 else
473 data = ret;
474
475 /* delete request object */
476 delete _luci2.rpc._requests[msg[i].id];
477 }
478
479 return data;
480 },
481
482 list: function()
483 {
484 var params = [ ];
485 for (var i = 0; i < arguments.length; i++)
486 params[i] = arguments[i];
487
488 var msg = {
489 jsonrpc: '2.0',
490 id: this._id++,
491 method: 'list',
492 params: (params.length > 0) ? params : undefined
493 };
494
495 return this._call(msg, this._list_cb);
496 },
497
498 batch: function()
499 {
500 if (!$.isArray(this._batch))
501 this._batch = [ ];
502 },
503
504 flush: function()
505 {
506 if (!$.isArray(this._batch))
507 return _luci2.deferrable([ ]);
508
509 var req = this._batch;
510 delete this._batch;
511
512 /* call rpc */
513 return this._call(req, this._call_cb);
514 },
515
516 declare: function(options)
517 {
518 var _rpc = this;
519
520 return function() {
521 /* build parameter object */
522 var p_off = 0;
523 var params = { };
524 if ($.isArray(options.params))
525 for (p_off = 0; p_off < options.params.length; p_off++)
526 params[options.params[p_off]] = arguments[p_off];
527
528 /* all remaining arguments are private args */
529 var priv = [ undefined, undefined ];
530 for (; p_off < arguments.length; p_off++)
531 priv.push(arguments[p_off]);
532
533 /* store request info */
534 var req = _rpc._requests[_rpc._id] = {
535 expect: options.expect,
536 filter: options.filter,
537 params: params,
538 priv: priv
539 };
540
541 /* build message object */
542 var msg = {
543 jsonrpc: '2.0',
544 id: _rpc._id++,
545 method: 'call',
546 params: [
547 _luci2.globals.sid,
548 options.object,
549 options.method,
550 params
551 ]
552 };
553
554 /* when a batch is in progress then store index in request data
555 * and push message object onto the stack */
556 if ($.isArray(_rpc._batch))
557 {
558 req.index = _rpc._batch.push(msg) - 1;
559 return _luci2.deferrable(msg);
560 }
561
562 /* call rpc */
563 return _rpc._call(msg, _rpc._call_cb);
564 };
565 }
566 };
567
568 this.uci = {
569
570 writable: function()
571 {
572 return _luci2.session.access('ubus', 'uci', 'commit');
573 },
574
575 add: _luci2.rpc.declare({
576 object: 'uci',
577 method: 'add',
578 params: [ 'config', 'type', 'name', 'values' ],
579 expect: { section: '' }
580 }),
581
582 apply: function()
583 {
584
585 },
586
587 changes: _luci2.rpc.declare({
588 object: 'uci',
589 method: 'changes',
590 params: [ 'config' ],
591 expect: { changes: [ ] }
592 }),
593
594 commit: _luci2.rpc.declare({
595 object: 'uci',
596 method: 'commit',
597 params: [ 'config' ]
598 }),
599
600 _delete_one: _luci2.rpc.declare({
601 object: 'uci',
602 method: 'delete',
603 params: [ 'config', 'section', 'option' ]
604 }),
605
606 _delete_multiple: _luci2.rpc.declare({
607 object: 'uci',
608 method: 'delete',
609 params: [ 'config', 'section', 'options' ]
610 }),
611
612 'delete': function(config, section, option)
613 {
614 if ($.isArray(option))
615 return this._delete_multiple(config, section, option);
616 else
617 return this._delete_one(config, section, option);
618 },
619
620 delete_all: _luci2.rpc.declare({
621 object: 'uci',
622 method: 'delete',
623 params: [ 'config', 'type', 'match' ]
624 }),
625
626 _foreach: _luci2.rpc.declare({
627 object: 'uci',
628 method: 'get',
629 params: [ 'config', 'type' ],
630 expect: { values: { } }
631 }),
632
633 foreach: function(config, type, cb)
634 {
635 return this._foreach(config, type).then(function(sections) {
636 for (var s in sections)
637 cb(sections[s]);
638 });
639 },
640
641 get: _luci2.rpc.declare({
642 object: 'uci',
643 method: 'get',
644 params: [ 'config', 'section', 'option' ],
645 expect: { '': { } },
646 filter: function(data, params) {
647 if (typeof(params.option) == 'undefined')
648 return data.values ? data.values['.type'] : undefined;
649 else
650 return data.value;
651 }
652 }),
653
654 get_all: _luci2.rpc.declare({
655 object: 'uci',
656 method: 'get',
657 params: [ 'config', 'section' ],
658 expect: { values: { } },
659 filter: function(data, params) {
660 if (typeof(params.section) == 'string')
661 data['.section'] = params.section;
662 else if (typeof(params.config) == 'string')
663 data['.package'] = params.config;
664 return data;
665 }
666 }),
667
668 get_first: function(config, type, option)
669 {
670 return this._foreach(config, type).then(function(sections) {
671 for (var s in sections)
672 {
673 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
674
675 if (typeof(val) != 'undefined')
676 return val;
677 }
678
679 return undefined;
680 });
681 },
682
683 section: _luci2.rpc.declare({
684 object: 'uci',
685 method: 'add',
686 params: [ 'config', 'type', 'name', 'values' ],
687 expect: { section: '' }
688 }),
689
690 _set: _luci2.rpc.declare({
691 object: 'uci',
692 method: 'set',
693 params: [ 'config', 'section', 'values' ]
694 }),
695
696 set: function(config, section, option, value)
697 {
698 if (typeof(value) == 'undefined' && typeof(option) == 'string')
699 return this.section(config, section, option); /* option -> type */
700 else if ($.isPlainObject(option))
701 return this._set(config, section, option); /* option -> values */
702
703 var values = { };
704 values[option] = value;
705
706 return this._set(config, section, values);
707 },
708
709 order: _luci2.rpc.declare({
710 object: 'uci',
711 method: 'order',
712 params: [ 'config', 'sections' ]
713 })
714 };
715
716 this.network = {
717 listNetworkNames: function() {
718 return _luci2.rpc.list('network.interface.*').then(function(list) {
719 var names = [ ];
720 for (var name in list)
721 if (name != 'network.interface.loopback')
722 names.push(name.substring(18));
723 names.sort();
724 return names;
725 });
726 },
727
728 listDeviceNames: _luci2.rpc.declare({
729 object: 'network.device',
730 method: 'status',
731 expect: { '': { } },
732 filter: function(data) {
733 var names = [ ];
734 for (var name in data)
735 if (name != 'lo')
736 names.push(name);
737 names.sort();
738 return names;
739 }
740 }),
741
742 getNetworkStatus: function()
743 {
744 var nets = [ ];
745 var devs = { };
746
747 return this.listNetworkNames().then(function(names) {
748 _luci2.rpc.batch();
749
750 for (var i = 0; i < names.length; i++)
751 _luci2.network.getInterfaceStatus(names[i]);
752
753 return _luci2.rpc.flush();
754 }).then(function(networks) {
755 for (var i = 0; i < networks.length; i++)
756 {
757 var net = nets[i] = networks[i];
758 var dev = net.l3_device || net.l2_device;
759 if (dev)
760 net.device = devs[dev] = { };
761 }
762
763 _luci2.rpc.batch();
764
765 for (var dev in devs)
766 _luci2.network.listDeviceNamestatus(dev);
767
768 return _luci2.rpc.flush();
769 }).then(function(devices) {
770 _luci2.rpc.batch();
771
772 for (var i = 0; i < devices.length; i++)
773 {
774 var brm = devices[i]['bridge-members'];
775 delete devices[i]['bridge-members'];
776
777 $.extend(devs[devices[i]['device']], devices[i]);
778
779 if (!brm)
780 continue;
781
782 devs[devices[i]['device']].subdevices = [ ];
783
784 for (var j = 0; j < brm.length; j++)
785 {
786 if (!devs[brm[j]])
787 {
788 devs[brm[j]] = { };
789 _luci2.network.listDeviceNamestatus(brm[j]);
790 }
791
792 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
793 }
794 }
795
796 return _luci2.rpc.flush();
797 }).then(function(subdevices) {
798 for (var i = 0; i < subdevices.length; i++)
799 $.extend(devs[subdevices[i]['device']], subdevices[i]);
800
801 _luci2.rpc.batch();
802
803 for (var dev in devs)
804 _luci2.wireless.getDeviceStatus(dev);
805
806 return _luci2.rpc.flush();
807 }).then(function(wifidevices) {
808 for (var i = 0; i < wifidevices.length; i++)
809 if (wifidevices[i])
810 devs[wifidevices[i]['device']].wireless = wifidevices[i];
811
812 nets.sort(function(a, b) {
813 if (a['interface'] < b['interface'])
814 return -1;
815 else if (a['interface'] > b['interface'])
816 return 1;
817 else
818 return 0;
819 });
820
821 return nets;
822 });
823 },
824
825 findWanInterfaces: function(cb)
826 {
827 return this.listNetworkNames().then(function(names) {
828 _luci2.rpc.batch();
829
830 for (var i = 0; i < names.length; i++)
831 _luci2.network.getInterfaceStatus(names[i]);
832
833 return _luci2.rpc.flush();
834 }).then(function(interfaces) {
835 var rv = [ undefined, undefined ];
836
837 for (var i = 0; i < interfaces.length; i++)
838 {
839 for (var j = 0; j < interfaces[i].route.length; j++)
840 {
841 var rt = interfaces[i].route[j];
842
843 if (typeof(rt.table) != 'undefined')
844 continue;
845
846 if (rt.target == '0.0.0.0' && rt.mask == 0)
847 rv[0] = interfaces[i];
848 else if (rt.target == '::' && rt.mask == 0)
849 rv[1] = interfaces[i];
850 }
851 }
852
853 return rv;
854 });
855 },
856
857 getDHCPLeases: _luci2.rpc.declare({
858 object: 'luci2.network',
859 method: 'dhcp_leases',
860 expect: { leases: [ ] }
861 }),
862
863 getDHCPv6Leases: _luci2.rpc.declare({
864 object: 'luci2.network',
865 method: 'dhcp6_leases',
866 expect: { leases: [ ] }
867 }),
868
869 getRoutes: _luci2.rpc.declare({
870 object: 'luci2.network',
871 method: 'routes',
872 expect: { routes: [ ] }
873 }),
874
875 getIPv6Routes: _luci2.rpc.declare({
876 object: 'luci2.network',
877 method: 'routes',
878 expect: { routes: [ ] }
879 }),
880
881 getARPTable: _luci2.rpc.declare({
882 object: 'luci2.network',
883 method: 'arp_table',
884 expect: { entries: [ ] }
885 }),
886
887 getInterfaceStatus: _luci2.rpc.declare({
888 object: 'network.interface',
889 method: 'status',
890 params: [ 'interface' ],
891 expect: { '': { } },
892 filter: function(data, params) {
893 data['interface'] = params['interface'];
894 data['l2_device'] = data['device'];
895 delete data['device'];
896 return data;
897 }
898 }),
899
900 listDeviceNamestatus: _luci2.rpc.declare({
901 object: 'network.device',
902 method: 'status',
903 params: [ 'name' ],
904 expect: { '': { } },
905 filter: function(data, params) {
906 data['device'] = params['name'];
907 return data;
908 }
909 }),
910
911 getConntrackCount: _luci2.rpc.declare({
912 object: 'luci2.network',
913 method: 'conntrack_count',
914 expect: { '': { count: 0, limit: 0 } }
915 })
916 };
917
918 this.wireless = {
919 listDeviceNames: _luci2.rpc.declare({
920 object: 'iwinfo',
921 method: 'devices',
922 expect: { 'devices': [ ] },
923 filter: function(data) {
924 data.sort();
925 return data;
926 }
927 }),
928
929 getDeviceStatus: _luci2.rpc.declare({
930 object: 'iwinfo',
931 method: 'info',
932 params: [ 'device' ],
933 expect: { '': { } },
934 filter: function(data, params) {
935 if (!$.isEmptyObject(data))
936 {
937 data['device'] = params['device'];
938 return data;
939 }
940 return undefined;
941 }
942 }),
943
944 getAssocList: _luci2.rpc.declare({
945 object: 'iwinfo',
946 method: 'assoclist',
947 params: [ 'device' ],
948 expect: { results: [ ] },
949 filter: function(data, params) {
950 for (var i = 0; i < data.length; i++)
951 data[i]['device'] = params['device'];
952
953 data.sort(function(a, b) {
954 if (a.bssid < b.bssid)
955 return -1;
956 else if (a.bssid > b.bssid)
957 return 1;
958 else
959 return 0;
960 });
961
962 return data;
963 }
964 }),
965
966 getWirelessStatus: function() {
967 return this.listDeviceNames().then(function(names) {
968 _luci2.rpc.batch();
969
970 for (var i = 0; i < names.length; i++)
971 _luci2.wireless.getDeviceStatus(names[i]);
972
973 return _luci2.rpc.flush();
974 }).then(function(networks) {
975 var rv = { };
976
977 var phy_attrs = [
978 'country', 'channel', 'frequency', 'frequency_offset',
979 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
980 ];
981
982 var net_attrs = [
983 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
984 'signal', 'noise', 'bitrate', 'encryption'
985 ];
986
987 for (var i = 0; i < networks.length; i++)
988 {
989 var phy = rv[networks[i].phy] || (
990 rv[networks[i].phy] = { networks: [ ] }
991 );
992
993 var net = {
994 device: networks[i].device
995 };
996
997 for (var j = 0; j < phy_attrs.length; j++)
998 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
999
1000 for (var j = 0; j < net_attrs.length; j++)
1001 net[net_attrs[j]] = networks[i][net_attrs[j]];
1002
1003 phy.networks.push(net);
1004 }
1005
1006 return rv;
1007 });
1008 },
1009
1010 getAssocLists: function()
1011 {
1012 return this.listDeviceNames().then(function(names) {
1013 _luci2.rpc.batch();
1014
1015 for (var i = 0; i < names.length; i++)
1016 _luci2.wireless.getAssocList(names[i]);
1017
1018 return _luci2.rpc.flush();
1019 }).then(function(assoclists) {
1020 var rv = [ ];
1021
1022 for (var i = 0; i < assoclists.length; i++)
1023 for (var j = 0; j < assoclists[i].length; j++)
1024 rv.push(assoclists[i][j]);
1025
1026 return rv;
1027 });
1028 },
1029
1030 formatEncryption: function(enc)
1031 {
1032 var format_list = function(l, s)
1033 {
1034 var rv = [ ];
1035 for (var i = 0; i < l.length; i++)
1036 rv.push(l[i].toUpperCase());
1037 return rv.join(s ? s : ', ');
1038 }
1039
1040 if (!enc || !enc.enabled)
1041 return _luci2.tr('None');
1042
1043 if (enc.wep)
1044 {
1045 if (enc.wep.length == 2)
1046 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1047 else if (enc.wep[0] == 'shared')
1048 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1049 else
1050 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1051 }
1052 else if (enc.wpa)
1053 {
1054 if (enc.wpa.length == 2)
1055 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1056 format_list(enc.authentication, '/'),
1057 format_list(enc.ciphers, ', ')
1058 );
1059 else if (enc.wpa[0] == 2)
1060 return 'WPA2 %s (%s)'.format(
1061 format_list(enc.authentication, '/'),
1062 format_list(enc.ciphers, ', ')
1063 );
1064 else
1065 return 'WPA %s (%s)'.format(
1066 format_list(enc.authentication, '/'),
1067 format_list(enc.ciphers, ', ')
1068 );
1069 }
1070
1071 return _luci2.tr('Unknown');
1072 }
1073 };
1074
1075 this.system = {
1076 getSystemInfo: _luci2.rpc.declare({
1077 object: 'system',
1078 method: 'info',
1079 expect: { '': { } }
1080 }),
1081
1082 getBoardInfo: _luci2.rpc.declare({
1083 object: 'system',
1084 method: 'board',
1085 expect: { '': { } }
1086 }),
1087
1088 getDiskInfo: _luci2.rpc.declare({
1089 object: 'luci2.system',
1090 method: 'diskfree',
1091 expect: { '': { } }
1092 }),
1093
1094 getInfo: function(cb)
1095 {
1096 _luci2.rpc.batch();
1097
1098 this.getSystemInfo();
1099 this.getBoardInfo();
1100 this.getDiskInfo();
1101
1102 return _luci2.rpc.flush().then(function(info) {
1103 var rv = { };
1104
1105 $.extend(rv, info[0]);
1106 $.extend(rv, info[1]);
1107 $.extend(rv, info[2]);
1108
1109 return rv;
1110 });
1111 },
1112
1113 getProcessList: _luci2.rpc.declare({
1114 object: 'luci2.system',
1115 method: 'process_list',
1116 expect: { processes: [ ] },
1117 filter: function(data) {
1118 data.sort(function(a, b) { return a.pid - b.pid });
1119 return data;
1120 }
1121 }),
1122
1123 getSystemLog: _luci2.rpc.declare({
1124 object: 'luci2.system',
1125 method: 'syslog',
1126 expect: { log: '' }
1127 }),
1128
1129 getKernelLog: _luci2.rpc.declare({
1130 object: 'luci2.system',
1131 method: 'dmesg',
1132 expect: { log: '' }
1133 }),
1134
1135 getZoneInfo: function(cb)
1136 {
1137 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1138 },
1139
1140 sendSignal: _luci2.rpc.declare({
1141 object: 'luci2.system',
1142 method: 'process_signal',
1143 params: [ 'pid', 'signal' ],
1144 filter: function(data) {
1145 return (data == 0);
1146 }
1147 }),
1148
1149 initList: _luci2.rpc.declare({
1150 object: 'luci2.system',
1151 method: 'init_list',
1152 expect: { initscripts: [ ] },
1153 filter: function(data) {
1154 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1155 return data;
1156 }
1157 }),
1158
1159 initEnabled: function(init, cb)
1160 {
1161 return this.initList().then(function(list) {
1162 for (var i = 0; i < list.length; i++)
1163 if (list[i].name == init)
1164 return !!list[i].enabled;
1165
1166 return false;
1167 });
1168 },
1169
1170 initRun: _luci2.rpc.declare({
1171 object: 'luci2.system',
1172 method: 'init_action',
1173 params: [ 'name', 'action' ],
1174 filter: function(data) {
1175 return (data == 0);
1176 }
1177 }),
1178
1179 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1180 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1181 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1182 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1183 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1184 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1185
1186
1187 getRcLocal: _luci2.rpc.declare({
1188 object: 'luci2.system',
1189 method: 'rclocal_get',
1190 expect: { data: '' }
1191 }),
1192
1193 setRcLocal: _luci2.rpc.declare({
1194 object: 'luci2.system',
1195 method: 'rclocal_set',
1196 params: [ 'data' ]
1197 }),
1198
1199
1200 getCrontab: _luci2.rpc.declare({
1201 object: 'luci2.system',
1202 method: 'crontab_get',
1203 expect: { data: '' }
1204 }),
1205
1206 setCrontab: _luci2.rpc.declare({
1207 object: 'luci2.system',
1208 method: 'crontab_set',
1209 params: [ 'data' ]
1210 }),
1211
1212
1213 getSSHKeys: _luci2.rpc.declare({
1214 object: 'luci2.system',
1215 method: 'sshkeys_get',
1216 expect: { keys: [ ] }
1217 }),
1218
1219 setSSHKeys: _luci2.rpc.declare({
1220 object: 'luci2.system',
1221 method: 'sshkeys_set',
1222 params: [ 'keys' ]
1223 }),
1224
1225
1226 setPassword: _luci2.rpc.declare({
1227 object: 'luci2.system',
1228 method: 'password_set',
1229 params: [ 'user', 'password' ]
1230 }),
1231
1232
1233 listLEDs: _luci2.rpc.declare({
1234 object: 'luci2.system',
1235 method: 'led_list',
1236 expect: { leds: [ ] }
1237 }),
1238
1239 listUSBDevices: _luci2.rpc.declare({
1240 object: 'luci2.system',
1241 method: 'usb_list',
1242 expect: { devices: [ ] }
1243 }),
1244
1245
1246 testUpgrade: _luci2.rpc.declare({
1247 object: 'luci2.system',
1248 method: 'upgrade_test',
1249 expect: { '': { } }
1250 }),
1251
1252 startUpgrade: _luci2.rpc.declare({
1253 object: 'luci2.system',
1254 method: 'upgrade_start',
1255 params: [ 'keep' ]
1256 }),
1257
1258 cleanUpgrade: _luci2.rpc.declare({
1259 object: 'luci2.system',
1260 method: 'upgrade_clean'
1261 }),
1262
1263
1264 restoreBackup: _luci2.rpc.declare({
1265 object: 'luci2.system',
1266 method: 'backup_restore'
1267 }),
1268
1269 cleanBackup: _luci2.rpc.declare({
1270 object: 'luci2.system',
1271 method: 'backup_clean'
1272 }),
1273
1274
1275 getBackupConfig: _luci2.rpc.declare({
1276 object: 'luci2.system',
1277 method: 'backup_config_get',
1278 expect: { config: '' }
1279 }),
1280
1281 setBackupConfig: _luci2.rpc.declare({
1282 object: 'luci2.system',
1283 method: 'backup_config_set',
1284 params: [ 'data' ]
1285 }),
1286
1287
1288 listBackup: _luci2.rpc.declare({
1289 object: 'luci2.system',
1290 method: 'backup_list',
1291 expect: { files: [ ] }
1292 }),
1293
1294
1295 performReboot: _luci2.rpc.declare({
1296 object: 'luci2.system',
1297 method: 'reboot'
1298 })
1299 };
1300
1301 this.opkg = {
1302 updateLists: _luci2.rpc.declare({
1303 object: 'luci2.opkg',
1304 method: 'update',
1305 expect: { '': { } }
1306 }),
1307
1308 _allPackages: _luci2.rpc.declare({
1309 object: 'luci2.opkg',
1310 method: 'list',
1311 params: [ 'offset', 'limit', 'pattern' ],
1312 expect: { '': { } }
1313 }),
1314
1315 _installedPackages: _luci2.rpc.declare({
1316 object: 'luci2.opkg',
1317 method: 'list_installed',
1318 params: [ 'offset', 'limit', 'pattern' ],
1319 expect: { '': { } }
1320 }),
1321
1322 _findPackages: _luci2.rpc.declare({
1323 object: 'luci2.opkg',
1324 method: 'find',
1325 params: [ 'offset', 'limit', 'pattern' ],
1326 expect: { '': { } }
1327 }),
1328
1329 _fetchPackages: function(action, offset, limit, pattern)
1330 {
1331 var packages = [ ];
1332
1333 return action(offset, limit, pattern).then(function(list) {
1334 if (!list.total || !list.packages)
1335 return { length: 0, total: 0 };
1336
1337 packages.push.apply(packages, list.packages);
1338 packages.total = list.total;
1339
1340 if (limit <= 0)
1341 limit = list.total;
1342
1343 if (packages.length >= limit)
1344 return packages;
1345
1346 _luci2.rpc.batch();
1347
1348 for (var i = offset + packages.length; i < limit; i += 100)
1349 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1350
1351 return _luci2.rpc.flush();
1352 }).then(function(lists) {
1353 for (var i = 0; i < lists.length; i++)
1354 {
1355 if (!lists[i].total || !lists[i].packages)
1356 continue;
1357
1358 packages.push.apply(packages, lists[i].packages);
1359 packages.total = lists[i].total;
1360 }
1361
1362 return packages;
1363 });
1364 },
1365
1366 listPackages: function(offset, limit, pattern)
1367 {
1368 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1369 },
1370
1371 installedPackages: function(offset, limit, pattern)
1372 {
1373 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1374 },
1375
1376 findPackages: function(offset, limit, pattern)
1377 {
1378 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1379 },
1380
1381 installPackage: _luci2.rpc.declare({
1382 object: 'luci2.opkg',
1383 method: 'install',
1384 params: [ 'package' ],
1385 expect: { '': { } }
1386 }),
1387
1388 removePackage: _luci2.rpc.declare({
1389 object: 'luci2.opkg',
1390 method: 'remove',
1391 params: [ 'package' ],
1392 expect: { '': { } }
1393 }),
1394
1395 getConfig: _luci2.rpc.declare({
1396 object: 'luci2.opkg',
1397 method: 'config_get',
1398 expect: { config: '' }
1399 }),
1400
1401 setConfig: _luci2.rpc.declare({
1402 object: 'luci2.opkg',
1403 method: 'config_set',
1404 params: [ 'data' ]
1405 })
1406 };
1407
1408 this.session = {
1409
1410 login: _luci2.rpc.declare({
1411 object: 'session',
1412 method: 'login',
1413 params: [ 'username', 'password' ],
1414 expect: { '': { } }
1415 }),
1416
1417 access: _luci2.rpc.declare({
1418 object: 'session',
1419 method: 'access',
1420 params: [ 'scope', 'object', 'function' ],
1421 expect: { access: false }
1422 }),
1423
1424 isAlive: function()
1425 {
1426 return _luci2.session.access('ubus', 'session', 'access');
1427 },
1428
1429 startHeartbeat: function()
1430 {
1431 this._hearbeatInterval = window.setInterval(function() {
1432 _luci2.session.isAlive(function(alive) {
1433 if (!alive)
1434 {
1435 _luci2.session.stopHeartbeat();
1436 _luci2.ui.login(true);
1437 }
1438
1439 });
1440 }, _luci2.globals.timeout * 2);
1441 },
1442
1443 stopHeartbeat: function()
1444 {
1445 if (typeof(this._hearbeatInterval) != 'undefined')
1446 window.clearInterval(this._hearbeatInterval);
1447 }
1448 };
1449
1450 this.ui = {
1451
1452 loading: function(enable)
1453 {
1454 var win = $(window);
1455 var body = $('body');
1456 var div = _luci2._modal || (
1457 _luci2._modal = $('<div />')
1458 .addClass('cbi-modal-loader')
1459 .append($('<div />').text(_luci2.tr('Loading data...')))
1460 .appendTo(body)
1461 );
1462
1463 if (enable)
1464 {
1465 body.css('overflow', 'hidden');
1466 body.css('padding', 0);
1467 body.css('width', win.width());
1468 body.css('height', win.height());
1469 div.css('width', win.width());
1470 div.css('height', win.height());
1471 div.show();
1472 }
1473 else
1474 {
1475 div.hide();
1476 body.css('overflow', '');
1477 body.css('padding', '');
1478 body.css('width', '');
1479 body.css('height', '');
1480 }
1481 },
1482
1483 dialog: function(title, content, options)
1484 {
1485 var win = $(window);
1486 var body = $('body');
1487 var div = _luci2._dialog || (
1488 _luci2._dialog = $('<div />')
1489 .addClass('cbi-modal-dialog')
1490 .append($('<div />')
1491 .append($('<div />')
1492 .addClass('cbi-modal-dialog-header'))
1493 .append($('<div />')
1494 .addClass('cbi-modal-dialog-body'))
1495 .append($('<div />')
1496 .addClass('cbi-modal-dialog-footer')
1497 .append($('<button />')
1498 .addClass('cbi-button')
1499 .text(_luci2.tr('Close'))
1500 .click(function() {
1501 $('body')
1502 .css('overflow', '')
1503 .css('padding', '')
1504 .css('width', '')
1505 .css('height', '');
1506
1507 $(this).parent().parent().parent().hide();
1508 }))))
1509 .appendTo(body)
1510 );
1511
1512 if (typeof(options) != 'object')
1513 options = { };
1514
1515 if (title === false)
1516 {
1517 body
1518 .css('overflow', '')
1519 .css('padding', '')
1520 .css('width', '')
1521 .css('height', '');
1522
1523 _luci2._dialog.hide();
1524
1525 return;
1526 }
1527
1528 var cnt = div.children().children('div.cbi-modal-dialog-body');
1529 var ftr = div.children().children('div.cbi-modal-dialog-footer');
1530
1531 ftr.empty();
1532
1533 if (options.style == 'confirm')
1534 {
1535 ftr.append($('<button />')
1536 .addClass('cbi-button')
1537 .text(_luci2.tr('Ok'))
1538 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1539
1540 ftr.append($('<button />')
1541 .addClass('cbi-button')
1542 .text(_luci2.tr('Cancel'))
1543 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1544 }
1545 else if (options.style == 'close')
1546 {
1547 ftr.append($('<button />')
1548 .addClass('cbi-button')
1549 .text(_luci2.tr('Close'))
1550 .click(options.close || function() { _luci2.ui.dialog(false) }));
1551 }
1552 else if (options.style == 'wait')
1553 {
1554 ftr.append($('<button />')
1555 .addClass('cbi-button')
1556 .text(_luci2.tr('Close'))
1557 .attr('disabled', true));
1558 }
1559
1560 div.find('div.cbi-modal-dialog-header').text(title);
1561 div.show();
1562
1563 cnt
1564 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1565 .empty()
1566 .append(content);
1567
1568 div.children()
1569 .css('margin-top', -Math.floor(div.children().height() / 2) + 'px');
1570
1571 body.css('overflow', 'hidden');
1572 body.css('padding', 0);
1573 body.css('width', win.width());
1574 body.css('height', win.height());
1575 div.css('width', win.width());
1576 div.css('height', win.height());
1577 },
1578
1579 upload: function(title, content, options)
1580 {
1581 var form = _luci2._upload || (
1582 _luci2._upload = $('<form />')
1583 .attr('method', 'post')
1584 .attr('action', '/cgi-bin/luci-upload')
1585 .attr('enctype', 'multipart/form-data')
1586 .attr('target', 'cbi-fileupload-frame')
1587 .append($('<p />'))
1588 .append($('<input />')
1589 .attr('type', 'hidden')
1590 .attr('name', 'sessionid')
1591 .attr('value', _luci2.globals.sid))
1592 .append($('<input />')
1593 .attr('type', 'hidden')
1594 .attr('name', 'filename')
1595 .attr('value', options.filename))
1596 .append($('<input />')
1597 .attr('type', 'file')
1598 .attr('name', 'filedata')
1599 .addClass('cbi-input-file'))
1600 .append($('<div />')
1601 .css('width', '100%')
1602 .addClass('progressbar')
1603 .addClass('intermediate')
1604 .append($('<div />')
1605 .css('width', '100%')))
1606 .append($('<iframe />')
1607 .attr('name', 'cbi-fileupload-frame')
1608 .css('width', '1px')
1609 .css('height', '1px')
1610 .css('visibility', 'hidden'))
1611 );
1612
1613 var finish = _luci2._upload_finish_cb || (
1614 _luci2._upload_finish_cb = function(ev) {
1615 $(this).off('load');
1616
1617 var body = (this.contentDocument || this.contentWindow.document).body;
1618 if (body.firstChild.tagName.toLowerCase() == 'pre')
1619 body = body.firstChild;
1620
1621 var json;
1622 try {
1623 json = $.parseJSON(body.innerHTML);
1624 } catch(e) {
1625 json = {
1626 message: _luci2.tr('Invalid server response received'),
1627 error: [ -1, _luci2.tr('Invalid data') ]
1628 };
1629 };
1630
1631 if (json.error)
1632 {
1633 L.ui.dialog(L.tr('File upload'), [
1634 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1635 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1636 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1637 ], { style: 'close' });
1638 }
1639 else if (typeof(ev.data.cb) == 'function')
1640 {
1641 ev.data.cb(json);
1642 }
1643 }
1644 );
1645
1646 var confirm = _luci2._upload_confirm_cb || (
1647 _luci2._upload_confirm_cb = function() {
1648 var d = _luci2._upload;
1649 var f = d.find('.cbi-input-file');
1650 var b = d.find('.progressbar');
1651 var p = d.find('p');
1652
1653 if (!f.val())
1654 return;
1655
1656 d.find('iframe').on('load', { cb: options.success }, finish);
1657 d.submit();
1658
1659 f.hide();
1660 b.show();
1661 p.text(_luci2.tr('File upload in progress …'));
1662
1663 _luci2._dialog.find('button').prop('disabled', true);
1664 }
1665 );
1666
1667 _luci2._upload.find('.progressbar').hide();
1668 _luci2._upload.find('.cbi-input-file').val('').show();
1669 _luci2._upload.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1670
1671 _luci2.ui.dialog(title || _luci2.tr('File upload'), _luci2._upload, {
1672 style: 'confirm',
1673 confirm: confirm
1674 });
1675 },
1676
1677 reconnect: function()
1678 {
1679 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1680 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1681 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1682 var images = $();
1683 var interval, timeout;
1684
1685 _luci2.ui.dialog(
1686 _luci2.tr('Waiting for device'), [
1687 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1688 $('<div />')
1689 .css('width', '100%')
1690 .addClass('progressbar')
1691 .addClass('intermediate')
1692 .append($('<div />')
1693 .css('width', '100%'))
1694 ], { style: 'wait' }
1695 );
1696
1697 for (var i = 0; i < protocols.length; i++)
1698 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1699
1700 //_luci2.network.getNetworkStatus(function(s) {
1701 // for (var i = 0; i < protocols.length; i++)
1702 // {
1703 // for (var j = 0; j < s.length; j++)
1704 // {
1705 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1706 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1707 //
1708 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1709 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1710 // }
1711 // }
1712 //}).then(function() {
1713 images.on('load', function() {
1714 var url = this.getAttribute('url');
1715 _luci2.session.isAlive().then(function(access) {
1716 if (access)
1717 {
1718 window.clearTimeout(timeout);
1719 window.clearInterval(interval);
1720 _luci2.ui.dialog(false);
1721 images = null;
1722 }
1723 else
1724 {
1725 location.href = url;
1726 }
1727 });
1728 });
1729
1730 interval = window.setInterval(function() {
1731 images.each(function() {
1732 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1733 });
1734 }, 5000);
1735
1736 timeout = window.setTimeout(function() {
1737 window.clearInterval(interval);
1738 images.off('load');
1739
1740 _luci2.ui.dialog(
1741 _luci2.tr('Device not responding'),
1742 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1743 { style: 'close' }
1744 );
1745 }, 180000);
1746 //});
1747 },
1748
1749 login: function(invalid)
1750 {
1751 if (!_luci2._login_deferred || _luci2._login_deferred.state() != 'pending')
1752 _luci2._login_deferred = $.Deferred();
1753
1754 /* try to find sid from hash */
1755 var sid = _luci2.getHash('id');
1756 if (sid && sid.match(/^[a-f0-9]{32}$/))
1757 {
1758 _luci2.globals.sid = sid;
1759 _luci2.session.isAlive().then(function(access) {
1760 if (access)
1761 {
1762 _luci2._login_deferred.resolve();
1763 }
1764 else
1765 {
1766 _luci2.setHash('id', undefined);
1767 _luci2.ui.login();
1768 }
1769 });
1770
1771 return _luci2._login_deferred;
1772 }
1773
1774 var form = _luci2._login || (
1775 _luci2._login = $('<div />')
1776 .append($('<p />')
1777 .addClass('alert-message')
1778 .text(_luci2.tr('Wrong username or password given!')))
1779 .append($('<p />')
1780 .append($('<label />')
1781 .text(_luci2.tr('Username'))
1782 .append($('<br />'))
1783 .append($('<input />')
1784 .attr('type', 'text')
1785 .attr('name', 'username')
1786 .attr('value', 'root')
1787 .addClass('cbi-input-text'))))
1788 .append($('<p />')
1789 .append($('<label />')
1790 .text(_luci2.tr('Password'))
1791 .append($('<br />'))
1792 .append($('<input />')
1793 .attr('type', 'password')
1794 .attr('name', 'password')
1795 .addClass('cbi-input-password'))))
1796 .append($('<p />')
1797 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok'))))
1798 );
1799
1800 var response_cb = _luci2._login_response_cb || (
1801 _luci2._login_response_cb = function(response) {
1802 if (!response.ubus_rpc_session)
1803 {
1804 _luci2.ui.login(true);
1805 }
1806 else
1807 {
1808 _luci2.globals.sid = response.ubus_rpc_session;
1809 _luci2.setHash('id', _luci2.globals.sid);
1810 _luci2.session.startHeartbeat();
1811 _luci2.ui.dialog(false);
1812 _luci2._login_deferred.resolve();
1813 }
1814 }
1815 );
1816
1817 var confirm_cb = _luci2._login_confirm_cb || (
1818 _luci2._login_confirm_cb = function() {
1819 var d = _luci2._login;
1820 var u = d.find('[name=username]').val();
1821 var p = d.find('[name=password]').val();
1822
1823 if (!u)
1824 return;
1825
1826 _luci2.ui.dialog(
1827 _luci2.tr('Logging in'), [
1828 $('<p />').text(_luci2.tr('Log in in progress …')),
1829 $('<div />')
1830 .css('width', '100%')
1831 .addClass('progressbar')
1832 .addClass('intermediate')
1833 .append($('<div />')
1834 .css('width', '100%'))
1835 ], { style: 'wait' }
1836 );
1837
1838 _luci2.globals.sid = '00000000000000000000000000000000';
1839 _luci2.session.login(u, p).then(response_cb);
1840 }
1841 );
1842
1843 if (invalid)
1844 form.find('.alert-message').show();
1845 else
1846 form.find('.alert-message').hide();
1847
1848 _luci2.ui.dialog(_luci2.tr('Authorization Required'), form, {
1849 style: 'confirm',
1850 confirm: confirm_cb
1851 });
1852
1853 return _luci2._login_deferred;
1854 },
1855
1856
1857 _acl_merge_scope: function(acl_scope, scope)
1858 {
1859 if ($.isArray(scope))
1860 {
1861 for (var i = 0; i < scope.length; i++)
1862 acl_scope[scope[i]] = true;
1863 }
1864 else if ($.isPlainObject(scope))
1865 {
1866 for (var object_name in scope)
1867 {
1868 if (!$.isArray(scope[object_name]))
1869 continue;
1870
1871 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
1872
1873 for (var i = 0; i < scope[object_name].length; i++)
1874 acl_object[scope[object_name][i]] = true;
1875 }
1876 }
1877 },
1878
1879 _acl_merge_permission: function(acl_perm, perm)
1880 {
1881 if ($.isPlainObject(perm))
1882 {
1883 for (var scope_name in perm)
1884 {
1885 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
1886 this._acl_merge_scope(acl_scope, perm[scope_name]);
1887 }
1888 }
1889 },
1890
1891 _acl_merge_group: function(acl_group, group)
1892 {
1893 if ($.isPlainObject(group))
1894 {
1895 if (!acl_group.description)
1896 acl_group.description = group.description;
1897
1898 if (group.read)
1899 {
1900 var acl_perm = acl_group.read || (acl_group.read = { });
1901 this._acl_merge_permission(acl_perm, group.read);
1902 }
1903
1904 if (group.write)
1905 {
1906 var acl_perm = acl_group.write || (acl_group.write = { });
1907 this._acl_merge_permission(acl_perm, group.write);
1908 }
1909 }
1910 },
1911
1912 _acl_merge_tree: function(acl_tree, tree)
1913 {
1914 if ($.isPlainObject(tree))
1915 {
1916 for (var group_name in tree)
1917 {
1918 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
1919 this._acl_merge_group(acl_group, tree[group_name]);
1920 }
1921 }
1922 },
1923
1924 listAvailableACLs: _luci2.rpc.declare({
1925 object: 'luci2.ui',
1926 method: 'acls',
1927 expect: { acls: [ ] },
1928 filter: function(trees) {
1929 var acl_tree = { };
1930 for (var i = 0; i < trees.length; i++)
1931 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
1932 return acl_tree;
1933 }
1934 }),
1935
1936 renderMainMenu: _luci2.rpc.declare({
1937 object: 'luci2.ui',
1938 method: 'menu',
1939 expect: { menu: { } },
1940 filter: function(entries) {
1941 _luci2.globals.mainMenu = new _luci2.ui.menu();
1942 _luci2.globals.mainMenu.entries(entries);
1943
1944 $('#mainmenu')
1945 .empty()
1946 .append(_luci2.globals.mainMenu.render(0, 1));
1947 }
1948 }),
1949
1950 renderViewMenu: function()
1951 {
1952 $('#viewmenu')
1953 .empty()
1954 .append(_luci2.globals.mainMenu.render(2, 900));
1955 },
1956
1957 renderView: function(node)
1958 {
1959 var name = node.view.split(/\//).join('.');
1960
1961 _luci2.ui.renderViewMenu();
1962
1963 if (!_luci2._views)
1964 _luci2._views = { };
1965
1966 _luci2.setHash('view', node.view);
1967
1968 if (_luci2._views[name] instanceof _luci2.ui.view)
1969 return _luci2._views[name].render();
1970
1971 return $.ajax(_luci2.globals.resource + '/view/' + name + '.js', {
1972 method: 'GET',
1973 cache: true,
1974 dataType: 'text'
1975 }).then(function(data) {
1976 try {
1977 var viewConstructor = (new Function(['L', '$'], 'return ' + data))(_luci2, $);
1978
1979 _luci2._views[name] = new viewConstructor({
1980 name: name,
1981 acls: node.write || { }
1982 });
1983
1984 return _luci2._views[name].render();
1985 }
1986 catch(e) { };
1987
1988 return $.Deferred().resolve();
1989 });
1990 },
1991
1992 init: function()
1993 {
1994 _luci2.ui.loading(true);
1995
1996 $.when(
1997 _luci2.ui.renderMainMenu()
1998 ).then(function() {
1999 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2000 _luci2.ui.loading(false);
2001 })
2002 });
2003 }
2004 };
2005
2006 var AbstractWidget = Class.extend({
2007 i18n: function(text) {
2008 return text;
2009 },
2010
2011 toString: function() {
2012 var x = document.createElement('div');
2013 x.appendChild(this.render());
2014
2015 return x.innerHTML;
2016 },
2017
2018 insertInto: function(id) {
2019 return $(id).empty().append(this.render());
2020 }
2021 });
2022
2023 this.ui.view = AbstractWidget.extend({
2024 _fetch_template: function()
2025 {
2026 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2027 method: 'GET',
2028 cache: true,
2029 dataType: 'text',
2030 success: function(data) {
2031 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2032 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2033 switch (p1)
2034 {
2035 case '#':
2036 return '';
2037
2038 case ':':
2039 return _luci2.tr(p2);
2040
2041 case '=':
2042 return _luci2.globals[p2] || '';
2043
2044 default:
2045 return '(?' + match + ')';
2046 }
2047 });
2048
2049 $('#maincontent').append(data);
2050 }
2051 });
2052 },
2053
2054 execute: function()
2055 {
2056 throw "Not implemented";
2057 },
2058
2059 render: function()
2060 {
2061 var container = $('#maincontent');
2062
2063 container.empty();
2064
2065 if (this.title)
2066 container.append($('<h2 />').append(this.title));
2067
2068 if (this.description)
2069 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2070
2071 var self = this;
2072 return this._fetch_template().then(function() {
2073 return _luci2.deferrable(self.execute());
2074 });
2075 }
2076 });
2077
2078 this.ui.menu = AbstractWidget.extend({
2079 init: function() {
2080 this._nodes = { };
2081 },
2082
2083 entries: function(entries)
2084 {
2085 for (var entry in entries)
2086 {
2087 var path = entry.split(/\//);
2088 var node = this._nodes;
2089
2090 for (i = 0; i < path.length; i++)
2091 {
2092 if (!node.childs)
2093 node.childs = { };
2094
2095 if (!node.childs[path[i]])
2096 node.childs[path[i]] = { };
2097
2098 node = node.childs[path[i]];
2099 }
2100
2101 $.extend(node, entries[entry]);
2102 }
2103 },
2104
2105 _indexcmp: function(a, b)
2106 {
2107 var x = a.index || 0;
2108 var y = b.index || 0;
2109 return (x - y);
2110 },
2111
2112 firstChildView: function(node)
2113 {
2114 if (node.view)
2115 return node;
2116
2117 var nodes = [ ];
2118 for (var child in (node.childs || { }))
2119 nodes.push(node.childs[child]);
2120
2121 nodes.sort(this._indexcmp);
2122
2123 for (var i = 0; i < nodes.length; i++)
2124 {
2125 var child = this.firstChildView(nodes[i]);
2126 if (child)
2127 {
2128 $.extend(node, child);
2129 return node;
2130 }
2131 }
2132
2133 return undefined;
2134 },
2135
2136 _onclick: function(ev)
2137 {
2138 _luci2.ui.loading(true);
2139 _luci2.ui.renderView(ev.data).then(function() {
2140 _luci2.ui.loading(false);
2141 });
2142
2143 ev.preventDefault();
2144 this.blur();
2145 },
2146
2147 _render: function(childs, level, min, max)
2148 {
2149 var nodes = [ ];
2150 for (var node in childs)
2151 {
2152 var child = this.firstChildView(childs[node]);
2153 if (child)
2154 nodes.push(childs[node]);
2155 }
2156
2157 nodes.sort(this._indexcmp);
2158
2159 var list = $('<ul />');
2160
2161 if (level == 0)
2162 list.addClass('nav');
2163 else if (level == 1)
2164 list.addClass('dropdown-menu');
2165
2166 for (var i = 0; i < nodes.length; i++)
2167 {
2168 if (!_luci2.globals.defaultNode)
2169 {
2170 var v = _luci2.getHash('view');
2171 if (!v || v == nodes[i].view)
2172 _luci2.globals.defaultNode = nodes[i];
2173 }
2174
2175 var item = $('<li />')
2176 .append($('<a />')
2177 .attr('href', '#')
2178 .text(_luci2.tr(nodes[i].title))
2179 .click(nodes[i], this._onclick))
2180 .appendTo(list);
2181
2182 if (nodes[i].childs && level < max)
2183 {
2184 item.addClass('dropdown');
2185 item.find('a').addClass('menu');
2186 item.append(this._render(nodes[i].childs, level + 1));
2187 }
2188 }
2189
2190 return list.get(0);
2191 },
2192
2193 render: function(min, max)
2194 {
2195 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2196 return this._render(top.childs, 0, min, max);
2197 },
2198
2199 getNode: function(path, max)
2200 {
2201 var p = path.split(/\//);
2202 var n = this._nodes;
2203
2204 if (typeof(max) == 'undefined')
2205 max = p.length;
2206
2207 for (var i = 0; i < max; i++)
2208 {
2209 if (!n.childs[p[i]])
2210 return undefined;
2211
2212 n = n.childs[p[i]];
2213 }
2214
2215 return n;
2216 }
2217 });
2218
2219 this.ui.table = AbstractWidget.extend({
2220 init: function()
2221 {
2222 this._rows = [ ];
2223 },
2224
2225 row: function(values)
2226 {
2227 if ($.isArray(values))
2228 {
2229 this._rows.push(values);
2230 }
2231 else if ($.isPlainObject(values))
2232 {
2233 var v = [ ];
2234 for (var i = 0; i < this.options.columns.length; i++)
2235 {
2236 var col = this.options.columns[i];
2237
2238 if (typeof col.key == 'string')
2239 v.push(values[col.key]);
2240 else
2241 v.push(null);
2242 }
2243 this._rows.push(v);
2244 }
2245 },
2246
2247 rows: function(rows)
2248 {
2249 for (var i = 0; i < rows.length; i++)
2250 this.row(rows[i]);
2251 },
2252
2253 render: function(id)
2254 {
2255 var fieldset = document.createElement('fieldset');
2256 fieldset.className = 'cbi-section';
2257
2258 if (this.options.caption)
2259 {
2260 var legend = document.createElement('legend');
2261 $(legend).append(this.options.caption);
2262 fieldset.appendChild(legend);
2263 }
2264
2265 var table = document.createElement('table');
2266 table.className = 'cbi-section-table';
2267
2268 var has_caption = false;
2269 var has_description = false;
2270
2271 for (var i = 0; i < this.options.columns.length; i++)
2272 if (this.options.columns[i].caption)
2273 {
2274 has_caption = true;
2275 break;
2276 }
2277 else if (this.options.columns[i].description)
2278 {
2279 has_description = true;
2280 break;
2281 }
2282
2283 if (has_caption)
2284 {
2285 var tr = table.insertRow(-1);
2286 tr.className = 'cbi-section-table-titles';
2287
2288 for (var i = 0; i < this.options.columns.length; i++)
2289 {
2290 var col = this.options.columns[i];
2291 var th = document.createElement('th');
2292 th.className = 'cbi-section-table-cell';
2293
2294 tr.appendChild(th);
2295
2296 if (col.width)
2297 th.style.width = col.width;
2298
2299 if (col.align)
2300 th.style.textAlign = col.align;
2301
2302 if (col.caption)
2303 $(th).append(col.caption);
2304 }
2305 }
2306
2307 if (has_description)
2308 {
2309 var tr = table.insertRow(-1);
2310 tr.className = 'cbi-section-table-descr';
2311
2312 for (var i = 0; i < this.options.columns.length; i++)
2313 {
2314 var col = this.options.columns[i];
2315 var th = document.createElement('th');
2316 th.className = 'cbi-section-table-cell';
2317
2318 tr.appendChild(th);
2319
2320 if (col.width)
2321 th.style.width = col.width;
2322
2323 if (col.align)
2324 th.style.textAlign = col.align;
2325
2326 if (col.description)
2327 $(th).append(col.description);
2328 }
2329 }
2330
2331 if (this._rows.length == 0)
2332 {
2333 if (this.options.placeholder)
2334 {
2335 var tr = table.insertRow(-1);
2336 var td = tr.insertCell(-1);
2337 td.className = 'cbi-section-table-cell';
2338
2339 td.colSpan = this.options.columns.length;
2340 $(td).append(this.options.placeholder);
2341 }
2342 }
2343 else
2344 {
2345 for (var i = 0; i < this._rows.length; i++)
2346 {
2347 var tr = table.insertRow(-1);
2348
2349 for (var j = 0; j < this.options.columns.length; j++)
2350 {
2351 var col = this.options.columns[j];
2352 var td = tr.insertCell(-1);
2353
2354 var val = this._rows[i][j];
2355
2356 if (typeof(val) == 'undefined')
2357 val = col.placeholder;
2358
2359 if (typeof(val) == 'undefined')
2360 val = '';
2361
2362 if (col.width)
2363 td.style.width = col.width;
2364
2365 if (col.align)
2366 td.style.textAlign = col.align;
2367
2368 if (typeof col.format == 'string')
2369 $(td).append(col.format.format(val));
2370 else if (typeof col.format == 'function')
2371 $(td).append(col.format(val, i));
2372 else
2373 $(td).append(val);
2374 }
2375 }
2376 }
2377
2378 this._rows = [ ];
2379 fieldset.appendChild(table);
2380
2381 return fieldset;
2382 }
2383 });
2384
2385 this.ui.progress = AbstractWidget.extend({
2386 render: function()
2387 {
2388 var vn = parseInt(this.options.value) || 0;
2389 var mn = parseInt(this.options.max) || 100;
2390 var pc = Math.floor((100 / mn) * vn);
2391
2392 var bar = document.createElement('div');
2393 bar.className = 'progressbar';
2394
2395 bar.appendChild(document.createElement('div'));
2396 bar.lastChild.appendChild(document.createElement('div'));
2397 bar.lastChild.style.width = pc + '%';
2398
2399 if (typeof(this.options.format) == 'string')
2400 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2401 else if (typeof(this.options.format) == 'function')
2402 $(bar.lastChild.lastChild).append(this.options.format(pc));
2403 else
2404 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2405
2406 return bar;
2407 }
2408 });
2409
2410 this.ui.devicebadge = AbstractWidget.extend({
2411 render: function()
2412 {
2413 var dev = this.options.l3_device || this.options.device || '?';
2414
2415 var span = document.createElement('span');
2416 span.className = 'ifacebadge';
2417
2418 if (typeof(this.options.signal) == 'number' ||
2419 typeof(this.options.noise) == 'number')
2420 {
2421 var r = 'none';
2422 if (typeof(this.options.signal) != 'undefined' &&
2423 typeof(this.options.noise) != 'undefined')
2424 {
2425 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2426 if (q < 1)
2427 r = '0';
2428 else if (q < 2)
2429 r = '0-25';
2430 else if (q < 3)
2431 r = '25-50';
2432 else if (q < 4)
2433 r = '50-75';
2434 else
2435 r = '75-100';
2436 }
2437
2438 span.appendChild(document.createElement('img'));
2439 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2440
2441 if (r == 'none')
2442 span.title = _luci2.tr('No signal');
2443 else
2444 span.title = '%s: %d %s / %s: %d %s'.format(
2445 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2446 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2447 );
2448 }
2449 else
2450 {
2451 var type = 'ethernet';
2452 var desc = _luci2.tr('Ethernet device');
2453
2454 if (this.options.l3_device != this.options.device)
2455 {
2456 type = 'tunnel';
2457 desc = _luci2.tr('Tunnel interface');
2458 }
2459 else if (dev.indexOf('br-') == 0)
2460 {
2461 type = 'bridge';
2462 desc = _luci2.tr('Bridge');
2463 }
2464 else if (dev.indexOf('.') > 0)
2465 {
2466 type = 'vlan';
2467 desc = _luci2.tr('VLAN interface');
2468 }
2469 else if (dev.indexOf('wlan') == 0 ||
2470 dev.indexOf('ath') == 0 ||
2471 dev.indexOf('wl') == 0)
2472 {
2473 type = 'wifi';
2474 desc = _luci2.tr('Wireless Network');
2475 }
2476
2477 span.appendChild(document.createElement('img'));
2478 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2479 span.title = desc;
2480 }
2481
2482 $(span).append(' ');
2483 $(span).append(dev);
2484
2485 return span;
2486 }
2487 });
2488
2489 var type = function(f, l)
2490 {
2491 f.message = l;
2492 return f;
2493 };
2494
2495 this.cbi = {
2496 validation: {
2497 i18n: function(msg)
2498 {
2499 _luci2.cbi.validation.message = _luci2.tr(msg);
2500 },
2501
2502 compile: function(code)
2503 {
2504 var pos = 0;
2505 var esc = false;
2506 var depth = 0;
2507 var types = _luci2.cbi.validation.types;
2508 var stack = [ ];
2509
2510 code += ',';
2511
2512 for (var i = 0; i < code.length; i++)
2513 {
2514 if (esc)
2515 {
2516 esc = false;
2517 continue;
2518 }
2519
2520 switch (code.charCodeAt(i))
2521 {
2522 case 92:
2523 esc = true;
2524 break;
2525
2526 case 40:
2527 case 44:
2528 if (depth <= 0)
2529 {
2530 if (pos < i)
2531 {
2532 var label = code.substring(pos, i);
2533 label = label.replace(/\\(.)/g, '$1');
2534 label = label.replace(/^[ \t]+/g, '');
2535 label = label.replace(/[ \t]+$/g, '');
2536
2537 if (label && !isNaN(label))
2538 {
2539 stack.push(parseFloat(label));
2540 }
2541 else if (label.match(/^(['"]).*\1$/))
2542 {
2543 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2544 }
2545 else if (typeof types[label] == 'function')
2546 {
2547 stack.push(types[label]);
2548 stack.push(null);
2549 }
2550 else
2551 {
2552 throw "Syntax error, unhandled token '"+label+"'";
2553 }
2554 }
2555 pos = i+1;
2556 }
2557 depth += (code.charCodeAt(i) == 40);
2558 break;
2559
2560 case 41:
2561 if (--depth <= 0)
2562 {
2563 if (typeof stack[stack.length-2] != 'function')
2564 throw "Syntax error, argument list follows non-function";
2565
2566 stack[stack.length-1] =
2567 arguments.callee(code.substring(pos, i));
2568
2569 pos = i+1;
2570 }
2571 break;
2572 }
2573 }
2574
2575 return stack;
2576 }
2577 }
2578 };
2579
2580 var validation = this.cbi.validation;
2581
2582 validation.types = {
2583 'integer': function()
2584 {
2585 if (this.match(/^-?[0-9]+$/) != null)
2586 return true;
2587
2588 validation.i18n('Must be a valid integer');
2589 return false;
2590 },
2591
2592 'uinteger': function()
2593 {
2594 if (validation.types['integer'].apply(this) && (this >= 0))
2595 return true;
2596
2597 validation.i18n('Must be a positive integer');
2598 return false;
2599 },
2600
2601 'float': function()
2602 {
2603 if (!isNaN(parseFloat(this)))
2604 return true;
2605
2606 validation.i18n('Must be a valid number');
2607 return false;
2608 },
2609
2610 'ufloat': function()
2611 {
2612 if (validation.types['float'].apply(this) && (this >= 0))
2613 return true;
2614
2615 validation.i18n('Must be a positive number');
2616 return false;
2617 },
2618
2619 'ipaddr': function()
2620 {
2621 if (validation.types['ip4addr'].apply(this) ||
2622 validation.types['ip6addr'].apply(this))
2623 return true;
2624
2625 validation.i18n('Must be a valid IP address');
2626 return false;
2627 },
2628
2629 'ip4addr': function()
2630 {
2631 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2632 {
2633 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2634 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2635 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2636 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2637 ((RegExp.$6.indexOf('.') < 0)
2638 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2639 : (validation.types['ip4addr'].apply(RegExp.$6))))
2640 return true;
2641 }
2642
2643 validation.i18n('Must be a valid IPv4 address');
2644 return false;
2645 },
2646
2647 'ip6addr': function()
2648 {
2649 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2650 {
2651 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2652 {
2653 var addr = RegExp.$1;
2654
2655 if (addr == '::')
2656 {
2657 return true;
2658 }
2659
2660 if (addr.indexOf('.') > 0)
2661 {
2662 var off = addr.lastIndexOf(':');
2663
2664 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2665 {
2666 validation.i18n('Must be a valid IPv6 address');
2667 return false;
2668 }
2669
2670 addr = addr.substr(0, off) + ':0:0';
2671 }
2672
2673 if (addr.indexOf('::') >= 0)
2674 {
2675 var colons = 0;
2676 var fill = '0';
2677
2678 for (var i = 1; i < (addr.length-1); i++)
2679 if (addr.charAt(i) == ':')
2680 colons++;
2681
2682 if (colons > 7)
2683 {
2684 validation.i18n('Must be a valid IPv6 address');
2685 return false;
2686 }
2687
2688 for (var i = 0; i < (7 - colons); i++)
2689 fill += ':0';
2690
2691 if (addr.match(/^(.*?)::(.*?)$/))
2692 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2693 (RegExp.$2 ? ':' + RegExp.$2 : '');
2694 }
2695
2696 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2697 return true;
2698
2699 validation.i18n('Must be a valid IPv6 address');
2700 return false;
2701 }
2702 }
2703
2704 return false;
2705 },
2706
2707 'port': function()
2708 {
2709 if (validation.types['integer'].apply(this) &&
2710 (this >= 0) && (this <= 65535))
2711 return true;
2712
2713 validation.i18n('Must be a valid port number');
2714 return false;
2715 },
2716
2717 'portrange': function()
2718 {
2719 if (this.match(/^(\d+)-(\d+)$/))
2720 {
2721 var p1 = RegExp.$1;
2722 var p2 = RegExp.$2;
2723
2724 if (validation.types['port'].apply(p1) &&
2725 validation.types['port'].apply(p2) &&
2726 (parseInt(p1) <= parseInt(p2)))
2727 return true;
2728 }
2729 else if (validation.types['port'].apply(this))
2730 {
2731 return true;
2732 }
2733
2734 validation.i18n('Must be a valid port range');
2735 return false;
2736 },
2737
2738 'macaddr': function()
2739 {
2740 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2741 return true;
2742
2743 validation.i18n('Must be a valid MAC address');
2744 return false;
2745 },
2746
2747 'host': function()
2748 {
2749 if (validation.types['hostname'].apply(this) ||
2750 validation.types['ipaddr'].apply(this))
2751 return true;
2752
2753 validation.i18n('Must be a valid hostname or IP address');
2754 return false;
2755 },
2756
2757 'hostname': function()
2758 {
2759 if ((this.length <= 253) &&
2760 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2761 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2762 this.match(/[^0-9.]/)))))
2763 return true;
2764
2765 validation.i18n('Must be a valid host name');
2766 return false;
2767 },
2768
2769 'network': function()
2770 {
2771 if (validation.types['uciname'].apply(this) ||
2772 validation.types['host'].apply(this))
2773 return true;
2774
2775 validation.i18n('Must be a valid network name');
2776 return false;
2777 },
2778
2779 'wpakey': function()
2780 {
2781 var v = this;
2782
2783 if ((v.length == 64)
2784 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
2785 : ((v.length >= 8) && (v.length <= 63)))
2786 return true;
2787
2788 validation.i18n('Must be a valid WPA key');
2789 return false;
2790 },
2791
2792 'wepkey': function()
2793 {
2794 var v = this;
2795
2796 if (v.substr(0,2) == 's:')
2797 v = v.substr(2);
2798
2799 if (((v.length == 10) || (v.length == 26))
2800 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
2801 : ((v.length == 5) || (v.length == 13)))
2802 return true;
2803
2804 validation.i18n('Must be a valid WEP key');
2805 return false;
2806 },
2807
2808 'uciname': function()
2809 {
2810 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2811 return true;
2812
2813 validation.i18n('Must be a valid UCI identifier');
2814 return false;
2815 },
2816
2817 'range': function(min, max)
2818 {
2819 var val = parseFloat(this);
2820
2821 if (validation.types['integer'].apply(this) &&
2822 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
2823 return true;
2824
2825 validation.i18n('Must be a number between %d and %d');
2826 return false;
2827 },
2828
2829 'min': function(min)
2830 {
2831 var val = parseFloat(this);
2832
2833 if (validation.types['integer'].apply(this) &&
2834 !isNaN(min) && !isNaN(val) && (val >= min))
2835 return true;
2836
2837 validation.i18n('Must be a number greater or equal to %d');
2838 return false;
2839 },
2840
2841 'max': function(max)
2842 {
2843 var val = parseFloat(this);
2844
2845 if (validation.types['integer'].apply(this) &&
2846 !isNaN(max) && !isNaN(val) && (val <= max))
2847 return true;
2848
2849 validation.i18n('Must be a number lower or equal to %d');
2850 return false;
2851 },
2852
2853 'rangelength': function(min, max)
2854 {
2855 var val = '' + this;
2856
2857 if (!isNaN(min) && !isNaN(max) &&
2858 (val.length >= min) && (val.length <= max))
2859 return true;
2860
2861 validation.i18n('Must be between %d and %d characters');
2862 return false;
2863 },
2864
2865 'minlength': function(min)
2866 {
2867 var val = '' + this;
2868
2869 if (!isNaN(min) && (val.length >= min))
2870 return true;
2871
2872 validation.i18n('Must be at least %d characters');
2873 return false;
2874 },
2875
2876 'maxlength': function(max)
2877 {
2878 var val = '' + this;
2879
2880 if (!isNaN(max) && (val.length <= max))
2881 return true;
2882
2883 validation.i18n('Must be at most %d characters');
2884 return false;
2885 },
2886
2887 'or': function()
2888 {
2889 var msgs = [ ];
2890
2891 for (var i = 0; i < arguments.length; i += 2)
2892 {
2893 delete validation.message;
2894
2895 if (typeof(arguments[i]) != 'function')
2896 {
2897 if (arguments[i] == this)
2898 return true;
2899 i--;
2900 }
2901 else if (arguments[i].apply(this, arguments[i+1]))
2902 {
2903 return true;
2904 }
2905
2906 if (validation.message)
2907 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2908 }
2909
2910 validation.message = msgs.join( _luci2.tr(' - or - '));
2911 return false;
2912 },
2913
2914 'and': function()
2915 {
2916 var msgs = [ ];
2917
2918 for (var i = 0; i < arguments.length; i += 2)
2919 {
2920 delete validation.message;
2921
2922 if (typeof arguments[i] != 'function')
2923 {
2924 if (arguments[i] != this)
2925 return false;
2926 i--;
2927 }
2928 else if (!arguments[i].apply(this, arguments[i+1]))
2929 {
2930 return false;
2931 }
2932
2933 if (validation.message)
2934 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2935 }
2936
2937 validation.message = msgs.join(', ');
2938 return true;
2939 },
2940
2941 'neg': function()
2942 {
2943 return validation.types['or'].apply(
2944 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
2945 },
2946
2947 'list': function(subvalidator, subargs)
2948 {
2949 if (typeof subvalidator != 'function')
2950 return false;
2951
2952 var tokens = this.match(/[^ \t]+/g);
2953 for (var i = 0; i < tokens.length; i++)
2954 if (!subvalidator.apply(tokens[i], subargs))
2955 return false;
2956
2957 return true;
2958 },
2959
2960 'phonedigit': function()
2961 {
2962 if (this.match(/^[0-9\*#!\.]+$/) != null)
2963 return true;
2964
2965 validation.i18n('Must be a valid phone number digit');
2966 return false;
2967 },
2968
2969 'string': function()
2970 {
2971 return true;
2972 }
2973 };
2974
2975
2976 var AbstractValue = AbstractWidget.extend({
2977 init: function(name, options)
2978 {
2979 this.name = name;
2980 this.instance = { };
2981 this.dependencies = [ ];
2982 this.rdependency = { };
2983
2984 this.options = _luci2.defaults(options, {
2985 placeholder: '',
2986 datatype: 'string',
2987 optional: false,
2988 keep: true
2989 });
2990 },
2991
2992 id: function(sid)
2993 {
2994 return this.section.id('field', sid || '__unknown__', this.name);
2995 },
2996
2997 render: function(sid)
2998 {
2999 var i = this.instance[sid] = { };
3000
3001 i.top = $('<div />').addClass('cbi-value');
3002
3003 if (typeof(this.options.caption) == 'string')
3004 $('<label />')
3005 .addClass('cbi-value-title')
3006 .attr('for', this.id(sid))
3007 .text(this.options.caption)
3008 .appendTo(i.top);
3009
3010 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
3011 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
3012
3013 if (typeof(this.options.description) == 'string')
3014 $('<div />')
3015 .addClass('cbi-value-description')
3016 .text(this.options.description)
3017 .appendTo(i.top);
3018
3019 return i.top;
3020 },
3021
3022 ucipath: function(sid)
3023 {
3024 return {
3025 config: (this.options.uci_package || this.map.uci_package),
3026 section: (this.options.uci_section || sid),
3027 option: (this.options.uci_option || this.name)
3028 };
3029 },
3030
3031 ucivalue: function(sid)
3032 {
3033 var uci = this.ucipath(sid);
3034 var val = this.map.get(uci.config, uci.section, uci.option);
3035
3036 if (typeof(val) == 'undefined')
3037 return this.options.initial;
3038
3039 return val;
3040 },
3041
3042 formvalue: function(sid)
3043 {
3044 var v = $('#' + this.id(sid)).val();
3045 return (v === '') ? undefined : v;
3046 },
3047
3048 textvalue: function(sid)
3049 {
3050 var v = this.formvalue(sid);
3051
3052 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3053 v = this.ucivalue(sid);
3054
3055 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3056 v = this.options.placeholder;
3057
3058 if (typeof(v) == 'undefined' || v === '')
3059 return undefined;
3060
3061 if (typeof(v) == 'string' && $.isArray(this.choices))
3062 {
3063 for (var i = 0; i < this.choices.length; i++)
3064 if (v === this.choices[i][0])
3065 return this.choices[i][1];
3066 }
3067 else if (v === true)
3068 return _luci2.tr('yes');
3069 else if (v === false)
3070 return _luci2.tr('no');
3071 else if ($.isArray(v))
3072 return v.join(', ');
3073
3074 return v;
3075 },
3076
3077 changed: function(sid)
3078 {
3079 var a = this.ucivalue(sid);
3080 var b = this.formvalue(sid);
3081
3082 if (typeof(a) != typeof(b))
3083 return true;
3084
3085 if (typeof(a) == 'object')
3086 {
3087 if (a.length != b.length)
3088 return true;
3089
3090 for (var i = 0; i < a.length; i++)
3091 if (a[i] != b[i])
3092 return true;
3093
3094 return false;
3095 }
3096
3097 return (a != b);
3098 },
3099
3100 save: function(sid)
3101 {
3102 var uci = this.ucipath(sid);
3103
3104 if (this.instance[sid].disabled)
3105 {
3106 if (!this.options.keep)
3107 return this.map.set(uci.config, uci.section, uci.option, undefined);
3108
3109 return false;
3110 }
3111
3112 var chg = this.changed(sid);
3113 var val = this.formvalue(sid);
3114
3115 if (chg)
3116 this.map.set(uci.config, uci.section, uci.option, val);
3117
3118 return chg;
3119 },
3120
3121 validator: function(sid, elem, multi)
3122 {
3123 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3124 return elem;
3125
3126 var vstack;
3127 if (typeof(this.options.datatype) == 'string')
3128 {
3129 try {
3130 vstack = _luci2.cbi.validation.compile(this.options.datatype);
3131 } catch(e) { };
3132 }
3133 else if (typeof(this.options.datatype) == 'function')
3134 {
3135 var vfunc = this.options.datatype;
3136 vstack = [ function(elem) {
3137 var rv = vfunc(this, elem);
3138 if (rv !== true)
3139 validation.message = rv;
3140 return (rv === true);
3141 }, [ elem ] ];
3142 }
3143
3144 var evdata = {
3145 self: this,
3146 sid: sid,
3147 elem: elem,
3148 multi: multi,
3149 inst: this.instance[sid],
3150 opt: this.options.optional
3151 };
3152
3153 var validator = function(ev)
3154 {
3155 var d = ev.data;
3156 var rv = true;
3157 var val = d.elem.val();
3158
3159 if (vstack && typeof(vstack[0]) == 'function')
3160 {
3161 delete validation.message;
3162
3163 if ((val.length == 0 && !d.opt))
3164 {
3165 d.elem.addClass('error');
3166 d.inst.top.addClass('error');
3167 d.inst.error.text(_luci2.tr('Field must not be empty'));
3168 rv = false;
3169 }
3170 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3171 {
3172 d.elem.addClass('error');
3173 d.inst.top.addClass('error');
3174 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
3175 rv = false;
3176 }
3177 else
3178 {
3179 d.elem.removeClass('error');
3180
3181 if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
3182 {
3183 rv = false;
3184 }
3185 else
3186 {
3187 d.inst.top.removeClass('error');
3188 d.inst.error.text('');
3189 }
3190 }
3191 }
3192
3193 if (rv)
3194 {
3195 for (var field in d.self.rdependency)
3196 d.self.rdependency[field].toggle(d.sid);
3197 }
3198
3199 return rv;
3200 };
3201
3202 if (elem.prop('tagName') == 'SELECT')
3203 {
3204 elem.change(evdata, validator);
3205 }
3206 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3207 {
3208 elem.click(evdata, validator);
3209 elem.blur(evdata, validator);
3210 }
3211 else
3212 {
3213 elem.keyup(evdata, validator);
3214 elem.blur(evdata, validator);
3215 }
3216
3217 elem.attr('cbi-validate', true).on('validate', evdata, validator);
3218
3219 return elem;
3220 },
3221
3222 validate: function(sid)
3223 {
3224 var i = this.instance[sid];
3225
3226 i.widget.find('[cbi-validate]').trigger('validate');
3227
3228 return (i.disabled || i.error.text() == '');
3229 },
3230
3231 depends: function(d, v)
3232 {
3233 var dep;
3234
3235 if ($.isArray(d))
3236 {
3237 dep = { };
3238 for (var i = 0; i < d.length; i++)
3239 {
3240 if (typeof(d[i]) == 'string')
3241 dep[d[i]] = true;
3242 else if (d[i] instanceof AbstractValue)
3243 dep[d[i].name] = true;
3244 }
3245 }
3246 else if (d instanceof AbstractValue)
3247 {
3248 dep = { };
3249 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3250 }
3251 else if (typeof(d) == 'object')
3252 {
3253 dep = d;
3254 }
3255 else if (typeof(d) == 'string')
3256 {
3257 dep = { };
3258 dep[d] = (typeof(v) == 'undefined') ? true : v;
3259 }
3260
3261 if (!dep || $.isEmptyObject(dep))
3262 return this;
3263
3264 for (var field in dep)
3265 {
3266 var f = this.section.fields[field];
3267 if (f)
3268 f.rdependency[this.name] = this;
3269 else
3270 delete dep[field];
3271 }
3272
3273 if ($.isEmptyObject(dep))
3274 return this;
3275
3276 this.dependencies.push(dep);
3277
3278 return this;
3279 },
3280
3281 toggle: function(sid)
3282 {
3283 var d = this.dependencies;
3284 var i = this.instance[sid];
3285
3286 if (!d.length)
3287 return true;
3288
3289 for (var n = 0; n < d.length; n++)
3290 {
3291 var rv = true;
3292
3293 for (var field in d[n])
3294 {
3295 var val = this.section.fields[field].formvalue(sid);
3296 var cmp = d[n][field];
3297
3298 if (typeof(cmp) == 'boolean')
3299 {
3300 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3301 {
3302 rv = false;
3303 break;
3304 }
3305 }
3306 else if (typeof(cmp) == 'string')
3307 {
3308 if (val != cmp)
3309 {
3310 rv = false;
3311 break;
3312 }
3313 }
3314 else if (typeof(cmp) == 'function')
3315 {
3316 if (!cmp(val))
3317 {
3318 rv = false;
3319 break;
3320 }
3321 }
3322 else if (cmp instanceof RegExp)
3323 {
3324 if (!cmp.test(val))
3325 {
3326 rv = false;
3327 break;
3328 }
3329 }
3330 }
3331
3332 if (rv)
3333 {
3334 if (i.disabled)
3335 {
3336 i.disabled = false;
3337 i.top.fadeIn();
3338 }
3339
3340 return true;
3341 }
3342 }
3343
3344 if (!i.disabled)
3345 {
3346 i.disabled = true;
3347 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3348 }
3349
3350 return false;
3351 }
3352 });
3353
3354 this.cbi.CheckboxValue = AbstractValue.extend({
3355 widget: function(sid)
3356 {
3357 var o = this.options;
3358
3359 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
3360 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3361
3362 var i = $('<input />')
3363 .attr('id', this.id(sid))
3364 .attr('type', 'checkbox')
3365 .prop('checked', this.ucivalue(sid));
3366
3367 return this.validator(sid, i);
3368 },
3369
3370 ucivalue: function(sid)
3371 {
3372 var v = this.callSuper('ucivalue', sid);
3373
3374 if (typeof(v) == 'boolean')
3375 return v;
3376
3377 return (v == this.options.enabled);
3378 },
3379
3380 formvalue: function(sid)
3381 {
3382 var v = $('#' + this.id(sid)).prop('checked');
3383
3384 if (typeof(v) == 'undefined')
3385 return !!this.options.initial;
3386
3387 return v;
3388 },
3389
3390 save: function(sid)
3391 {
3392 var uci = this.ucipath(sid);
3393
3394 if (this.instance[sid].disabled)
3395 {
3396 if (!this.options.keep)
3397 return this.map.set(uci.config, uci.section, uci.option, undefined);
3398
3399 return false;
3400 }
3401
3402 var chg = this.changed(sid);
3403 var val = this.formvalue(sid);
3404
3405 if (chg)
3406 {
3407 val = val ? this.options.enabled : this.options.disabled;
3408
3409 if (this.options.optional && val == this.options.initial)
3410 this.map.set(uci.config, uci.section, uci.option, undefined);
3411 else
3412 this.map.set(uci.config, uci.section, uci.option, val);
3413 }
3414
3415 return chg;
3416 }
3417 });
3418
3419 this.cbi.InputValue = AbstractValue.extend({
3420 widget: function(sid)
3421 {
3422 var i = $('<input />')
3423 .attr('id', this.id(sid))
3424 .attr('type', 'text')
3425 .attr('placeholder', this.options.placeholder)
3426 .val(this.ucivalue(sid));
3427
3428 return this.validator(sid, i);
3429 }
3430 });
3431
3432 this.cbi.PasswordValue = AbstractValue.extend({
3433 widget: function(sid)
3434 {
3435 var i = $('<input />')
3436 .attr('id', this.id(sid))
3437 .attr('type', 'password')
3438 .attr('placeholder', this.options.placeholder)
3439 .val(this.ucivalue(sid));
3440
3441 var t = $('<img />')
3442 .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
3443 .attr('title', _luci2.tr('Reveal or hide password'))
3444 .addClass('cbi-button')
3445 .click(function(ev) {
3446 var i = $(this).prev();
3447 var t = i.attr('type');
3448 i.attr('type', (t == 'password') ? 'text' : 'password');
3449 i = t = null;
3450 });
3451
3452 this.validator(sid, i);
3453
3454 return $('<div />')
3455 .addClass('cbi-input-password')
3456 .append(i)
3457 .append(t);
3458 }
3459 });
3460
3461 this.cbi.ListValue = AbstractValue.extend({
3462 widget: function(sid)
3463 {
3464 var s = $('<select />');
3465
3466 if (this.options.optional)
3467 $('<option />')
3468 .attr('value', '')
3469 .text(_luci2.tr('-- Please choose --'))
3470 .appendTo(s);
3471
3472 if (this.choices)
3473 for (var i = 0; i < this.choices.length; i++)
3474 $('<option />')
3475 .attr('value', this.choices[i][0])
3476 .text(this.choices[i][1])
3477 .appendTo(s);
3478
3479 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
3480
3481 return this.validator(sid, s);
3482 },
3483
3484 value: function(k, v)
3485 {
3486 if (!this.choices)
3487 this.choices = [ ];
3488
3489 this.choices.push([k, v || k]);
3490 return this;
3491 }
3492 });
3493
3494 this.cbi.MultiValue = this.cbi.ListValue.extend({
3495 widget: function(sid)
3496 {
3497 var v = this.ucivalue(sid);
3498 var t = $('<div />').attr('id', this.id(sid));
3499
3500 if (!$.isArray(v))
3501 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3502
3503 var s = { };
3504 for (var i = 0; i < v.length; i++)
3505 s[v[i]] = true;
3506
3507 if (this.choices)
3508 for (var i = 0; i < this.choices.length; i++)
3509 {
3510 $('<label />')
3511 .append($('<input />')
3512 .addClass('cbi-input-checkbox')
3513 .attr('type', 'checkbox')
3514 .attr('value', this.choices[i][0])
3515 .prop('checked', s[this.choices[i][0]]))
3516 .append(this.choices[i][1])
3517 .appendTo(t);
3518
3519 $('<br />')
3520 .appendTo(t);
3521 }
3522
3523 return t;
3524 },
3525
3526 formvalue: function(sid)
3527 {
3528 var rv = [ ];
3529 var fields = $('#' + this.id(sid) + ' > label > input');
3530
3531 for (var i = 0; i < fields.length; i++)
3532 if (fields[i].checked)
3533 rv.push(fields[i].getAttribute('value'));
3534
3535 return rv;
3536 },
3537
3538 textvalue: function(sid)
3539 {
3540 var v = this.formvalue(sid);
3541 var c = { };
3542
3543 if (this.choices)
3544 for (var i = 0; i < this.choices.length; i++)
3545 c[this.choices[i][0]] = this.choices[i][1];
3546
3547 var t = [ ];
3548
3549 for (var i = 0; i < v.length; i++)
3550 t.push(c[v[i]] || v[i]);
3551
3552 return t.join(', ');
3553 }
3554 });
3555
3556 this.cbi.ComboBox = AbstractValue.extend({
3557 _change: function(ev)
3558 {
3559 var s = ev.target;
3560 var self = ev.data.self;
3561
3562 if (s.selectedIndex == (s.options.length - 1))
3563 {
3564 ev.data.select.hide();
3565 ev.data.input.show().focus();
3566
3567 var v = ev.data.input.val();
3568 ev.data.input.val(' ');
3569 ev.data.input.val(v);
3570 }
3571 else if (self.options.optional && s.selectedIndex == 0)
3572 {
3573 ev.data.input.val('');
3574 }
3575 else
3576 {
3577 ev.data.input.val(ev.data.select.val());
3578 }
3579 },
3580
3581 _blur: function(ev)
3582 {
3583 var seen = false;
3584 var val = this.value;
3585 var self = ev.data.self;
3586
3587 ev.data.select.empty();
3588
3589 if (self.options.optional)
3590 $('<option />')
3591 .attr('value', '')
3592 .text(_luci2.tr('-- please choose --'))
3593 .appendTo(ev.data.select);
3594
3595 if (self.choices)
3596 for (var i = 0; i < self.choices.length; i++)
3597 {
3598 if (self.choices[i][0] == val)
3599 seen = true;
3600
3601 $('<option />')
3602 .attr('value', self.choices[i][0])
3603 .text(self.choices[i][1])
3604 .appendTo(ev.data.select);
3605 }
3606
3607 if (!seen && val != '')
3608 $('<option />')
3609 .attr('value', val)
3610 .text(val)
3611 .appendTo(ev.data.select);
3612
3613 $('<option />')
3614 .attr('value', ' ')
3615 .text(_luci2.tr('-- custom --'))
3616 .appendTo(ev.data.select);
3617
3618 ev.data.input.hide();
3619 ev.data.select.val(val).show().focus();
3620 },
3621
3622 _enter: function(ev)
3623 {
3624 if (ev.which != 13)
3625 return true;
3626
3627 ev.preventDefault();
3628 ev.data.self._blur(ev);
3629 return false;
3630 },
3631
3632 widget: function(sid)
3633 {
3634 var d = $('<div />')
3635 .attr('id', this.id(sid));
3636
3637 var t = $('<input />')
3638 .attr('type', 'text')
3639 .hide()
3640 .appendTo(d);
3641
3642 var s = $('<select />')
3643 .appendTo(d);
3644
3645 var evdata = {
3646 self: this,
3647 input: this.validator(sid, t),
3648 select: this.validator(sid, s)
3649 };
3650
3651 s.change(evdata, this._change);
3652 t.blur(evdata, this._blur);
3653 t.keydown(evdata, this._enter);
3654
3655 t.val(this.ucivalue(sid));
3656 t.blur();
3657
3658 return d;
3659 },
3660
3661 value: function(k, v)
3662 {
3663 if (!this.choices)
3664 this.choices = [ ];
3665
3666 this.choices.push([k, v || k]);
3667 return this;
3668 },
3669
3670 formvalue: function(sid)
3671 {
3672 var v = $('#' + this.id(sid)).children('input').val();
3673 return (v == '') ? undefined : v;
3674 }
3675 });
3676
3677 this.cbi.DynamicList = this.cbi.ComboBox.extend({
3678 _redraw: function(focus, add, del, s)
3679 {
3680 var v = s.values || [ ];
3681 delete s.values;
3682
3683 $(s.parent).children('input').each(function(i) {
3684 if (i != del)
3685 v.push(this.value || '');
3686 });
3687
3688 $(s.parent).empty();
3689
3690 if (add >= 0)
3691 {
3692 focus = add + 1;
3693 v.splice(focus, 0, '');
3694 }
3695 else if (v.length == 0)
3696 {
3697 focus = 0;
3698 v.push('');
3699 }
3700
3701 for (var i = 0; i < v.length; i++)
3702 {
3703 var evdata = {
3704 sid: s.sid,
3705 self: s.self,
3706 parent: s.parent,
3707 index: i
3708 };
3709
3710 if (this.choices)
3711 {
3712 var txt = $('<input />')
3713 .attr('type', 'text')
3714 .hide()
3715 .appendTo(s.parent);
3716
3717 var sel = $('<select />')
3718 .appendTo(s.parent);
3719
3720 evdata.input = this.validator(s.sid, txt, true);
3721 evdata.select = this.validator(s.sid, sel, true);
3722
3723 sel.change(evdata, this._change);
3724 txt.blur(evdata, this._blur);
3725 txt.keydown(evdata, this._keydown);
3726
3727 txt.val(v[i]);
3728 txt.blur();
3729
3730 if (i == focus || -(i+1) == focus)
3731 sel.focus();
3732
3733 sel = txt = null;
3734 }
3735 else
3736 {
3737 var f = $('<input />')
3738 .attr('type', 'text')
3739 .attr('index', i)
3740 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
3741 .addClass('cbi-input-text')
3742 .keydown(evdata, this._keydown)
3743 .keypress(evdata, this._keypress)
3744 .val(v[i]);
3745
3746 f.appendTo(s.parent);
3747
3748 if (i == focus)
3749 {
3750 f.focus();
3751 }
3752 else if (-(i+1) == focus)
3753 {
3754 f.focus();
3755
3756 /* force cursor to end */
3757 var val = f.val();
3758 f.val(' ');
3759 f.val(val);
3760 }
3761
3762 evdata.input = this.validator(s.sid, f, true);
3763
3764 f = null;
3765 }
3766
3767 $('<img />')
3768 .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
3769 .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
3770 .addClass('cbi-button')
3771 .click(evdata, this._btnclick)
3772 .appendTo(s.parent);
3773
3774 $('<br />')
3775 .appendTo(s.parent);
3776
3777 evdata = null;
3778 }
3779
3780 s = null;
3781 },
3782
3783 _keypress: function(ev)
3784 {
3785 switch (ev.which)
3786 {
3787 /* backspace, delete */
3788 case 8:
3789 case 46:
3790 if (ev.data.input.val() == '')
3791 {
3792 ev.preventDefault();
3793 return false;
3794 }
3795
3796 return true;
3797
3798 /* enter, arrow up, arrow down */
3799 case 13:
3800 case 38:
3801 case 40:
3802 ev.preventDefault();
3803 return false;
3804 }
3805
3806 return true;
3807 },
3808
3809 _keydown: function(ev)
3810 {
3811 var input = ev.data.input;
3812
3813 switch (ev.which)
3814 {
3815 /* backspace, delete */
3816 case 8:
3817 case 46:
3818 if (input.val().length == 0)
3819 {
3820 ev.preventDefault();
3821
3822 var index = ev.data.index;
3823 var focus = index;
3824
3825 if (ev.which == 8)
3826 focus = -focus;
3827
3828 ev.data.self._redraw(focus, -1, index, ev.data);
3829 return false;
3830 }
3831
3832 break;
3833
3834 /* enter */
3835 case 13:
3836 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
3837 break;
3838
3839 /* arrow up */
3840 case 38:
3841 var prev = input.prevAll('input:first');
3842 if (prev.is(':visible'))
3843 prev.focus();
3844 else
3845 prev.next('select').focus();
3846 break;
3847
3848 /* arrow down */
3849 case 40:
3850 var next = input.nextAll('input:first');
3851 if (next.is(':visible'))
3852 next.focus();
3853 else
3854 next.next('select').focus();
3855 break;
3856 }
3857
3858 return true;
3859 },
3860
3861 _btnclick: function(ev)
3862 {
3863 if (!this.getAttribute('disabled'))
3864 {
3865 if (ev.target.src.indexOf('remove') > -1)
3866 {
3867 var index = ev.data.index;
3868 ev.data.self._redraw(-index, -1, index, ev.data);
3869 }
3870 else
3871 {
3872 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
3873 }
3874 }
3875
3876 return false;
3877 },
3878
3879 widget: function(sid)
3880 {
3881 this.options.optional = true;
3882
3883 var v = this.ucivalue(sid);
3884
3885 if (!$.isArray(v))
3886 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3887
3888 var d = $('<div />')
3889 .attr('id', this.id(sid))
3890 .addClass('cbi-input-dynlist');
3891
3892 this._redraw(NaN, -1, -1, {
3893 self: this,
3894 parent: d[0],
3895 values: v,
3896 sid: sid
3897 });
3898
3899 return d;
3900 },
3901
3902 ucivalue: function(sid)
3903 {
3904 var v = this.callSuper('ucivalue', sid);
3905
3906 if (!$.isArray(v))
3907 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3908
3909 return v;
3910 },
3911
3912 formvalue: function(sid)
3913 {
3914 var rv = [ ];
3915 var fields = $('#' + this.id(sid) + ' > input');
3916
3917 for (var i = 0; i < fields.length; i++)
3918 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
3919 rv.push(fields[i].value);
3920
3921 return rv;
3922 }
3923 });
3924
3925 this.cbi.DummyValue = AbstractValue.extend({
3926 widget: function(sid)
3927 {
3928 return $('<div />')
3929 .addClass('cbi-value-dummy')
3930 .attr('id', this.id(sid))
3931 .html(this.ucivalue(sid));
3932 },
3933
3934 formvalue: function(sid)
3935 {
3936 return this.ucivalue(sid);
3937 }
3938 });
3939
3940 this.cbi.NetworkList = AbstractValue.extend({
3941 load: function(sid)
3942 {
3943 var self = this;
3944
3945 if (!self.interfaces)
3946 {
3947 self.interfaces = [ ];
3948 return _luci2.network.getNetworkStatus(function(ifaces) {
3949 self.interfaces = ifaces;
3950 self = null;
3951 });
3952 }
3953
3954 return undefined;
3955 },
3956
3957 _device_icon: function(dev)
3958 {
3959 var type = 'ethernet';
3960 var desc = _luci2.tr('Ethernet device');
3961
3962 if (dev.type == 'IP tunnel')
3963 {
3964 type = 'tunnel';
3965 desc = _luci2.tr('Tunnel interface');
3966 }
3967 else if (dev['bridge-members'])
3968 {
3969 type = 'bridge';
3970 desc = _luci2.tr('Bridge');
3971 }
3972 else if (dev.wireless)
3973 {
3974 type = 'wifi';
3975 desc = _luci2.tr('Wireless Network');
3976 }
3977 else if (dev.name.indexOf('.') > 0)
3978 {
3979 type = 'vlan';
3980 desc = _luci2.tr('VLAN interface');
3981 }
3982
3983 return $('<img />')
3984 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
3985 .attr('title', '%s (%s)'.format(desc, dev.name));
3986 },
3987
3988 widget: function(sid)
3989 {
3990 var id = this.id(sid);
3991 var ul = $('<ul />')
3992 .attr('id', id)
3993 .addClass('cbi-input-networks');
3994
3995 var itype = this.options.multiple ? 'checkbox' : 'radio';
3996 var value = this.ucivalue(sid);
3997 var check = { };
3998
3999 if (!this.options.multiple)
4000 check[value] = true;
4001 else
4002 for (var i = 0; i < value.length; i++)
4003 check[value[i]] = true;
4004
4005 if (this.interfaces)
4006 {
4007 for (var i = 0; i < this.interfaces.length; i++)
4008 {
4009 var iface = this.interfaces[i];
4010 var badge = $('<span />')
4011 .addClass('ifacebadge')
4012 .text('%s: '.format(iface.name));
4013
4014 if (iface.subdevices)
4015 for (var j = 0; j < iface.subdevices.length; j++)
4016 badge.append(this._device_icon(iface.subdevices[j]));
4017 else if (iface.device)
4018 badge.append(this._device_icon(iface.device));
4019 else
4020 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
4021
4022 $('<li />')
4023 .append($('<label />')
4024 .append($('<input />')
4025 .attr('name', itype + id)
4026 .attr('type', itype)
4027 .attr('value', iface.name)
4028 .prop('checked', !!check[iface.name])
4029 .addClass('cbi-input-' + itype))
4030 .append(badge))
4031 .appendTo(ul);
4032 }
4033 }
4034
4035 if (!this.options.multiple)
4036 {
4037 $('<li />')
4038 .append($('<label />')
4039 .append($('<input />')
4040 .attr('name', itype + id)
4041 .attr('type', itype)
4042 .attr('value', '')
4043 .prop('checked', !value)
4044 .addClass('cbi-input-' + itype))
4045 .append(_luci2.tr('unspecified')))
4046 .appendTo(ul);
4047 }
4048
4049 return ul;
4050 },
4051
4052 ucivalue: function(sid)
4053 {
4054 var v = this.callSuper('ucivalue', sid);
4055
4056 if (!this.options.multiple)
4057 {
4058 if ($.isArray(v))
4059 {
4060 return v[0];
4061 }
4062 else if (typeof(v) == 'string')
4063 {
4064 v = v.match(/\S+/);
4065 return v ? v[0] : undefined;
4066 }
4067
4068 return v;
4069 }
4070 else
4071 {
4072 if (typeof(v) == 'string')
4073 v = v.match(/\S+/g);
4074
4075 return v || [ ];
4076 }
4077 },
4078
4079 formvalue: function(sid)
4080 {
4081 var inputs = $('#' + this.id(sid) + ' input');
4082
4083 if (!this.options.multiple)
4084 {
4085 for (var i = 0; i < inputs.length; i++)
4086 if (inputs[i].checked && inputs[i].value !== '')
4087 return inputs[i].value;
4088
4089 return undefined;
4090 }
4091
4092 var rv = [ ];
4093
4094 for (var i = 0; i < inputs.length; i++)
4095 if (inputs[i].checked)
4096 rv.push(inputs[i].value);
4097
4098 return rv.length ? rv : undefined;
4099 }
4100 });
4101
4102
4103 var AbstractSection = AbstractWidget.extend({
4104 id: function()
4105 {
4106 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
4107
4108 for (var i = 1; i < arguments.length; i++)
4109 s.push(arguments[i].replace(/\./g, '_'));
4110
4111 return s.join('_');
4112 },
4113
4114 option: function(widget, name, options)
4115 {
4116 if (this.tabs.length == 0)
4117 this.tab({ id: '__default__', selected: true });
4118
4119 return this.taboption('__default__', widget, name, options);
4120 },
4121
4122 tab: function(options)
4123 {
4124 if (options.selected)
4125 this.tabs.selected = this.tabs.length;
4126
4127 this.tabs.push({
4128 id: options.id,
4129 caption: options.caption,
4130 description: options.description,
4131 fields: [ ],
4132 li: { }
4133 });
4134 },
4135
4136 taboption: function(tabid, widget, name, options)
4137 {
4138 var tab;
4139 for (var i = 0; i < this.tabs.length; i++)
4140 {
4141 if (this.tabs[i].id == tabid)
4142 {
4143 tab = this.tabs[i];
4144 break;
4145 }
4146 }
4147
4148 if (!tab)
4149 throw 'Cannot append to unknown tab ' + tabid;
4150
4151 var w = widget ? new widget(name, options) : null;
4152
4153 if (!(w instanceof AbstractValue))
4154 throw 'Widget must be an instance of AbstractValue';
4155
4156 w.section = this;
4157 w.map = this.map;
4158
4159 this.fields[name] = w;
4160 tab.fields.push(w);
4161
4162 return w;
4163 },
4164
4165 ucipackages: function(pkg)
4166 {
4167 for (var i = 0; i < this.tabs.length; i++)
4168 for (var j = 0; j < this.tabs[i].fields.length; j++)
4169 if (this.tabs[i].fields[j].options.uci_package)
4170 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4171 },
4172
4173 formvalue: function()
4174 {
4175 var rv = { };
4176
4177 this.sections(function(s) {
4178 var sid = s['.name'];
4179 var sv = rv[sid] || (rv[sid] = { });
4180
4181 for (var i = 0; i < this.tabs.length; i++)
4182 for (var j = 0; j < this.tabs[i].fields.length; j++)
4183 {
4184 var val = this.tabs[i].fields[j].formvalue(sid);
4185 sv[this.tabs[i].fields[j].name] = val;
4186 }
4187 });
4188
4189 return rv;
4190 },
4191
4192 validate: function(sid)
4193 {
4194 var rv = true;
4195
4196 if (!sid)
4197 {
4198 var as = this.sections();
4199 for (var i = 0; i < as.length; i++)
4200 if (!this.validate(as[i]['.name']))
4201 rv = false;
4202 return rv;
4203 }
4204
4205 var inst = this.instance[sid];
4206 var sv = rv[sid] || (rv[sid] = { });
4207
4208 var invals = 0;
4209 var legend = $('#' + this.id('sort', sid)).find('legend:first');
4210
4211 legend.children('span').detach();
4212
4213 for (var i = 0; i < this.tabs.length; i++)
4214 {
4215 var inval = 0;
4216 var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
4217
4218 tab.children('span').detach();
4219
4220 for (var j = 0; j < this.tabs[i].fields.length; j++)
4221 if (!this.tabs[i].fields[j].validate(sid))
4222 inval++;
4223
4224 if (inval > 0)
4225 {
4226 $('<span />')
4227 .addClass('badge')
4228 .attr('title', _luci2.tr('%d Errors'.format(inval)))
4229 .text(inval)
4230 .appendTo(tab);
4231
4232 invals += inval;
4233 tab = null;
4234 rv = false;
4235 }
4236 }
4237
4238 if (invals > 0)
4239 $('<span />')
4240 .addClass('badge')
4241 .attr('title', _luci2.tr('%d Errors'.format(invals)))
4242 .text(invals)
4243 .appendTo(legend);
4244
4245 return rv;
4246 }
4247 });
4248
4249 this.cbi.TypedSection = AbstractSection.extend({
4250 init: function(uci_type, options)
4251 {
4252 this.uci_type = uci_type;
4253 this.options = options;
4254 this.tabs = [ ];
4255 this.fields = { };
4256 this.active_panel = 0;
4257 this.active_tab = { };
4258 },
4259
4260 filter: function(section)
4261 {
4262 return true;
4263 },
4264
4265 sections: function(cb)
4266 {
4267 var s1 = this.map.ucisections(this.map.uci_package);
4268 var s2 = [ ];
4269
4270 for (var i = 0; i < s1.length; i++)
4271 if (s1[i]['.type'] == this.uci_type)
4272 if (this.filter(s1[i]))
4273 s2.push(s1[i]);
4274
4275 if (typeof(cb) == 'function')
4276 for (var i = 0; i < s2.length; i++)
4277 cb.apply(this, [ s2[i] ]);
4278
4279 return s2;
4280 },
4281
4282 add: function(name)
4283 {
4284 this.map.add(this.map.uci_package, this.uci_type, name);
4285 },
4286
4287 remove: function(sid)
4288 {
4289 this.map.remove(this.map.uci_package, sid);
4290 },
4291
4292 _add: function(ev)
4293 {
4294 var addb = $(this);
4295 var name = undefined;
4296 var self = ev.data.self;
4297
4298 if (addb.prev().prop('nodeName') == 'INPUT')
4299 name = addb.prev().val();
4300
4301 if (addb.prop('disabled') || name === '')
4302 return;
4303
4304 self.active_panel = -1;
4305 self.map.save();
4306 self.add(name);
4307 self.map.redraw();
4308 },
4309
4310 _remove: function(ev)
4311 {
4312 var self = ev.data.self;
4313 var sid = ev.data.sid;
4314
4315 self.map.save();
4316 self.remove(sid);
4317 self.map.redraw();
4318
4319 ev.stopPropagation();
4320 },
4321
4322 _sid: function(ev)
4323 {
4324 var self = ev.data.self;
4325 var text = $(this);
4326 var addb = text.next();
4327 var errt = addb.next();
4328 var name = text.val();
4329 var used = false;
4330
4331 if (!/^[a-zA-Z0-9_]*$/.test(name))
4332 {
4333 errt.text(_luci2.tr('Invalid section name')).show();
4334 text.addClass('error');
4335 addb.prop('disabled', true);
4336 return false;
4337 }
4338
4339 for (var sid in self.map.uci.values[self.map.uci_package])
4340 if (sid == name)
4341 {
4342 used = true;
4343 break;
4344 }
4345
4346 for (var sid in self.map.uci.creates[self.map.uci_package])
4347 if (sid == name)
4348 {
4349 used = true;
4350 break;
4351 }
4352
4353 if (used)
4354 {
4355 errt.text(_luci2.tr('Name already used')).show();
4356 text.addClass('error');
4357 addb.prop('disabled', true);
4358 return false;
4359 }
4360
4361 errt.text('').hide();
4362 text.removeClass('error');
4363 addb.prop('disabled', false);
4364 return true;
4365 },
4366
4367 teaser: function(sid)
4368 {
4369 var tf = this.teaser_fields;
4370
4371 if (!tf)
4372 {
4373 tf = this.teaser_fields = [ ];
4374
4375 if ($.isArray(this.options.teasers))
4376 {
4377 for (var i = 0; i < this.options.teasers.length; i++)
4378 {
4379 var f = this.options.teasers[i];
4380 if (f instanceof AbstractValue)
4381 tf.push(f);
4382 else if (typeof(f) == 'string' && this.fields[f] instanceof AbstractValue)
4383 tf.push(this.fields[f]);
4384 }
4385 }
4386 else
4387 {
4388 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
4389 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
4390 tf.push(this.tabs[i].fields[j]);
4391 }
4392 }
4393
4394 var t = '';
4395
4396 for (var i = 0; i < tf.length; i++)
4397 {
4398 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
4399 continue;
4400
4401 var n = tf[i].options.caption || tf[i].name;
4402 var v = tf[i].textvalue(sid);
4403
4404 if (typeof(v) == 'undefined')
4405 continue;
4406
4407 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
4408 }
4409
4410 return t;
4411 },
4412
4413 _render_add: function()
4414 {
4415 var text = _luci2.tr('Add section');
4416 var ttip = _luci2.tr('Create new section...');
4417
4418 if ($.isArray(this.options.add_caption))
4419 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
4420 else if (typeof(this.options.add_caption) == 'string')
4421 text = this.options.add_caption, ttip = '';
4422
4423 var add = $('<div />').addClass('cbi-section-add');
4424
4425 if (this.options.anonymous === false)
4426 {
4427 $('<input />')
4428 .addClass('cbi-input-text')
4429 .attr('type', 'text')
4430 .attr('placeholder', ttip)
4431 .blur({ self: this }, this._sid)
4432 .keyup({ self: this }, this._sid)
4433 .appendTo(add);
4434
4435 $('<img />')
4436 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
4437 .attr('title', text)
4438 .addClass('cbi-button')
4439 .click({ self: this }, this._add)
4440 .appendTo(add);
4441
4442 $('<div />')
4443 .addClass('cbi-value-error')
4444 .hide()
4445 .appendTo(add);
4446 }
4447 else
4448 {
4449 $('<input />')
4450 .attr('type', 'button')
4451 .addClass('cbi-button')
4452 .addClass('cbi-button-add')
4453 .val(text).attr('title', ttip)
4454 .click({ self: this }, this._add)
4455 .appendTo(add)
4456 }
4457
4458 return add;
4459 },
4460
4461 _render_remove: function(sid)
4462 {
4463 var text = _luci2.tr('Remove');
4464 var ttip = _luci2.tr('Remove this section');
4465
4466 if ($.isArray(this.options.remove_caption))
4467 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
4468 else if (typeof(this.options.remove_caption) == 'string')
4469 text = this.options.remove_caption, ttip = '';
4470
4471 return $('<input />')
4472 .attr('type', 'button')
4473 .addClass('cbi-button')
4474 .addClass('cbi-button-remove')
4475 .val(text).attr('title', ttip)
4476 .click({ self: this, sid: sid }, this._remove);
4477 },
4478
4479 _render_caption: function(sid)
4480 {
4481 if (typeof(this.options.caption) == 'string')
4482 {
4483 return $('<legend />')
4484 .text(this.options.caption.format(sid));
4485 }
4486 else if (typeof(this.options.caption) == 'function')
4487 {
4488 return $('<legend />')
4489 .text(this.options.caption.call(this, sid));
4490 }
4491
4492 return '';
4493 },
4494
4495 render: function()
4496 {
4497 var allsections = $();
4498 var panel_index = 0;
4499
4500 this.instance = { };
4501
4502 var s = this.sections();
4503
4504 if (s.length == 0)
4505 {
4506 var fieldset = $('<fieldset />')
4507 .addClass('cbi-section');
4508
4509 var head = $('<div />')
4510 .addClass('cbi-section-head')
4511 .appendTo(fieldset);
4512
4513 head.append(this._render_caption(undefined));
4514
4515 if (typeof(this.options.description) == 'string')
4516 {
4517 $('<div />')
4518 .addClass('cbi-section-descr')
4519 .text(this.options.description)
4520 .appendTo(head);
4521 }
4522
4523 allsections = allsections.add(fieldset);
4524 }
4525
4526 for (var i = 0; i < s.length; i++)
4527 {
4528 var sid = s[i]['.name'];
4529 var inst = this.instance[sid] = { tabs: [ ] };
4530
4531 var fieldset = $('<fieldset />')
4532 .attr('id', this.id('sort', sid))
4533 .addClass('cbi-section');
4534
4535 var head = $('<div />')
4536 .addClass('cbi-section-head')
4537 .attr('cbi-section-num', this.index)
4538 .attr('cbi-section-id', sid);
4539
4540 head.append(this._render_caption(sid));
4541
4542 if (typeof(this.options.description) == 'string')
4543 {
4544 $('<div />')
4545 .addClass('cbi-section-descr')
4546 .text(this.options.description)
4547 .appendTo(head);
4548 }
4549
4550 var teaser;
4551 if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
4552 teaser = $('<div />')
4553 .addClass('cbi-section-teaser')
4554 .appendTo(head);
4555
4556 if (this.options.addremove)
4557 $('<div />')
4558 .addClass('cbi-section-remove')
4559 .addClass('right')
4560 .append(this._render_remove(sid))
4561 .appendTo(head);
4562
4563 var body = $('<div />')
4564 .attr('index', panel_index++);
4565
4566 var fields = $('<fieldset />')
4567 .addClass('cbi-section-node');
4568
4569 if (this.tabs.length > 1)
4570 {
4571 var menu = $('<ul />')
4572 .addClass('cbi-tabmenu');
4573
4574 for (var j = 0; j < this.tabs.length; j++)
4575 {
4576 var tabid = this.id('tab', sid, this.tabs[j].id);
4577 var theadid = this.id('tabhead', sid, this.tabs[j].id);
4578
4579 var tabc = $('<div />')
4580 .addClass('cbi-tabcontainer')
4581 .attr('id', tabid)
4582 .attr('index', j);
4583
4584 if (typeof(this.tabs[j].description) == 'string')
4585 {
4586 $('<div />')
4587 .addClass('cbi-tab-descr')
4588 .text(this.tabs[j].description)
4589 .appendTo(tabc);
4590 }
4591
4592 for (var k = 0; k < this.tabs[j].fields.length; k++)
4593 this.tabs[j].fields[k].render(sid).appendTo(tabc);
4594
4595 tabc.appendTo(fields);
4596 tabc = null;
4597
4598 $('<li />').attr('id', theadid).append(
4599 $('<a />')
4600 .text(this.tabs[j].caption.format(this.tabs[j].id))
4601 .attr('href', '#' + tabid)
4602 ).appendTo(menu);
4603 }
4604
4605 menu.appendTo(body);
4606 menu = null;
4607
4608 fields.appendTo(body);
4609 fields = null;
4610
4611 var t = body.tabs({ active: this.active_tab[sid] });
4612
4613 t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
4614 var d = ev.data;
4615 d.self.validate();
4616 d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
4617 });
4618 }
4619 else
4620 {
4621 for (var j = 0; j < this.tabs[0].fields.length; j++)
4622 this.tabs[0].fields[j].render(sid).appendTo(fields);
4623
4624 fields.appendTo(body);
4625 fields = null;
4626 }
4627
4628 head.appendTo(fieldset);
4629 head = null;
4630
4631 body.appendTo(fieldset);
4632 body = null;
4633
4634 allsections = allsections.add(fieldset);
4635 fieldset = null;
4636
4637 //this.validate(sid);
4638 //
4639 //if (teaser)
4640 // teaser.append(this.teaser(sid));
4641 }
4642
4643 if (this.options.collabsible && s.length > 1)
4644 {
4645 var a = $('<div />').append(allsections).accordion({
4646 header: '> fieldset > div.cbi-section-head',
4647 heightStyle: 'content',
4648 active: this.active_panel
4649 });
4650
4651 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4652 var h = ui.oldHeader;
4653 var s = ev.data.self;
4654 var i = h.attr('cbi-section-id');
4655
4656 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4657 s.validate();
4658 });
4659
4660 a.on('accordionactivate', { self: this }, function(ev, ui) {
4661 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4662 });
4663
4664 if (this.options.sortable)
4665 {
4666 var s = a.sortable({
4667 axis: 'y',
4668 handle: 'div.cbi-section-head'
4669 });
4670
4671 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4672 var sections = [ ];
4673 for (var i = 0; i < ev.data.ids.length; i++)
4674 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4675 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4676 });
4677
4678 s.on('sortstop', function(ev, ui) {
4679 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4680 });
4681 }
4682
4683 if (this.options.addremove)
4684 this._render_add().appendTo(a);
4685
4686 return a;
4687 }
4688
4689 if (this.options.addremove)
4690 allsections = allsections.add(this._render_add());
4691
4692 return allsections;
4693 },
4694
4695 finish: function()
4696 {
4697 var s = this.sections();
4698
4699 for (var i = 0; i < s.length; i++)
4700 {
4701 var sid = s[i]['.name'];
4702
4703 this.validate(sid);
4704
4705 $('#' + this.id('sort', sid))
4706 .children('.cbi-section-head')
4707 .children('.cbi-section-teaser')
4708 .append(this.teaser(sid));
4709 }
4710 }
4711 });
4712
4713 this.cbi.TableSection = this.cbi.TypedSection.extend({
4714 render: function()
4715 {
4716 var allsections = $();
4717 var panel_index = 0;
4718
4719 this.instance = { };
4720
4721 var s = this.sections();
4722
4723 var fieldset = $('<fieldset />')
4724 .addClass('cbi-section');
4725
4726 fieldset.append(this._render_caption(sid));
4727
4728 if (typeof(this.options.description) == 'string')
4729 {
4730 $('<div />')
4731 .addClass('cbi-section-descr')
4732 .text(this.options.description)
4733 .appendTo(fieldset);
4734 }
4735
4736 var fields = $('<div />')
4737 .addClass('cbi-section-node')
4738 .appendTo(fieldset);
4739
4740 var table = $('<table />')
4741 .addClass('cbi-section-table')
4742 .appendTo(fields);
4743
4744 var thead = $('<thead />')
4745 .append($('<tr />').addClass('cbi-section-table-titles'))
4746 .appendTo(table);
4747
4748 for (var j = 0; j < this.tabs[0].fields.length; j++)
4749 $('<th />')
4750 .addClass('cbi-section-table-cell')
4751 .css('width', this.tabs[0].fields[j].options.width || '')
4752 .append(this.tabs[0].fields[j].options.caption)
4753 .appendTo(thead.children());
4754
4755 if (this.options.sortable)
4756 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4757
4758 if (this.options.addremove !== false)
4759 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4760
4761 var tbody = $('<tbody />')
4762 .appendTo(table);
4763
4764 if (s.length == 0)
4765 {
4766 $('<tr />')
4767 .addClass('cbi-section-table-row')
4768 .append(
4769 $('<td />')
4770 .addClass('cbi-section-table-cell')
4771 .addClass('cbi-section-table-placeholder')
4772 .attr('colspan', thead.children().children().length)
4773 .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
4774 .appendTo(tbody);
4775 }
4776
4777 for (var i = 0; i < s.length; i++)
4778 {
4779 var sid = s[i]['.name'];
4780 var inst = this.instance[sid] = { tabs: [ ] };
4781
4782 var row = $('<tr />')
4783 .addClass('cbi-section-table-row')
4784 .appendTo(tbody);
4785
4786 for (var j = 0; j < this.tabs[0].fields.length; j++)
4787 {
4788 $('<td />')
4789 .addClass('cbi-section-table-cell')
4790 .css('width', this.tabs[0].fields[j].options.width || '')
4791 .append(this.tabs[0].fields[j].render(sid, true))
4792 .appendTo(row);
4793 }
4794
4795 if (this.options.sortable)
4796 {
4797 $('<td />')
4798 .addClass('cbi-section-table-cell')
4799 .addClass('cbi-section-table-sort')
4800 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
4801 .append($('<br />'))
4802 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
4803 .appendTo(row);
4804 }
4805
4806 if (this.options.addremove !== false)
4807 {
4808 $('<td />')
4809 .addClass('cbi-section-table-cell')
4810 .append(this._render_remove(sid))
4811 .appendTo(row);
4812 }
4813
4814 this.validate(sid);
4815
4816 row = null;
4817 }
4818
4819 if (this.options.sortable)
4820 {
4821 var s = tbody.sortable({
4822 handle: 'td.cbi-section-table-sort'
4823 });
4824
4825 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4826 var sections = [ ];
4827 for (var i = 0; i < ev.data.ids.length; i++)
4828 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4829 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4830 });
4831
4832 s.on('sortstop', function(ev, ui) {
4833 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4834 });
4835 }
4836
4837 if (this.options.addremove)
4838 this._render_add().appendTo(fieldset);
4839
4840 fields = table = thead = tbody = null;
4841
4842 return fieldset;
4843 }
4844 });
4845
4846 this.cbi.NamedSection = this.cbi.TypedSection.extend({
4847 sections: function(cb)
4848 {
4849 var sa = [ ];
4850 var pkg = this.map.uci.values[this.map.uci_package];
4851
4852 for (var s in pkg)
4853 if (pkg[s]['.name'] == this.uci_type)
4854 {
4855 sa.push(pkg[s]);
4856 break;
4857 }
4858
4859 if (typeof(cb) == 'function' && sa.length > 0)
4860 cb.apply(this, [ sa[0] ]);
4861
4862 return sa;
4863 }
4864 });
4865
4866 this.cbi.DummySection = this.cbi.TypedSection.extend({
4867 sections: function(cb)
4868 {
4869 if (typeof(cb) == 'function')
4870 cb.apply(this, [ { '.name': this.uci_type } ]);
4871
4872 return [ { '.name': this.uci_type } ];
4873 }
4874 });
4875
4876 this.cbi.Map = AbstractWidget.extend({
4877 init: function(uci_package, options)
4878 {
4879 var self = this;
4880
4881 this.uci_package = uci_package;
4882 this.sections = [ ];
4883 this.options = _luci2.defaults(options, {
4884 save: function() { },
4885 prepare: function() {
4886 return _luci2.uci.writable(function(writable) {
4887 self.options.readonly = !writable;
4888 });
4889 }
4890 });
4891 },
4892
4893 load: function()
4894 {
4895 this.uci = {
4896 newid: 0,
4897 values: { },
4898 creates: { },
4899 changes: { },
4900 deletes: { }
4901 };
4902
4903 this.active_panel = 0;
4904
4905 var packages = { };
4906
4907 for (var i = 0; i < this.sections.length; i++)
4908 this.sections[i].ucipackages(packages);
4909
4910 packages[this.uci_package] = true;
4911
4912 var load_cb = this._load_cb || (this._load_cb = $.proxy(function(packages) {
4913 for (var i = 0; i < packages.length; i++)
4914 {
4915 this.uci.values[packages[i]['.package']] = packages[i];
4916 delete packages[i]['.package'];
4917 }
4918
4919 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
4920
4921 for (var i = 0; i < this.sections.length; i++)
4922 {
4923 for (var f in this.sections[i].fields)
4924 {
4925 if (typeof(this.sections[i].fields[f].load) != 'function')
4926 continue;
4927
4928 var s = this.sections[i].sections();
4929 for (var j = 0; j < s.length; j++)
4930 {
4931 var rv = this.sections[i].fields[f].load(s[j]['.name']);
4932 if (_luci2.isDeferred(rv))
4933 deferreds.push(rv);
4934 }
4935 }
4936 }
4937
4938 return $.when.apply($, deferreds);
4939 }, this));
4940
4941 _luci2.rpc.batch();
4942
4943 for (var pkg in packages)
4944 _luci2.uci.get_all(pkg);
4945
4946 return _luci2.rpc.flush().then(load_cb);
4947 },
4948
4949 render: function()
4950 {
4951 var map = $('<div />').addClass('cbi-map');
4952
4953 if (typeof(this.options.caption) == 'string')
4954 $('<h2 />').text(this.options.caption).appendTo(map);
4955
4956 if (typeof(this.options.description) == 'string')
4957 $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
4958
4959 var sections = $('<div />').appendTo(map);
4960
4961 for (var i = 0; i < this.sections.length; i++)
4962 {
4963 var s = this.sections[i].render();
4964
4965 if (this.options.readonly || this.sections[i].options.readonly)
4966 s.find('input, select, button, img.cbi-button').attr('disabled', true);
4967
4968 s.appendTo(sections);
4969
4970 if (this.sections[i].options.active)
4971 this.active_panel = i;
4972 }
4973
4974 if (this.options.collabsible)
4975 {
4976 var a = sections.accordion({
4977 header: '> fieldset > div.cbi-section-head',
4978 heightStyle: 'content',
4979 active: this.active_panel
4980 });
4981
4982 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4983 var h = ui.oldHeader;
4984 var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
4985 var i = h.attr('cbi-section-id');
4986
4987 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4988
4989 for (var i = 0; i < ev.data.self.sections.length; i++)
4990 ev.data.self.sections[i].validate();
4991 });
4992
4993 a.on('accordionactivate', { self: this }, function(ev, ui) {
4994 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4995 });
4996 }
4997
4998 if (this.options.pageaction !== false)
4999 {
5000 var a = $('<div />')
5001 .addClass('cbi-page-actions')
5002 .appendTo(map);
5003
5004 $('<input />')
5005 .addClass('cbi-button').addClass('cbi-button-apply')
5006 .attr('type', 'button')
5007 .val(_luci2.tr('Save & Apply'))
5008 .appendTo(a);
5009
5010 $('<input />')
5011 .addClass('cbi-button').addClass('cbi-button-save')
5012 .attr('type', 'button')
5013 .val(_luci2.tr('Save'))
5014 .click({ self: this }, function(ev) { ev.data.self.send(); })
5015 .appendTo(a);
5016
5017 $('<input />')
5018 .addClass('cbi-button').addClass('cbi-button-reset')
5019 .attr('type', 'button')
5020 .val(_luci2.tr('Reset'))
5021 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
5022 .appendTo(a);
5023
5024 a = null;
5025 }
5026
5027 var top = $('<form />').append(map);
5028
5029 map = null;
5030
5031 return top;
5032 },
5033
5034 finish: function()
5035 {
5036 for (var i = 0; i < this.sections.length; i++)
5037 this.sections[i].finish();
5038
5039 this.validate();
5040 },
5041
5042 redraw: function()
5043 {
5044 this.target.hide().empty().append(this.render());
5045 this.finish();
5046 this.target.show();
5047 },
5048
5049 section: function(widget, uci_type, options)
5050 {
5051 var w = widget ? new widget(uci_type, options) : null;
5052
5053 if (!(w instanceof AbstractSection))
5054 throw 'Widget must be an instance of AbstractSection';
5055
5056 w.map = this;
5057 w.index = this.sections.length;
5058
5059 this.sections.push(w);
5060 return w;
5061 },
5062
5063 formvalue: function()
5064 {
5065 var rv = { };
5066
5067 for (var i = 0; i < this.sections.length; i++)
5068 {
5069 var sids = this.sections[i].formvalue();
5070 for (var sid in sids)
5071 {
5072 var s = rv[sid] || (rv[sid] = { });
5073 $.extend(s, sids[sid]);
5074 }
5075 }
5076
5077 return rv;
5078 },
5079
5080 add: function(conf, type, name)
5081 {
5082 var c = this.uci.creates;
5083 var s = '.new.%d'.format(this.uci.newid++);
5084
5085 if (!c[conf])
5086 c[conf] = { };
5087
5088 c[conf][s] = {
5089 '.type': type,
5090 '.name': s,
5091 '.create': name,
5092 '.anonymous': !name
5093 };
5094
5095 return s;
5096 },
5097
5098 remove: function(conf, sid)
5099 {
5100 var n = this.uci.creates;
5101 var c = this.uci.changes;
5102 var d = this.uci.deletes;
5103
5104 /* requested deletion of a just created section */
5105 if (sid.indexOf('.new.') == 0)
5106 {
5107 if (n[conf])
5108 delete n[conf][sid];
5109 }
5110 else
5111 {
5112 if (c[conf])
5113 delete c[conf][sid];
5114
5115 if (!d[conf])
5116 d[conf] = { };
5117
5118 d[conf][sid] = true;
5119 }
5120 },
5121
5122 ucisections: function(conf, cb)
5123 {
5124 var sa = [ ];
5125 var pkg = this.uci.values[conf];
5126 var crt = this.uci.creates[conf];
5127 var del = this.uci.deletes[conf];
5128
5129 if (!pkg)
5130 return sa;
5131
5132 for (var s in pkg)
5133 if (!del || del[s] !== true)
5134 sa.push(pkg[s]);
5135
5136 sa.sort(function(a, b) { return a['.index'] - b['.index'] });
5137
5138 if (crt)
5139 for (var s in crt)
5140 sa.push(crt[s]);
5141
5142 if (typeof(cb) == 'function')
5143 for (var i = 0; i < sa.length; i++)
5144 cb.apply(this, [ sa[i] ]);
5145
5146 return sa;
5147 },
5148
5149 get: function(conf, sid, opt)
5150 {
5151 var v = this.uci.values;
5152 var n = this.uci.creates;
5153 var c = this.uci.changes;
5154 var d = this.uci.deletes;
5155
5156 /* requested option in a just created section */
5157 if (sid.indexOf('.new.') == 0)
5158 {
5159 if (!n[conf])
5160 return undefined;
5161
5162 if (typeof(opt) == 'undefined')
5163 return (n[conf][sid] || { });
5164
5165 return n[conf][sid][opt];
5166 }
5167
5168 /* requested an option value */
5169 if (typeof(opt) != 'undefined')
5170 {
5171 /* check whether option was deleted */
5172 if (d[conf] && d[conf][sid])
5173 {
5174 if (d[conf][sid] === true)
5175 return undefined;
5176
5177 for (var i = 0; i < d[conf][sid].length; i++)
5178 if (d[conf][sid][i] == opt)
5179 return undefined;
5180 }
5181
5182 /* check whether option was changed */
5183 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
5184 return c[conf][sid][opt];
5185
5186 /* return base value */
5187 if (v[conf] && v[conf][sid])
5188 return v[conf][sid][opt];
5189
5190 return undefined;
5191 }
5192
5193 /* requested an entire section */
5194 if (v[conf])
5195 return (v[conf][sid] || { });
5196
5197 return undefined;
5198 },
5199
5200 set: function(conf, sid, opt, val)
5201 {
5202 var n = this.uci.creates;
5203 var c = this.uci.changes;
5204 var d = this.uci.deletes;
5205
5206 if (sid.indexOf('.new.') == 0)
5207 {
5208 if (n[conf] && n[conf][sid])
5209 {
5210 if (typeof(val) != 'undefined')
5211 n[conf][sid][opt] = val;
5212 else
5213 delete n[conf][sid][opt];
5214 }
5215 }
5216 else if (typeof(val) != 'undefined')
5217 {
5218 if (!c[conf])
5219 c[conf] = { };
5220
5221 if (!c[conf][sid])
5222 c[conf][sid] = { };
5223
5224 c[conf][sid][opt] = val;
5225 }
5226 else
5227 {
5228 if (!d[conf])
5229 d[conf] = { };
5230
5231 if (!d[conf][sid])
5232 d[conf][sid] = [ ];
5233
5234 d[conf][sid].push(opt);
5235 }
5236 },
5237
5238 validate: function()
5239 {
5240 var rv = true;
5241
5242 for (var i = 0; i < this.sections.length; i++)
5243 if (!this.sections[i].validate())
5244 rv = false;
5245
5246 return rv;
5247 },
5248
5249 save: function()
5250 {
5251 if (this.options.readonly)
5252 return _luci2.deferrable();
5253
5254 var deferreds = [ _luci2.deferrable(this.options.save()) ];
5255
5256 for (var i = 0; i < this.sections.length; i++)
5257 {
5258 if (this.sections[i].options.readonly)
5259 continue;
5260
5261 for (var f in this.sections[i].fields)
5262 {
5263 if (typeof(this.sections[i].fields[f].save) != 'function')
5264 continue;
5265
5266 var s = this.sections[i].sections();
5267 for (var j = 0; j < s.length; j++)
5268 {
5269 var rv = this.sections[i].fields[f].save(s[j]['.name']);
5270 if (_luci2.isDeferred(rv))
5271 deferreds.push(rv);
5272 }
5273 }
5274 }
5275
5276 return $.when.apply($, deferreds);
5277 },
5278
5279 send: function()
5280 {
5281 if (!this.validate())
5282 return _luci2.deferrable();
5283
5284 var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
5285 _luci2.rpc.batch();
5286
5287 if (this.uci.creates)
5288 for (var c in this.uci.creates)
5289 for (var s in this.uci.creates[c])
5290 {
5291 var r = {
5292 config: c,
5293 values: { }
5294 };
5295
5296 for (var k in this.uci.creates[c][s])
5297 {
5298 if (k == '.type')
5299 r.type = this.uci.creates[i][k];
5300 else if (k == '.create')
5301 r.name = this.uci.creates[i][k];
5302 else if (k.charAt(0) != '.')
5303 r.values[k] = this.uci.creates[i][k];
5304 }
5305
5306 _luci2.uci.add(r.config, r.type, r.name, r.values);
5307 }
5308
5309 if (this.uci.changes)
5310 for (var c in this.uci.changes)
5311 for (var s in this.uci.changes[c])
5312 _luci2.uci.set(c, s, this.uci.changes[c][s]);
5313
5314 if (this.uci.deletes)
5315 for (var c in this.uci.deletes)
5316 for (var s in this.uci.deletes[c])
5317 {
5318 var o = this.uci.deletes[c][s];
5319 _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
5320 }
5321
5322 return _luci2.rpc.flush();
5323 }, this));
5324
5325 var self = this;
5326
5327 _luci2.ui.loading(true);
5328
5329 return this.save().then(send_cb).then(function() {
5330 return self.load();
5331 }).then(function() {
5332 self.redraw();
5333 self = null;
5334
5335 _luci2.ui.loading(false);
5336 });
5337 },
5338
5339 dialog: function(id)
5340 {
5341 var d = $('<div />');
5342 var p = $('<p />');
5343
5344 $('<img />')
5345 .attr('src', _luci2.globals.resource + '/icons/loading.gif')
5346 .css('vertical-align', 'middle')
5347 .css('padding-right', '10px')
5348 .appendTo(p);
5349
5350 p.append(_luci2.tr('Loading data...'));
5351
5352 p.appendTo(d);
5353 d.appendTo(id);
5354
5355 return d.dialog({
5356 modal: true,
5357 draggable: false,
5358 resizable: false,
5359 height: 90,
5360 open: function() {
5361 $(this).parent().children('.ui-dialog-titlebar').hide();
5362 }
5363 });
5364 },
5365
5366 insertInto: function(id)
5367 {
5368 var self = this;
5369 self.target = $(id);
5370
5371 _luci2.ui.loading(true);
5372 self.target.hide();
5373
5374 return self.load().then(function() {
5375 self.target.empty().append(self.render());
5376 self.finish();
5377 self.target.show();
5378 self = null;
5379 _luci2.ui.loading(false);
5380 });
5381 }
5382 });
5383 };