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