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