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