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