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