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