luci2: implement LuCI2.session.updateACLs() and LuCI2.session.hasACL()
[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 _acls: { },
2212
2213 _fetch_acls: _luci2.rpc.declare({
2214 object: 'session',
2215 method: 'access',
2216 expect: { '': { } }
2217 }),
2218
2219 _fetch_acls_cb: function(acls)
2220 {
2221 _luci2.session._acls = acls;
2222 },
2223
2224 updateACLs: function()
2225 {
2226 return _luci2.session._fetch_acls()
2227 .then(_luci2.session._fetch_acls_cb);
2228 },
2229
2230 hasACL: function(scope, object, func)
2231 {
2232 var acls = _luci2.session._acls;
2233
2234 if (typeof(func) == 'undefined')
2235 return (acls && acls[scope] && acls[scope][object]);
2236
2237 if (acls && acls[scope] && acls[scope][object])
2238 for (var i = 0; i < acls[scope][object].length; i++)
2239 if (acls[scope][object][i] == func)
2240 return true;
2241
2242 return false;
2243 }
2244 };
2245
2246 this.ui = {
2247
2248 saveScrollTop: function()
2249 {
2250 this._scroll_top = $(document).scrollTop();
2251 },
2252
2253 restoreScrollTop: function()
2254 {
2255 if (typeof(this._scroll_top) == 'undefined')
2256 return;
2257
2258 $(document).scrollTop(this._scroll_top);
2259
2260 delete this._scroll_top;
2261 },
2262
2263 loading: function(enable)
2264 {
2265 var win = $(window);
2266 var body = $('body');
2267
2268 var state = _luci2.ui._loading || (_luci2.ui._loading = {
2269 modal: $('<div />')
2270 .addClass('modal fade')
2271 .append($('<div />')
2272 .addClass('modal-dialog')
2273 .append($('<div />')
2274 .addClass('modal-content luci2-modal-loader')
2275 .append($('<div />')
2276 .addClass('modal-body')
2277 .text(_luci2.tr('Loading data…')))))
2278 .appendTo(body)
2279 .modal({
2280 backdrop: 'static',
2281 keyboard: false
2282 })
2283 });
2284
2285 state.modal.modal(enable ? 'show' : 'hide');
2286 },
2287
2288 dialog: function(title, content, options)
2289 {
2290 var win = $(window);
2291 var body = $('body');
2292
2293 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
2294 dialog: $('<div />')
2295 .addClass('modal fade')
2296 .append($('<div />')
2297 .addClass('modal-dialog')
2298 .append($('<div />')
2299 .addClass('modal-content')
2300 .append($('<div />')
2301 .addClass('modal-header')
2302 .append('<h4 />')
2303 .addClass('modal-title'))
2304 .append($('<div />')
2305 .addClass('modal-body'))
2306 .append($('<div />')
2307 .addClass('modal-footer')
2308 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2309 .click(function() {
2310 $(this).parents('div.modal').modal('hide');
2311 })))))
2312 .appendTo(body)
2313 });
2314
2315 if (typeof(options) != 'object')
2316 options = { };
2317
2318 if (title === false)
2319 {
2320 state.dialog.modal('hide');
2321
2322 return;
2323 }
2324
2325 var cnt = state.dialog.children().children().children('div.modal-body');
2326 var ftr = state.dialog.children().children().children('div.modal-footer');
2327
2328 ftr.empty();
2329
2330 if (options.style == 'confirm')
2331 {
2332 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
2333 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
2334
2335 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
2336 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
2337 }
2338 else if (options.style == 'close')
2339 {
2340 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2341 .click(options.close || function() { _luci2.ui.dialog(false) }));
2342 }
2343 else if (options.style == 'wait')
2344 {
2345 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2346 .attr('disabled', true));
2347 }
2348
2349 state.dialog.find('h4:first').text(title);
2350 state.dialog.modal('show');
2351
2352 cnt.empty().append(content);
2353 },
2354
2355 upload: function(title, content, options)
2356 {
2357 var state = _luci2.ui._upload || (_luci2.ui._upload = {
2358 form: $('<form />')
2359 .attr('method', 'post')
2360 .attr('action', '/cgi-bin/luci-upload')
2361 .attr('enctype', 'multipart/form-data')
2362 .attr('target', 'cbi-fileupload-frame')
2363 .append($('<p />'))
2364 .append($('<input />')
2365 .attr('type', 'hidden')
2366 .attr('name', 'sessionid'))
2367 .append($('<input />')
2368 .attr('type', 'hidden')
2369 .attr('name', 'filename'))
2370 .append($('<input />')
2371 .attr('type', 'file')
2372 .attr('name', 'filedata')
2373 .addClass('cbi-input-file'))
2374 .append($('<div />')
2375 .css('width', '100%')
2376 .addClass('progress progress-striped active')
2377 .append($('<div />')
2378 .addClass('progress-bar')
2379 .css('width', '100%')))
2380 .append($('<iframe />')
2381 .addClass('pull-right')
2382 .attr('name', 'cbi-fileupload-frame')
2383 .css('width', '1px')
2384 .css('height', '1px')
2385 .css('visibility', 'hidden')),
2386
2387 finish_cb: function(ev) {
2388 $(this).off('load');
2389
2390 var body = (this.contentDocument || this.contentWindow.document).body;
2391 if (body.firstChild.tagName.toLowerCase() == 'pre')
2392 body = body.firstChild;
2393
2394 var json;
2395 try {
2396 json = $.parseJSON(body.innerHTML);
2397 } catch(e) {
2398 json = {
2399 message: _luci2.tr('Invalid server response received'),
2400 error: [ -1, _luci2.tr('Invalid data') ]
2401 };
2402 };
2403
2404 if (json.error)
2405 {
2406 L.ui.dialog(L.tr('File upload'), [
2407 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
2408 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
2409 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
2410 ], { style: 'close' });
2411 }
2412 else if (typeof(state.success_cb) == 'function')
2413 {
2414 state.success_cb(json);
2415 }
2416 },
2417
2418 confirm_cb: function() {
2419 var f = state.form.find('.cbi-input-file');
2420 var b = state.form.find('.progress');
2421 var p = state.form.find('p');
2422
2423 if (!f.val())
2424 return;
2425
2426 state.form.find('iframe').on('load', state.finish_cb);
2427 state.form.submit();
2428
2429 f.hide();
2430 b.show();
2431 p.text(_luci2.tr('File upload in progress …'));
2432
2433 state.form.parent().parent().find('button').prop('disabled', true);
2434 }
2435 });
2436
2437 state.form.find('.progress').hide();
2438 state.form.find('.cbi-input-file').val('').show();
2439 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
2440
2441 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
2442 state.form.find('[name=filename]').val(options.filename);
2443
2444 state.success_cb = options.success;
2445
2446 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
2447 style: 'confirm',
2448 confirm: state.confirm_cb
2449 });
2450 },
2451
2452 reconnect: function()
2453 {
2454 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
2455 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
2456 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
2457 var images = $();
2458 var interval, timeout;
2459
2460 _luci2.ui.dialog(
2461 _luci2.tr('Waiting for device'), [
2462 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
2463 $('<div />')
2464 .css('width', '100%')
2465 .addClass('progressbar')
2466 .addClass('intermediate')
2467 .append($('<div />')
2468 .css('width', '100%'))
2469 ], { style: 'wait' }
2470 );
2471
2472 for (var i = 0; i < protocols.length; i++)
2473 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
2474
2475 //_luci2.network.getNetworkStatus(function(s) {
2476 // for (var i = 0; i < protocols.length; i++)
2477 // {
2478 // for (var j = 0; j < s.length; j++)
2479 // {
2480 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
2481 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
2482 //
2483 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
2484 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
2485 // }
2486 // }
2487 //}).then(function() {
2488 images.on('load', function() {
2489 var url = this.getAttribute('url');
2490 _luci2.session.isAlive().then(function(access) {
2491 if (access)
2492 {
2493 window.clearTimeout(timeout);
2494 window.clearInterval(interval);
2495 _luci2.ui.dialog(false);
2496 images = null;
2497 }
2498 else
2499 {
2500 location.href = url;
2501 }
2502 });
2503 });
2504
2505 interval = window.setInterval(function() {
2506 images.each(function() {
2507 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
2508 });
2509 }, 5000);
2510
2511 timeout = window.setTimeout(function() {
2512 window.clearInterval(interval);
2513 images.off('load');
2514
2515 _luci2.ui.dialog(
2516 _luci2.tr('Device not responding'),
2517 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2518 { style: 'close' }
2519 );
2520 }, 180000);
2521 //});
2522 },
2523
2524 login: function(invalid)
2525 {
2526 var state = _luci2.ui._login || (_luci2.ui._login = {
2527 form: $('<form />')
2528 .attr('target', '')
2529 .attr('method', 'post')
2530 .append($('<p />')
2531 .addClass('alert-message')
2532 .text(_luci2.tr('Wrong username or password given!')))
2533 .append($('<p />')
2534 .append($('<label />')
2535 .text(_luci2.tr('Username'))
2536 .append($('<br />'))
2537 .append($('<input />')
2538 .attr('type', 'text')
2539 .attr('name', 'username')
2540 .attr('value', 'root')
2541 .addClass('form-control')
2542 .keypress(function(ev) {
2543 if (ev.which == 10 || ev.which == 13)
2544 state.confirm_cb();
2545 }))))
2546 .append($('<p />')
2547 .append($('<label />')
2548 .text(_luci2.tr('Password'))
2549 .append($('<br />'))
2550 .append($('<input />')
2551 .attr('type', 'password')
2552 .attr('name', 'password')
2553 .addClass('form-control')
2554 .keypress(function(ev) {
2555 if (ev.which == 10 || ev.which == 13)
2556 state.confirm_cb();
2557 }))))
2558 .append($('<p />')
2559 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
2560
2561 response_cb: function(response) {
2562 if (!response.ubus_rpc_session)
2563 {
2564 _luci2.ui.login(true);
2565 }
2566 else
2567 {
2568 _luci2.globals.sid = response.ubus_rpc_session;
2569 _luci2.setHash('id', _luci2.globals.sid);
2570 _luci2.session.startHeartbeat();
2571 _luci2.ui.dialog(false);
2572 state.deferred.resolve();
2573 }
2574 },
2575
2576 confirm_cb: function() {
2577 var u = state.form.find('[name=username]').val();
2578 var p = state.form.find('[name=password]').val();
2579
2580 if (!u)
2581 return;
2582
2583 _luci2.ui.dialog(
2584 _luci2.tr('Logging in'), [
2585 $('<p />').text(_luci2.tr('Log in in progress …')),
2586 $('<div />')
2587 .css('width', '100%')
2588 .addClass('progressbar')
2589 .addClass('intermediate')
2590 .append($('<div />')
2591 .css('width', '100%'))
2592 ], { style: 'wait' }
2593 );
2594
2595 _luci2.globals.sid = '00000000000000000000000000000000';
2596 _luci2.session.login(u, p).then(state.response_cb);
2597 }
2598 });
2599
2600 if (!state.deferred || state.deferred.state() != 'pending')
2601 state.deferred = $.Deferred();
2602
2603 /* try to find sid from hash */
2604 var sid = _luci2.getHash('id');
2605 if (sid && sid.match(/^[a-f0-9]{32}$/))
2606 {
2607 _luci2.globals.sid = sid;
2608 _luci2.session.isAlive().then(function(access) {
2609 if (access)
2610 {
2611 _luci2.session.startHeartbeat();
2612 state.deferred.resolve();
2613 }
2614 else
2615 {
2616 _luci2.setHash('id', undefined);
2617 _luci2.ui.login();
2618 }
2619 });
2620
2621 return state.deferred;
2622 }
2623
2624 if (invalid)
2625 state.form.find('.alert-message').show();
2626 else
2627 state.form.find('.alert-message').hide();
2628
2629 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2630 style: 'confirm',
2631 confirm: state.confirm_cb
2632 });
2633
2634 state.form.find('[name=password]').focus();
2635
2636 return state.deferred;
2637 },
2638
2639 cryptPassword: _luci2.rpc.declare({
2640 object: 'luci2.ui',
2641 method: 'crypt',
2642 params: [ 'data' ],
2643 expect: { crypt: '' }
2644 }),
2645
2646
2647 _acl_merge_scope: function(acl_scope, scope)
2648 {
2649 if ($.isArray(scope))
2650 {
2651 for (var i = 0; i < scope.length; i++)
2652 acl_scope[scope[i]] = true;
2653 }
2654 else if ($.isPlainObject(scope))
2655 {
2656 for (var object_name in scope)
2657 {
2658 if (!$.isArray(scope[object_name]))
2659 continue;
2660
2661 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2662
2663 for (var i = 0; i < scope[object_name].length; i++)
2664 acl_object[scope[object_name][i]] = true;
2665 }
2666 }
2667 },
2668
2669 _acl_merge_permission: function(acl_perm, perm)
2670 {
2671 if ($.isPlainObject(perm))
2672 {
2673 for (var scope_name in perm)
2674 {
2675 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2676 this._acl_merge_scope(acl_scope, perm[scope_name]);
2677 }
2678 }
2679 },
2680
2681 _acl_merge_group: function(acl_group, group)
2682 {
2683 if ($.isPlainObject(group))
2684 {
2685 if (!acl_group.description)
2686 acl_group.description = group.description;
2687
2688 if (group.read)
2689 {
2690 var acl_perm = acl_group.read || (acl_group.read = { });
2691 this._acl_merge_permission(acl_perm, group.read);
2692 }
2693
2694 if (group.write)
2695 {
2696 var acl_perm = acl_group.write || (acl_group.write = { });
2697 this._acl_merge_permission(acl_perm, group.write);
2698 }
2699 }
2700 },
2701
2702 _acl_merge_tree: function(acl_tree, tree)
2703 {
2704 if ($.isPlainObject(tree))
2705 {
2706 for (var group_name in tree)
2707 {
2708 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2709 this._acl_merge_group(acl_group, tree[group_name]);
2710 }
2711 }
2712 },
2713
2714 listAvailableACLs: _luci2.rpc.declare({
2715 object: 'luci2.ui',
2716 method: 'acls',
2717 expect: { acls: [ ] },
2718 filter: function(trees) {
2719 var acl_tree = { };
2720 for (var i = 0; i < trees.length; i++)
2721 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2722 return acl_tree;
2723 }
2724 }),
2725
2726 renderMainMenu: _luci2.rpc.declare({
2727 object: 'luci2.ui',
2728 method: 'menu',
2729 expect: { menu: { } },
2730 filter: function(entries) {
2731 _luci2.globals.mainMenu = new _luci2.ui.menu();
2732 _luci2.globals.mainMenu.entries(entries);
2733
2734 $('#mainmenu')
2735 .empty()
2736 .append(_luci2.globals.mainMenu.render(0, 1));
2737 }
2738 }),
2739
2740 renderViewMenu: function()
2741 {
2742 $('#viewmenu')
2743 .empty()
2744 .append(_luci2.globals.mainMenu.render(2, 900));
2745 },
2746
2747 renderView: function()
2748 {
2749 var node = arguments[0];
2750 var name = node.view.split(/\//).join('.');
2751 var args = [ ];
2752
2753 for (var i = 1; i < arguments.length; i++)
2754 args.push(arguments[i]);
2755
2756 if (_luci2.globals.currentView)
2757 _luci2.globals.currentView.finish();
2758
2759 _luci2.ui.renderViewMenu();
2760
2761 if (!_luci2._views)
2762 _luci2._views = { };
2763
2764 _luci2.setHash('view', node.view);
2765
2766 if (_luci2._views[name] instanceof _luci2.ui.view)
2767 {
2768 _luci2.globals.currentView = _luci2._views[name];
2769 return _luci2._views[name].render.apply(_luci2._views[name], args);
2770 }
2771
2772 var url = _luci2.globals.resource + '/view/' + name + '.js';
2773
2774 return $.ajax(url, {
2775 method: 'GET',
2776 cache: true,
2777 dataType: 'text'
2778 }).then(function(data) {
2779 try {
2780 var viewConstructorSource = (
2781 '(function(L, $) { ' +
2782 'return %s' +
2783 '})(_luci2, $);\n\n' +
2784 '//@ sourceURL=%s'
2785 ).format(data, url);
2786
2787 var viewConstructor = eval(viewConstructorSource);
2788
2789 _luci2._views[name] = new viewConstructor({
2790 name: name,
2791 acls: node.write || { }
2792 });
2793
2794 _luci2.globals.currentView = _luci2._views[name];
2795 return _luci2._views[name].render.apply(_luci2._views[name], args);
2796 }
2797 catch(e) {
2798 alert('Unable to instantiate view "%s": %s'.format(url, e));
2799 };
2800
2801 return $.Deferred().resolve();
2802 });
2803 },
2804
2805 updateHostname: function()
2806 {
2807 return _luci2.system.getBoardInfo().then(function(info) {
2808 if (info.hostname)
2809 $('#hostname').text(info.hostname);
2810 });
2811 },
2812
2813 updateChanges: function()
2814 {
2815 return _luci2.uci.changes().then(function(changes) {
2816 var n = 0;
2817 var html = '';
2818
2819 for (var config in changes)
2820 {
2821 var log = [ ];
2822
2823 for (var i = 0; i < changes[config].length; i++)
2824 {
2825 var c = changes[config][i];
2826
2827 switch (c[0])
2828 {
2829 case 'order':
2830 break;
2831
2832 case 'remove':
2833 if (c.length < 3)
2834 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2835 else
2836 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2837 break;
2838
2839 case 'rename':
2840 if (c.length < 4)
2841 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2842 else
2843 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2844 break;
2845
2846 case 'add':
2847 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2848 break;
2849
2850 case 'list-add':
2851 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2852 break;
2853
2854 case 'list-del':
2855 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2856 break;
2857
2858 case 'set':
2859 if (c.length < 4)
2860 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2861 else
2862 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2863 break;
2864 }
2865 }
2866
2867 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2868 n += changes[config].length;
2869 }
2870
2871 if (n > 0)
2872 $('#changes')
2873 .empty()
2874 .show()
2875 .append($('<a />')
2876 .attr('href', '#')
2877 .addClass('label')
2878 .addClass('notice')
2879 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2880 .click(function(ev) {
2881 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2882 ev.preventDefault();
2883 }));
2884 else
2885 $('#changes')
2886 .hide();
2887 });
2888 },
2889
2890 init: function()
2891 {
2892 _luci2.ui.loading(true);
2893
2894 $.when(
2895 _luci2.ui.updateHostname(),
2896 _luci2.ui.updateChanges(),
2897 _luci2.ui.renderMainMenu()
2898 ).then(function() {
2899 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2900 _luci2.ui.loading(false);
2901 })
2902 });
2903 },
2904
2905 button: function(label, style, title)
2906 {
2907 style = style || 'default';
2908
2909 return $('<button />')
2910 .attr('type', 'button')
2911 .attr('title', title ? title : '')
2912 .addClass('btn btn-' + style)
2913 .text(label);
2914 }
2915 };
2916
2917 this.ui.AbstractWidget = Class.extend({
2918 i18n: function(text) {
2919 return text;
2920 },
2921
2922 label: function() {
2923 var key = arguments[0];
2924 var args = [ ];
2925
2926 for (var i = 1; i < arguments.length; i++)
2927 args.push(arguments[i]);
2928
2929 switch (typeof(this.options[key]))
2930 {
2931 case 'undefined':
2932 return '';
2933
2934 case 'function':
2935 return this.options[key].apply(this, args);
2936
2937 default:
2938 return ''.format.apply('' + this.options[key], args);
2939 }
2940 },
2941
2942 toString: function() {
2943 return $('<div />').append(this.render()).html();
2944 },
2945
2946 insertInto: function(id) {
2947 return $(id).empty().append(this.render());
2948 },
2949
2950 appendTo: function(id) {
2951 return $(id).append(this.render());
2952 }
2953 });
2954
2955 this.ui.view = this.ui.AbstractWidget.extend({
2956 _fetch_template: function()
2957 {
2958 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2959 method: 'GET',
2960 cache: true,
2961 dataType: 'text',
2962 success: function(data) {
2963 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2964 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2965 switch (p1)
2966 {
2967 case '#':
2968 return '';
2969
2970 case ':':
2971 return _luci2.tr(p2);
2972
2973 case '=':
2974 return _luci2.globals[p2] || '';
2975
2976 default:
2977 return '(?' + match + ')';
2978 }
2979 });
2980
2981 $('#maincontent').append(data);
2982 }
2983 });
2984 },
2985
2986 execute: function()
2987 {
2988 throw "Not implemented";
2989 },
2990
2991 render: function()
2992 {
2993 var container = $('#maincontent');
2994
2995 container.empty();
2996
2997 if (this.title)
2998 container.append($('<h2 />').append(this.title));
2999
3000 if (this.description)
3001 container.append($('<p />').append(this.description));
3002
3003 var self = this;
3004 var args = [ ];
3005
3006 for (var i = 0; i < arguments.length; i++)
3007 args.push(arguments[i]);
3008
3009 return this._fetch_template().then(function() {
3010 return _luci2.deferrable(self.execute.apply(self, args));
3011 });
3012 },
3013
3014 repeat: function(func, interval)
3015 {
3016 var self = this;
3017
3018 if (!self._timeouts)
3019 self._timeouts = [ ];
3020
3021 var index = self._timeouts.length;
3022
3023 if (typeof(interval) != 'number')
3024 interval = 5000;
3025
3026 var setTimer, runTimer;
3027
3028 setTimer = function() {
3029 if (self._timeouts)
3030 self._timeouts[index] = window.setTimeout(runTimer, interval);
3031 };
3032
3033 runTimer = function() {
3034 _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
3035 };
3036
3037 runTimer();
3038 },
3039
3040 finish: function()
3041 {
3042 if ($.isArray(this._timeouts))
3043 {
3044 for (var i = 0; i < this._timeouts.length; i++)
3045 window.clearTimeout(this._timeouts[i]);
3046
3047 delete this._timeouts;
3048 }
3049 }
3050 });
3051
3052 this.ui.menu = this.ui.AbstractWidget.extend({
3053 init: function() {
3054 this._nodes = { };
3055 },
3056
3057 entries: function(entries)
3058 {
3059 for (var entry in entries)
3060 {
3061 var path = entry.split(/\//);
3062 var node = this._nodes;
3063
3064 for (i = 0; i < path.length; i++)
3065 {
3066 if (!node.childs)
3067 node.childs = { };
3068
3069 if (!node.childs[path[i]])
3070 node.childs[path[i]] = { };
3071
3072 node = node.childs[path[i]];
3073 }
3074
3075 $.extend(node, entries[entry]);
3076 }
3077 },
3078
3079 _indexcmp: function(a, b)
3080 {
3081 var x = a.index || 0;
3082 var y = b.index || 0;
3083 return (x - y);
3084 },
3085
3086 firstChildView: function(node)
3087 {
3088 if (node.view)
3089 return node;
3090
3091 var nodes = [ ];
3092 for (var child in (node.childs || { }))
3093 nodes.push(node.childs[child]);
3094
3095 nodes.sort(this._indexcmp);
3096
3097 for (var i = 0; i < nodes.length; i++)
3098 {
3099 var child = this.firstChildView(nodes[i]);
3100 if (child)
3101 {
3102 for (var key in child)
3103 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
3104 node[key] = child[key];
3105
3106 return node;
3107 }
3108 }
3109
3110 return undefined;
3111 },
3112
3113 _onclick: function(ev)
3114 {
3115 _luci2.ui.loading(true);
3116 _luci2.ui.renderView(ev.data).then(function() {
3117 _luci2.ui.loading(false);
3118 });
3119
3120 ev.preventDefault();
3121 this.blur();
3122 },
3123
3124 _render: function(childs, level, min, max)
3125 {
3126 var nodes = [ ];
3127 for (var node in childs)
3128 {
3129 var child = this.firstChildView(childs[node]);
3130 if (child)
3131 nodes.push(childs[node]);
3132 }
3133
3134 nodes.sort(this._indexcmp);
3135
3136 var list = $('<ul />');
3137
3138 if (level == 0)
3139 list.addClass('nav').addClass('navbar-nav');
3140 else if (level == 1)
3141 list.addClass('dropdown-menu').addClass('navbar-inverse');
3142
3143 for (var i = 0; i < nodes.length; i++)
3144 {
3145 if (!_luci2.globals.defaultNode)
3146 {
3147 var v = _luci2.getHash('view');
3148 if (!v || v == nodes[i].view)
3149 _luci2.globals.defaultNode = nodes[i];
3150 }
3151
3152 var item = $('<li />')
3153 .append($('<a />')
3154 .attr('href', '#')
3155 .text(_luci2.tr(nodes[i].title)))
3156 .appendTo(list);
3157
3158 if (nodes[i].childs && level < max)
3159 {
3160 item.addClass('dropdown');
3161
3162 item.find('a')
3163 .addClass('dropdown-toggle')
3164 .attr('data-toggle', 'dropdown')
3165 .append('<b class="caret"></b>');
3166
3167 item.append(this._render(nodes[i].childs, level + 1));
3168 }
3169 else
3170 {
3171 item.find('a').click(nodes[i], this._onclick);
3172 }
3173 }
3174
3175 return list.get(0);
3176 },
3177
3178 render: function(min, max)
3179 {
3180 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
3181 return this._render(top.childs, 0, min, max);
3182 },
3183
3184 getNode: function(path, max)
3185 {
3186 var p = path.split(/\//);
3187 var n = this._nodes;
3188
3189 if (typeof(max) == 'undefined')
3190 max = p.length;
3191
3192 for (var i = 0; i < max; i++)
3193 {
3194 if (!n.childs[p[i]])
3195 return undefined;
3196
3197 n = n.childs[p[i]];
3198 }
3199
3200 return n;
3201 }
3202 });
3203
3204 this.ui.table = this.ui.AbstractWidget.extend({
3205 init: function()
3206 {
3207 this._rows = [ ];
3208 },
3209
3210 row: function(values)
3211 {
3212 if ($.isArray(values))
3213 {
3214 this._rows.push(values);
3215 }
3216 else if ($.isPlainObject(values))
3217 {
3218 var v = [ ];
3219 for (var i = 0; i < this.options.columns.length; i++)
3220 {
3221 var col = this.options.columns[i];
3222
3223 if (typeof col.key == 'string')
3224 v.push(values[col.key]);
3225 else
3226 v.push(null);
3227 }
3228 this._rows.push(v);
3229 }
3230 },
3231
3232 rows: function(rows)
3233 {
3234 for (var i = 0; i < rows.length; i++)
3235 this.row(rows[i]);
3236 },
3237
3238 render: function(id)
3239 {
3240 var fieldset = document.createElement('fieldset');
3241 fieldset.className = 'cbi-section';
3242
3243 if (this.options.caption)
3244 {
3245 var legend = document.createElement('legend');
3246 $(legend).append(this.options.caption);
3247 fieldset.appendChild(legend);
3248 }
3249
3250 var table = document.createElement('table');
3251 table.className = 'table table-condensed table-hover';
3252
3253 var has_caption = false;
3254 var has_description = false;
3255
3256 for (var i = 0; i < this.options.columns.length; i++)
3257 if (this.options.columns[i].caption)
3258 {
3259 has_caption = true;
3260 break;
3261 }
3262 else if (this.options.columns[i].description)
3263 {
3264 has_description = true;
3265 break;
3266 }
3267
3268 if (has_caption)
3269 {
3270 var tr = table.insertRow(-1);
3271 tr.className = 'cbi-section-table-titles';
3272
3273 for (var i = 0; i < this.options.columns.length; i++)
3274 {
3275 var col = this.options.columns[i];
3276 var th = document.createElement('th');
3277 th.className = 'cbi-section-table-cell';
3278
3279 tr.appendChild(th);
3280
3281 if (col.width)
3282 th.style.width = col.width;
3283
3284 if (col.align)
3285 th.style.textAlign = col.align;
3286
3287 if (col.caption)
3288 $(th).append(col.caption);
3289 }
3290 }
3291
3292 if (has_description)
3293 {
3294 var tr = table.insertRow(-1);
3295 tr.className = 'cbi-section-table-descr';
3296
3297 for (var i = 0; i < this.options.columns.length; i++)
3298 {
3299 var col = this.options.columns[i];
3300 var th = document.createElement('th');
3301 th.className = 'cbi-section-table-cell';
3302
3303 tr.appendChild(th);
3304
3305 if (col.width)
3306 th.style.width = col.width;
3307
3308 if (col.align)
3309 th.style.textAlign = col.align;
3310
3311 if (col.description)
3312 $(th).append(col.description);
3313 }
3314 }
3315
3316 if (this._rows.length == 0)
3317 {
3318 if (this.options.placeholder)
3319 {
3320 var tr = table.insertRow(-1);
3321 var td = tr.insertCell(-1);
3322 td.className = 'cbi-section-table-cell';
3323
3324 td.colSpan = this.options.columns.length;
3325 $(td).append(this.options.placeholder);
3326 }
3327 }
3328 else
3329 {
3330 for (var i = 0; i < this._rows.length; i++)
3331 {
3332 var tr = table.insertRow(-1);
3333
3334 for (var j = 0; j < this.options.columns.length; j++)
3335 {
3336 var col = this.options.columns[j];
3337 var td = tr.insertCell(-1);
3338
3339 var val = this._rows[i][j];
3340
3341 if (typeof(val) == 'undefined')
3342 val = col.placeholder;
3343
3344 if (typeof(val) == 'undefined')
3345 val = '';
3346
3347 if (col.width)
3348 td.style.width = col.width;
3349
3350 if (col.align)
3351 td.style.textAlign = col.align;
3352
3353 if (typeof col.format == 'string')
3354 $(td).append(col.format.format(val));
3355 else if (typeof col.format == 'function')
3356 $(td).append(col.format(val, i));
3357 else
3358 $(td).append(val);
3359 }
3360 }
3361 }
3362
3363 this._rows = [ ];
3364 fieldset.appendChild(table);
3365
3366 return fieldset;
3367 }
3368 });
3369
3370 this.ui.progress = this.ui.AbstractWidget.extend({
3371 render: function()
3372 {
3373 var vn = parseInt(this.options.value) || 0;
3374 var mn = parseInt(this.options.max) || 100;
3375 var pc = Math.floor((100 / mn) * vn);
3376
3377 var text;
3378
3379 if (typeof(this.options.format) == 'string')
3380 text = this.options.format.format(this.options.value, this.options.max, pc);
3381 else if (typeof(this.options.format) == 'function')
3382 text = this.options.format(pc);
3383 else
3384 text = '%.2f%%'.format(pc);
3385
3386 return $('<div />')
3387 .addClass('progress')
3388 .append($('<div />')
3389 .addClass('progress-bar')
3390 .addClass('progress-bar-info')
3391 .css('width', pc + '%'))
3392 .append($('<small />')
3393 .text(text));
3394 }
3395 });
3396
3397 this.ui.devicebadge = this.ui.AbstractWidget.extend({
3398 render: function()
3399 {
3400 var l2dev = this.options.l2_device || this.options.device;
3401 var l3dev = this.options.l3_device;
3402 var dev = l3dev || l2dev || '?';
3403
3404 var span = document.createElement('span');
3405 span.className = 'badge';
3406
3407 if (typeof(this.options.signal) == 'number' ||
3408 typeof(this.options.noise) == 'number')
3409 {
3410 var r = 'none';
3411 if (typeof(this.options.signal) != 'undefined' &&
3412 typeof(this.options.noise) != 'undefined')
3413 {
3414 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
3415 if (q < 1)
3416 r = '0';
3417 else if (q < 2)
3418 r = '0-25';
3419 else if (q < 3)
3420 r = '25-50';
3421 else if (q < 4)
3422 r = '50-75';
3423 else
3424 r = '75-100';
3425 }
3426
3427 span.appendChild(document.createElement('img'));
3428 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
3429
3430 if (r == 'none')
3431 span.title = _luci2.tr('No signal');
3432 else
3433 span.title = '%s: %d %s / %s: %d %s'.format(
3434 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
3435 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
3436 );
3437 }
3438 else
3439 {
3440 var type = 'ethernet';
3441 var desc = _luci2.tr('Ethernet device');
3442
3443 if (l3dev != l2dev)
3444 {
3445 type = 'tunnel';
3446 desc = _luci2.tr('Tunnel interface');
3447 }
3448 else if (dev.indexOf('br-') == 0)
3449 {
3450 type = 'bridge';
3451 desc = _luci2.tr('Bridge');
3452 }
3453 else if (dev.indexOf('.') > 0)
3454 {
3455 type = 'vlan';
3456 desc = _luci2.tr('VLAN interface');
3457 }
3458 else if (dev.indexOf('wlan') == 0 ||
3459 dev.indexOf('ath') == 0 ||
3460 dev.indexOf('wl') == 0)
3461 {
3462 type = 'wifi';
3463 desc = _luci2.tr('Wireless Network');
3464 }
3465
3466 span.appendChild(document.createElement('img'));
3467 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
3468 span.title = desc;
3469 }
3470
3471 $(span).append(' ');
3472 $(span).append(dev);
3473
3474 return span;
3475 }
3476 });
3477
3478 var type = function(f, l)
3479 {
3480 f.message = l;
3481 return f;
3482 };
3483
3484 this.cbi = {
3485 validation: {
3486 i18n: function(msg)
3487 {
3488 _luci2.cbi.validation.message = _luci2.tr(msg);
3489 },
3490
3491 compile: function(code)
3492 {
3493 var pos = 0;
3494 var esc = false;
3495 var depth = 0;
3496 var types = _luci2.cbi.validation.types;
3497 var stack = [ ];
3498
3499 code += ',';
3500
3501 for (var i = 0; i < code.length; i++)
3502 {
3503 if (esc)
3504 {
3505 esc = false;
3506 continue;
3507 }
3508
3509 switch (code.charCodeAt(i))
3510 {
3511 case 92:
3512 esc = true;
3513 break;
3514
3515 case 40:
3516 case 44:
3517 if (depth <= 0)
3518 {
3519 if (pos < i)
3520 {
3521 var label = code.substring(pos, i);
3522 label = label.replace(/\\(.)/g, '$1');
3523 label = label.replace(/^[ \t]+/g, '');
3524 label = label.replace(/[ \t]+$/g, '');
3525
3526 if (label && !isNaN(label))
3527 {
3528 stack.push(parseFloat(label));
3529 }
3530 else if (label.match(/^(['"]).*\1$/))
3531 {
3532 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
3533 }
3534 else if (typeof types[label] == 'function')
3535 {
3536 stack.push(types[label]);
3537 stack.push([ ]);
3538 }
3539 else
3540 {
3541 throw "Syntax error, unhandled token '"+label+"'";
3542 }
3543 }
3544 pos = i+1;
3545 }
3546 depth += (code.charCodeAt(i) == 40);
3547 break;
3548
3549 case 41:
3550 if (--depth <= 0)
3551 {
3552 if (typeof stack[stack.length-2] != 'function')
3553 throw "Syntax error, argument list follows non-function";
3554
3555 stack[stack.length-1] =
3556 _luci2.cbi.validation.compile(code.substring(pos, i));
3557
3558 pos = i+1;
3559 }
3560 break;
3561 }
3562 }
3563
3564 return stack;
3565 }
3566 }
3567 };
3568
3569 var validation = this.cbi.validation;
3570
3571 validation.types = {
3572 'integer': function()
3573 {
3574 if (this.match(/^-?[0-9]+$/) != null)
3575 return true;
3576
3577 validation.i18n('Must be a valid integer');
3578 return false;
3579 },
3580
3581 'uinteger': function()
3582 {
3583 if (validation.types['integer'].apply(this) && (this >= 0))
3584 return true;
3585
3586 validation.i18n('Must be a positive integer');
3587 return false;
3588 },
3589
3590 'float': function()
3591 {
3592 if (!isNaN(parseFloat(this)))
3593 return true;
3594
3595 validation.i18n('Must be a valid number');
3596 return false;
3597 },
3598
3599 'ufloat': function()
3600 {
3601 if (validation.types['float'].apply(this) && (this >= 0))
3602 return true;
3603
3604 validation.i18n('Must be a positive number');
3605 return false;
3606 },
3607
3608 'ipaddr': function()
3609 {
3610 if (validation.types['ip4addr'].apply(this) ||
3611 validation.types['ip6addr'].apply(this))
3612 return true;
3613
3614 validation.i18n('Must be a valid IP address');
3615 return false;
3616 },
3617
3618 'ip4addr': function()
3619 {
3620 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
3621 {
3622 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
3623 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
3624 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
3625 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
3626 ((RegExp.$6.indexOf('.') < 0)
3627 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
3628 : (validation.types['ip4addr'].apply(RegExp.$6))))
3629 return true;
3630 }
3631
3632 validation.i18n('Must be a valid IPv4 address');
3633 return false;
3634 },
3635
3636 'ip6addr': function()
3637 {
3638 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
3639 {
3640 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
3641 {
3642 var addr = RegExp.$1;
3643
3644 if (addr == '::')
3645 {
3646 return true;
3647 }
3648
3649 if (addr.indexOf('.') > 0)
3650 {
3651 var off = addr.lastIndexOf(':');
3652
3653 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
3654 {
3655 validation.i18n('Must be a valid IPv6 address');
3656 return false;
3657 }
3658
3659 addr = addr.substr(0, off) + ':0:0';
3660 }
3661
3662 if (addr.indexOf('::') >= 0)
3663 {
3664 var colons = 0;
3665 var fill = '0';
3666
3667 for (var i = 1; i < (addr.length-1); i++)
3668 if (addr.charAt(i) == ':')
3669 colons++;
3670
3671 if (colons > 7)
3672 {
3673 validation.i18n('Must be a valid IPv6 address');
3674 return false;
3675 }
3676
3677 for (var i = 0; i < (7 - colons); i++)
3678 fill += ':0';
3679
3680 if (addr.match(/^(.*?)::(.*?)$/))
3681 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
3682 (RegExp.$2 ? ':' + RegExp.$2 : '');
3683 }
3684
3685 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
3686 return true;
3687
3688 validation.i18n('Must be a valid IPv6 address');
3689 return false;
3690 }
3691 }
3692
3693 validation.i18n('Must be a valid IPv6 address');
3694 return false;
3695 },
3696
3697 'port': function()
3698 {
3699 if (validation.types['integer'].apply(this) &&
3700 (this >= 0) && (this <= 65535))
3701 return true;
3702
3703 validation.i18n('Must be a valid port number');
3704 return false;
3705 },
3706
3707 'portrange': function()
3708 {
3709 if (this.match(/^(\d+)-(\d+)$/))
3710 {
3711 var p1 = RegExp.$1;
3712 var p2 = RegExp.$2;
3713
3714 if (validation.types['port'].apply(p1) &&
3715 validation.types['port'].apply(p2) &&
3716 (parseInt(p1) <= parseInt(p2)))
3717 return true;
3718 }
3719 else if (validation.types['port'].apply(this))
3720 {
3721 return true;
3722 }
3723
3724 validation.i18n('Must be a valid port range');
3725 return false;
3726 },
3727
3728 'macaddr': function()
3729 {
3730 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
3731 return true;
3732
3733 validation.i18n('Must be a valid MAC address');
3734 return false;
3735 },
3736
3737 'host': function()
3738 {
3739 if (validation.types['hostname'].apply(this) ||
3740 validation.types['ipaddr'].apply(this))
3741 return true;
3742
3743 validation.i18n('Must be a valid hostname or IP address');
3744 return false;
3745 },
3746
3747 'hostname': function()
3748 {
3749 if ((this.length <= 253) &&
3750 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3751 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3752 this.match(/[^0-9.]/)))))
3753 return true;
3754
3755 validation.i18n('Must be a valid host name');
3756 return false;
3757 },
3758
3759 'network': function()
3760 {
3761 if (validation.types['uciname'].apply(this) ||
3762 validation.types['host'].apply(this))
3763 return true;
3764
3765 validation.i18n('Must be a valid network name');
3766 return false;
3767 },
3768
3769 'wpakey': function()
3770 {
3771 var v = this;
3772
3773 if ((v.length == 64)
3774 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
3775 : ((v.length >= 8) && (v.length <= 63)))
3776 return true;
3777
3778 validation.i18n('Must be a valid WPA key');
3779 return false;
3780 },
3781
3782 'wepkey': function()
3783 {
3784 var v = this;
3785
3786 if (v.substr(0,2) == 's:')
3787 v = v.substr(2);
3788
3789 if (((v.length == 10) || (v.length == 26))
3790 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
3791 : ((v.length == 5) || (v.length == 13)))
3792 return true;
3793
3794 validation.i18n('Must be a valid WEP key');
3795 return false;
3796 },
3797
3798 'uciname': function()
3799 {
3800 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3801 return true;
3802
3803 validation.i18n('Must be a valid UCI identifier');
3804 return false;
3805 },
3806
3807 'range': function(min, max)
3808 {
3809 var val = parseFloat(this);
3810
3811 if (validation.types['integer'].apply(this) &&
3812 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
3813 return true;
3814
3815 validation.i18n('Must be a number between %d and %d');
3816 return false;
3817 },
3818
3819 'min': function(min)
3820 {
3821 var val = parseFloat(this);
3822
3823 if (validation.types['integer'].apply(this) &&
3824 !isNaN(min) && !isNaN(val) && (val >= min))
3825 return true;
3826
3827 validation.i18n('Must be a number greater or equal to %d');
3828 return false;
3829 },
3830
3831 'max': function(max)
3832 {
3833 var val = parseFloat(this);
3834
3835 if (validation.types['integer'].apply(this) &&
3836 !isNaN(max) && !isNaN(val) && (val <= max))
3837 return true;
3838
3839 validation.i18n('Must be a number lower or equal to %d');
3840 return false;
3841 },
3842
3843 'rangelength': function(min, max)
3844 {
3845 var val = '' + this;
3846
3847 if (!isNaN(min) && !isNaN(max) &&
3848 (val.length >= min) && (val.length <= max))
3849 return true;
3850
3851 validation.i18n('Must be between %d and %d characters');
3852 return false;
3853 },
3854
3855 'minlength': function(min)
3856 {
3857 var val = '' + this;
3858
3859 if (!isNaN(min) && (val.length >= min))
3860 return true;
3861
3862 validation.i18n('Must be at least %d characters');
3863 return false;
3864 },
3865
3866 'maxlength': function(max)
3867 {
3868 var val = '' + this;
3869
3870 if (!isNaN(max) && (val.length <= max))
3871 return true;
3872
3873 validation.i18n('Must be at most %d characters');
3874 return false;
3875 },
3876
3877 'or': function()
3878 {
3879 var msgs = [ ];
3880
3881 for (var i = 0; i < arguments.length; i += 2)
3882 {
3883 delete validation.message;
3884
3885 if (typeof(arguments[i]) != 'function')
3886 {
3887 if (arguments[i] == this)
3888 return true;
3889 i--;
3890 }
3891 else if (arguments[i].apply(this, arguments[i+1]))
3892 {
3893 return true;
3894 }
3895
3896 if (validation.message)
3897 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3898 }
3899
3900 validation.message = msgs.join( _luci2.tr(' - or - '));
3901 return false;
3902 },
3903
3904 'and': function()
3905 {
3906 var msgs = [ ];
3907
3908 for (var i = 0; i < arguments.length; i += 2)
3909 {
3910 delete validation.message;
3911
3912 if (typeof arguments[i] != 'function')
3913 {
3914 if (arguments[i] != this)
3915 return false;
3916 i--;
3917 }
3918 else if (!arguments[i].apply(this, arguments[i+1]))
3919 {
3920 return false;
3921 }
3922
3923 if (validation.message)
3924 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3925 }
3926
3927 validation.message = msgs.join(', ');
3928 return true;
3929 },
3930
3931 'neg': function()
3932 {
3933 return validation.types['or'].apply(
3934 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
3935 },
3936
3937 'list': function(subvalidator, subargs)
3938 {
3939 if (typeof subvalidator != 'function')
3940 return false;
3941
3942 var tokens = this.match(/[^ \t]+/g);
3943 for (var i = 0; i < tokens.length; i++)
3944 if (!subvalidator.apply(tokens[i], subargs))
3945 return false;
3946
3947 return true;
3948 },
3949
3950 'phonedigit': function()
3951 {
3952 if (this.match(/^[0-9\*#!\.]+$/) != null)
3953 return true;
3954
3955 validation.i18n('Must be a valid phone number digit');
3956 return false;
3957 },
3958
3959 'string': function()
3960 {
3961 return true;
3962 }
3963 };
3964
3965
3966 this.cbi.AbstractValue = this.ui.AbstractWidget.extend({
3967 init: function(name, options)
3968 {
3969 this.name = name;
3970 this.instance = { };
3971 this.dependencies = [ ];
3972 this.rdependency = { };
3973
3974 this.options = _luci2.defaults(options, {
3975 placeholder: '',
3976 datatype: 'string',
3977 optional: false,
3978 keep: true
3979 });
3980 },
3981
3982 id: function(sid)
3983 {
3984 return this.section.id('field', sid || '__unknown__', this.name);
3985 },
3986
3987 render: function(sid, condensed)
3988 {
3989 var i = this.instance[sid] = { };
3990
3991 i.top = $('<div />');
3992
3993 if (!condensed)
3994 {
3995 i.top.addClass('form-group');
3996
3997 if (typeof(this.options.caption) == 'string')
3998 $('<label />')
3999 .addClass('col-lg-2 control-label')
4000 .attr('for', this.id(sid))
4001 .text(this.options.caption)
4002 .appendTo(i.top);
4003 }
4004
4005 i.error = $('<div />')
4006 .hide()
4007 .addClass('label label-danger');
4008
4009 i.widget = $('<div />')
4010
4011 .append(this.widget(sid))
4012 .append(i.error)
4013 .appendTo(i.top);
4014
4015 if (!condensed)
4016 {
4017 i.widget.addClass('col-lg-5');
4018
4019 $('<div />')
4020 .addClass('col-lg-5')
4021 .text((typeof(this.options.description) == 'string') ? this.options.description : '')
4022 .appendTo(i.top);
4023 }
4024
4025 return i.top;
4026 },
4027
4028 ucipath: function(sid)
4029 {
4030 return {
4031 config: (this.options.uci_package || this.map.uci_package),
4032 section: (this.options.uci_section || sid),
4033 option: (this.options.uci_option || this.name)
4034 };
4035 },
4036
4037 ucivalue: function(sid)
4038 {
4039 var uci = this.ucipath(sid);
4040 var val = this.map.get(uci.config, uci.section, uci.option);
4041
4042 if (typeof(val) == 'undefined')
4043 return this.options.initial;
4044
4045 return val;
4046 },
4047
4048 formvalue: function(sid)
4049 {
4050 var v = $('#' + this.id(sid)).val();
4051 return (v === '') ? undefined : v;
4052 },
4053
4054 textvalue: function(sid)
4055 {
4056 var v = this.formvalue(sid);
4057
4058 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
4059 v = this.ucivalue(sid);
4060
4061 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
4062 v = this.options.placeholder;
4063
4064 if (typeof(v) == 'undefined' || v === '')
4065 return undefined;
4066
4067 if (typeof(v) == 'string' && $.isArray(this.choices))
4068 {
4069 for (var i = 0; i < this.choices.length; i++)
4070 if (v === this.choices[i][0])
4071 return this.choices[i][1];
4072 }
4073 else if (v === true)
4074 return _luci2.tr('yes');
4075 else if (v === false)
4076 return _luci2.tr('no');
4077 else if ($.isArray(v))
4078 return v.join(', ');
4079
4080 return v;
4081 },
4082
4083 changed: function(sid)
4084 {
4085 var a = this.ucivalue(sid);
4086 var b = this.formvalue(sid);
4087
4088 if (typeof(a) != typeof(b))
4089 return true;
4090
4091 if (typeof(a) == 'object')
4092 {
4093 if (a.length != b.length)
4094 return true;
4095
4096 for (var i = 0; i < a.length; i++)
4097 if (a[i] != b[i])
4098 return true;
4099
4100 return false;
4101 }
4102
4103 return (a != b);
4104 },
4105
4106 save: function(sid)
4107 {
4108 var uci = this.ucipath(sid);
4109
4110 if (this.instance[sid].disabled)
4111 {
4112 if (!this.options.keep)
4113 return this.map.set(uci.config, uci.section, uci.option, undefined);
4114
4115 return false;
4116 }
4117
4118 var chg = this.changed(sid);
4119 var val = this.formvalue(sid);
4120
4121 if (chg)
4122 this.map.set(uci.config, uci.section, uci.option, val);
4123
4124 return chg;
4125 },
4126
4127 _ev_validate: function(ev)
4128 {
4129 var d = ev.data;
4130 var rv = true;
4131 var val = d.elem.val();
4132 var vstack = d.vstack;
4133
4134 if (vstack && typeof(vstack[0]) == 'function')
4135 {
4136 delete validation.message;
4137
4138 if ((val.length == 0 && !d.opt))
4139 {
4140 d.elem.parents('div.form-group, td').first().addClass('luci2-form-error');
4141 d.elem.parents('div.input-group, div.form-group, td').first().addClass('has-error');
4142
4143 d.inst.error.text(_luci2.tr('Field must not be empty')).show();
4144 rv = false;
4145 }
4146 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
4147 {
4148 d.elem.parents('div.form-group, td').first().addClass('luci2-form-error');
4149 d.elem.parents('div.input-group, div.form-group, td').first().addClass('has-error');
4150
4151 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1])).show();
4152 rv = false;
4153 }
4154 else
4155 {
4156 d.elem.parents('div.form-group, td').first().removeClass('luci2-form-error');
4157 d.elem.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
4158
4159 if (d.multi && d.inst.widget && d.inst.widget.find('input.error, select.error').length > 0)
4160 rv = false;
4161 else
4162 d.inst.error.text('').hide();
4163 }
4164 }
4165
4166 if (rv)
4167 for (var field in d.self.rdependency)
4168 d.self.rdependency[field].toggle(d.sid);
4169
4170 return rv;
4171 },
4172
4173 validator: function(sid, elem, multi)
4174 {
4175 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
4176 return elem;
4177
4178 var vstack;
4179 if (typeof(this.options.datatype) == 'string')
4180 {
4181 try {
4182 vstack = _luci2.cbi.validation.compile(this.options.datatype);
4183 } catch(e) { };
4184 }
4185 else if (typeof(this.options.datatype) == 'function')
4186 {
4187 var vfunc = this.options.datatype;
4188 vstack = [ function(elem) {
4189 var rv = vfunc(this, elem);
4190 if (rv !== true)
4191 validation.message = rv;
4192 return (rv === true);
4193 }, [ elem ] ];
4194 }
4195
4196 var evdata = {
4197 self: this,
4198 sid: sid,
4199 elem: elem,
4200 multi: multi,
4201 vstack: vstack,
4202 inst: this.instance[sid],
4203 opt: this.options.optional
4204 };
4205
4206 if (elem.prop('tagName') == 'SELECT')
4207 {
4208 elem.change(evdata, this._ev_validate);
4209 }
4210 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
4211 {
4212 elem.click(evdata, this._ev_validate);
4213 elem.blur(evdata, this._ev_validate);
4214 }
4215 else
4216 {
4217 elem.keyup(evdata, this._ev_validate);
4218 elem.blur(evdata, this._ev_validate);
4219 }
4220
4221 elem.attr('cbi-validate', true).on('validate', evdata, this._ev_validate);
4222
4223 return elem;
4224 },
4225
4226 validate: function(sid)
4227 {
4228 var i = this.instance[sid];
4229
4230 i.widget.find('[cbi-validate]').trigger('validate');
4231
4232 return (i.disabled || i.error.text() == '');
4233 },
4234
4235 depends: function(d, v)
4236 {
4237 var dep;
4238
4239 if ($.isArray(d))
4240 {
4241 dep = { };
4242 for (var i = 0; i < d.length; i++)
4243 {
4244 if (typeof(d[i]) == 'string')
4245 dep[d[i]] = true;
4246 else if (d[i] instanceof _luci2.cbi.AbstractValue)
4247 dep[d[i].name] = true;
4248 }
4249 }
4250 else if (d instanceof _luci2.cbi.AbstractValue)
4251 {
4252 dep = { };
4253 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
4254 }
4255 else if (typeof(d) == 'object')
4256 {
4257 dep = d;
4258 }
4259 else if (typeof(d) == 'string')
4260 {
4261 dep = { };
4262 dep[d] = (typeof(v) == 'undefined') ? true : v;
4263 }
4264
4265 if (!dep || $.isEmptyObject(dep))
4266 return this;
4267
4268 for (var field in dep)
4269 {
4270 var f = this.section.fields[field];
4271 if (f)
4272 f.rdependency[this.name] = this;
4273 else
4274 delete dep[field];
4275 }
4276
4277 if ($.isEmptyObject(dep))
4278 return this;
4279
4280 this.dependencies.push(dep);
4281
4282 return this;
4283 },
4284
4285 toggle: function(sid)
4286 {
4287 var d = this.dependencies;
4288 var i = this.instance[sid];
4289
4290 if (!d.length)
4291 return true;
4292
4293 for (var n = 0; n < d.length; n++)
4294 {
4295 var rv = true;
4296
4297 for (var field in d[n])
4298 {
4299 var val = this.section.fields[field].formvalue(sid);
4300 var cmp = d[n][field];
4301
4302 if (typeof(cmp) == 'boolean')
4303 {
4304 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
4305 {
4306 rv = false;
4307 break;
4308 }
4309 }
4310 else if (typeof(cmp) == 'string')
4311 {
4312 if (val != cmp)
4313 {
4314 rv = false;
4315 break;
4316 }
4317 }
4318 else if (typeof(cmp) == 'function')
4319 {
4320 if (!cmp(val))
4321 {
4322 rv = false;
4323 break;
4324 }
4325 }
4326 else if (cmp instanceof RegExp)
4327 {
4328 if (!cmp.test(val))
4329 {
4330 rv = false;
4331 break;
4332 }
4333 }
4334 }
4335
4336 if (rv)
4337 {
4338 if (i.disabled)
4339 {
4340 i.disabled = false;
4341 i.top.fadeIn();
4342 }
4343
4344 return true;
4345 }
4346 }
4347
4348 if (!i.disabled)
4349 {
4350 i.disabled = true;
4351 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
4352 }
4353
4354 return false;
4355 }
4356 });
4357
4358 this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
4359 widget: function(sid)
4360 {
4361 var o = this.options;
4362
4363 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
4364 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
4365
4366 var i = $('<input />')
4367 .attr('id', this.id(sid))
4368 .attr('type', 'checkbox')
4369 .prop('checked', this.ucivalue(sid));
4370
4371 return $('<div />')
4372 .addClass('checkbox')
4373 .append(this.validator(sid, i));
4374 },
4375
4376 ucivalue: function(sid)
4377 {
4378 var v = this.callSuper('ucivalue', sid);
4379
4380 if (typeof(v) == 'boolean')
4381 return v;
4382
4383 return (v == this.options.enabled);
4384 },
4385
4386 formvalue: function(sid)
4387 {
4388 var v = $('#' + this.id(sid)).prop('checked');
4389
4390 if (typeof(v) == 'undefined')
4391 return !!this.options.initial;
4392
4393 return v;
4394 },
4395
4396 save: function(sid)
4397 {
4398 var uci = this.ucipath(sid);
4399
4400 if (this.instance[sid].disabled)
4401 {
4402 if (!this.options.keep)
4403 return this.map.set(uci.config, uci.section, uci.option, undefined);
4404
4405 return false;
4406 }
4407
4408 var chg = this.changed(sid);
4409 var val = this.formvalue(sid);
4410
4411 if (chg)
4412 {
4413 if (this.options.optional && val == this.options.initial)
4414 this.map.set(uci.config, uci.section, uci.option, undefined);
4415 else
4416 this.map.set(uci.config, uci.section, uci.option, val ? this.options.enabled : this.options.disabled);
4417 }
4418
4419 return chg;
4420 }
4421 });
4422
4423 this.cbi.InputValue = this.cbi.AbstractValue.extend({
4424 widget: function(sid)
4425 {
4426 var i = $('<input />')
4427 .addClass('form-control')
4428 .attr('id', this.id(sid))
4429 .attr('type', 'text')
4430 .attr('placeholder', this.options.placeholder)
4431 .val(this.ucivalue(sid));
4432
4433 return this.validator(sid, i);
4434 }
4435 });
4436
4437 this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
4438 widget: function(sid)
4439 {
4440 var i = $('<input />')
4441 .addClass('form-control')
4442 .attr('id', this.id(sid))
4443 .attr('type', 'password')
4444 .attr('placeholder', this.options.placeholder)
4445 .val(this.ucivalue(sid));
4446
4447 var t = $('<span />')
4448 .addClass('input-group-btn')
4449 .append(_luci2.ui.button(_luci2.tr('Reveal'), 'default')
4450 .click(function(ev) {
4451 var b = $(this);
4452 var i = b.parent().prev();
4453 var t = i.attr('type');
4454 b.text(t == 'password' ? _luci2.tr('Hide') : _luci2.tr('Reveal'));
4455 i.attr('type', (t == 'password') ? 'text' : 'password');
4456 b = i = t = null;
4457 }));
4458
4459 this.validator(sid, i);
4460
4461 return $('<div />')
4462 .addClass('input-group')
4463 .append(i)
4464 .append(t);
4465 }
4466 });
4467
4468 this.cbi.ListValue = this.cbi.AbstractValue.extend({
4469 widget: function(sid)
4470 {
4471 var s = $('<select />')
4472 .addClass('form-control');
4473
4474 if (this.options.optional)
4475 $('<option />')
4476 .attr('value', '')
4477 .text(_luci2.tr('-- Please choose --'))
4478 .appendTo(s);
4479
4480 if (this.choices)
4481 for (var i = 0; i < this.choices.length; i++)
4482 $('<option />')
4483 .attr('value', this.choices[i][0])
4484 .text(this.choices[i][1])
4485 .appendTo(s);
4486
4487 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
4488
4489 return this.validator(sid, s);
4490 },
4491
4492 value: function(k, v)
4493 {
4494 if (!this.choices)
4495 this.choices = [ ];
4496
4497 this.choices.push([k, v || k]);
4498 return this;
4499 }
4500 });
4501
4502 this.cbi.MultiValue = this.cbi.ListValue.extend({
4503 widget: function(sid)
4504 {
4505 var v = this.ucivalue(sid);
4506 var t = $('<div />').attr('id', this.id(sid));
4507
4508 if (!$.isArray(v))
4509 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4510
4511 var s = { };
4512 for (var i = 0; i < v.length; i++)
4513 s[v[i]] = true;
4514
4515 if (this.choices)
4516 for (var i = 0; i < this.choices.length; i++)
4517 {
4518 $('<label />')
4519 .addClass('checkbox')
4520 .append($('<input />')
4521 .attr('type', 'checkbox')
4522 .attr('value', this.choices[i][0])
4523 .prop('checked', s[this.choices[i][0]]))
4524 .append(this.choices[i][1])
4525 .appendTo(t);
4526 }
4527
4528 return t;
4529 },
4530
4531 formvalue: function(sid)
4532 {
4533 var rv = [ ];
4534 var fields = $('#' + this.id(sid) + ' > label > input');
4535
4536 for (var i = 0; i < fields.length; i++)
4537 if (fields[i].checked)
4538 rv.push(fields[i].getAttribute('value'));
4539
4540 return rv;
4541 },
4542
4543 textvalue: function(sid)
4544 {
4545 var v = this.formvalue(sid);
4546 var c = { };
4547
4548 if (this.choices)
4549 for (var i = 0; i < this.choices.length; i++)
4550 c[this.choices[i][0]] = this.choices[i][1];
4551
4552 var t = [ ];
4553
4554 for (var i = 0; i < v.length; i++)
4555 t.push(c[v[i]] || v[i]);
4556
4557 return t.join(', ');
4558 }
4559 });
4560
4561 this.cbi.ComboBox = this.cbi.AbstractValue.extend({
4562 _change: function(ev)
4563 {
4564 var s = ev.target;
4565 var self = ev.data.self;
4566
4567 if (s.selectedIndex == (s.options.length - 1))
4568 {
4569 ev.data.select.hide();
4570 ev.data.input.show().focus();
4571
4572 var v = ev.data.input.val();
4573 ev.data.input.val(' ');
4574 ev.data.input.val(v);
4575 }
4576 else if (self.options.optional && s.selectedIndex == 0)
4577 {
4578 ev.data.input.val('');
4579 }
4580 else
4581 {
4582 ev.data.input.val(ev.data.select.val());
4583 }
4584 },
4585
4586 _blur: function(ev)
4587 {
4588 var seen = false;
4589 var val = this.value;
4590 var self = ev.data.self;
4591
4592 ev.data.select.empty();
4593
4594 if (self.options.optional)
4595 $('<option />')
4596 .attr('value', '')
4597 .text(_luci2.tr('-- please choose --'))
4598 .appendTo(ev.data.select);
4599
4600 if (self.choices)
4601 for (var i = 0; i < self.choices.length; i++)
4602 {
4603 if (self.choices[i][0] == val)
4604 seen = true;
4605
4606 $('<option />')
4607 .attr('value', self.choices[i][0])
4608 .text(self.choices[i][1])
4609 .appendTo(ev.data.select);
4610 }
4611
4612 if (!seen && val != '')
4613 $('<option />')
4614 .attr('value', val)
4615 .text(val)
4616 .appendTo(ev.data.select);
4617
4618 $('<option />')
4619 .attr('value', ' ')
4620 .text(_luci2.tr('-- custom --'))
4621 .appendTo(ev.data.select);
4622
4623 ev.data.input.hide();
4624 ev.data.select.val(val).show().focus();
4625 },
4626
4627 _enter: function(ev)
4628 {
4629 if (ev.which != 13)
4630 return true;
4631
4632 ev.preventDefault();
4633 ev.data.self._blur(ev);
4634 return false;
4635 },
4636
4637 widget: function(sid)
4638 {
4639 var d = $('<div />')
4640 .attr('id', this.id(sid));
4641
4642 var t = $('<input />')
4643 .attr('type', 'text')
4644 .hide()
4645 .appendTo(d);
4646
4647 var s = $('<select />')
4648 .appendTo(d);
4649
4650 var evdata = {
4651 self: this,
4652 input: this.validator(sid, t),
4653 select: this.validator(sid, s)
4654 };
4655
4656 s.change(evdata, this._change);
4657 t.blur(evdata, this._blur);
4658 t.keydown(evdata, this._enter);
4659
4660 t.val(this.ucivalue(sid));
4661 t.blur();
4662
4663 return d;
4664 },
4665
4666 value: function(k, v)
4667 {
4668 if (!this.choices)
4669 this.choices = [ ];
4670
4671 this.choices.push([k, v || k]);
4672 return this;
4673 },
4674
4675 formvalue: function(sid)
4676 {
4677 var v = $('#' + this.id(sid)).children('input').val();
4678 return (v == '') ? undefined : v;
4679 }
4680 });
4681
4682 this.cbi.DynamicList = this.cbi.ComboBox.extend({
4683 _redraw: function(focus, add, del, s)
4684 {
4685 var v = s.values || [ ];
4686 delete s.values;
4687
4688 $(s.parent).children('div.input-group').children('input').each(function(i) {
4689 if (i != del)
4690 v.push(this.value || '');
4691 });
4692
4693 $(s.parent).empty();
4694
4695 if (add >= 0)
4696 {
4697 focus = add + 1;
4698 v.splice(focus, 0, '');
4699 }
4700 else if (v.length == 0)
4701 {
4702 focus = 0;
4703 v.push('');
4704 }
4705
4706 for (var i = 0; i < v.length; i++)
4707 {
4708 var evdata = {
4709 sid: s.sid,
4710 self: s.self,
4711 parent: s.parent,
4712 index: i,
4713 remove: ((i+1) < v.length)
4714 };
4715
4716 var btn;
4717 if (evdata.remove)
4718 btn = _luci2.ui.button('–', 'danger').click(evdata, this._btnclick);
4719 else
4720 btn = _luci2.ui.button('+', 'success').click(evdata, this._btnclick);
4721
4722 if (this.choices)
4723 {
4724 var txt = $('<input />')
4725 .addClass('form-control')
4726 .attr('type', 'text')
4727 .hide();
4728
4729 var sel = $('<select />')
4730 .addClass('form-control');
4731
4732 $('<div />')
4733 .addClass('input-group')
4734 .append(txt)
4735 .append(sel)
4736 .append($('<span />')
4737 .addClass('input-group-btn')
4738 .append(btn))
4739 .appendTo(s.parent);
4740
4741 evdata.input = this.validator(s.sid, txt, true);
4742 evdata.select = this.validator(s.sid, sel, true);
4743
4744 sel.change(evdata, this._change);
4745 txt.blur(evdata, this._blur);
4746 txt.keydown(evdata, this._keydown);
4747
4748 txt.val(v[i]);
4749 txt.blur();
4750
4751 if (i == focus || -(i+1) == focus)
4752 sel.focus();
4753
4754 sel = txt = null;
4755 }
4756 else
4757 {
4758 var f = $('<input />')
4759 .attr('type', 'text')
4760 .attr('index', i)
4761 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
4762 .addClass('form-control')
4763 .keydown(evdata, this._keydown)
4764 .keypress(evdata, this._keypress)
4765 .val(v[i]);
4766
4767 $('<div />')
4768 .addClass('input-group')
4769 .append(f)
4770 .append($('<span />')
4771 .addClass('input-group-btn')
4772 .append(btn))
4773 .appendTo(s.parent);
4774
4775 if (i == focus)
4776 {
4777 f.focus();
4778 }
4779 else if (-(i+1) == focus)
4780 {
4781 f.focus();
4782
4783 /* force cursor to end */
4784 var val = f.val();
4785 f.val(' ');
4786 f.val(val);
4787 }
4788
4789 evdata.input = this.validator(s.sid, f, true);
4790
4791 f = null;
4792 }
4793
4794 evdata = null;
4795 }
4796
4797 s = null;
4798 },
4799
4800 _keypress: function(ev)
4801 {
4802 switch (ev.which)
4803 {
4804 /* backspace, delete */
4805 case 8:
4806 case 46:
4807 if (ev.data.input.val() == '')
4808 {
4809 ev.preventDefault();
4810 return false;
4811 }
4812
4813 return true;
4814
4815 /* enter, arrow up, arrow down */
4816 case 13:
4817 case 38:
4818 case 40:
4819 ev.preventDefault();
4820 return false;
4821 }
4822
4823 return true;
4824 },
4825
4826 _keydown: function(ev)
4827 {
4828 var input = ev.data.input;
4829
4830 switch (ev.which)
4831 {
4832 /* backspace, delete */
4833 case 8:
4834 case 46:
4835 if (input.val().length == 0)
4836 {
4837 ev.preventDefault();
4838
4839 var index = ev.data.index;
4840 var focus = index;
4841
4842 if (ev.which == 8)
4843 focus = -focus;
4844
4845 ev.data.self._redraw(focus, -1, index, ev.data);
4846 return false;
4847 }
4848
4849 break;
4850
4851 /* enter */
4852 case 13:
4853 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4854 break;
4855
4856 /* arrow up */
4857 case 38:
4858 var prev = input.parent().prevAll('div.input-group:first').children('input');
4859 if (prev.is(':visible'))
4860 prev.focus();
4861 else
4862 prev.next('select').focus();
4863 break;
4864
4865 /* arrow down */
4866 case 40:
4867 var next = input.parent().nextAll('div.input-group:first').children('input');
4868 if (next.is(':visible'))
4869 next.focus();
4870 else
4871 next.next('select').focus();
4872 break;
4873 }
4874
4875 return true;
4876 },
4877
4878 _btnclick: function(ev)
4879 {
4880 if (!this.getAttribute('disabled'))
4881 {
4882 if (ev.data.remove)
4883 {
4884 var index = ev.data.index;
4885 ev.data.self._redraw(-index, -1, index, ev.data);
4886 }
4887 else
4888 {
4889 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4890 }
4891 }
4892
4893 return false;
4894 },
4895
4896 widget: function(sid)
4897 {
4898 this.options.optional = true;
4899
4900 var v = this.ucivalue(sid);
4901
4902 if (!$.isArray(v))
4903 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4904
4905 var d = $('<div />')
4906 .attr('id', this.id(sid))
4907 .addClass('cbi-input-dynlist');
4908
4909 this._redraw(NaN, -1, -1, {
4910 self: this,
4911 parent: d[0],
4912 values: v,
4913 sid: sid
4914 });
4915
4916 return d;
4917 },
4918
4919 ucivalue: function(sid)
4920 {
4921 var v = this.callSuper('ucivalue', sid);
4922
4923 if (!$.isArray(v))
4924 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4925
4926 return v;
4927 },
4928
4929 formvalue: function(sid)
4930 {
4931 var rv = [ ];
4932 var fields = $('#' + this.id(sid) + ' > input');
4933
4934 for (var i = 0; i < fields.length; i++)
4935 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
4936 rv.push(fields[i].value);
4937
4938 return rv;
4939 }
4940 });
4941
4942 this.cbi.DummyValue = this.cbi.AbstractValue.extend({
4943 widget: function(sid)
4944 {
4945 return $('<div />')
4946 .addClass('form-control-static')
4947 .attr('id', this.id(sid))
4948 .html(this.ucivalue(sid));
4949 },
4950
4951 formvalue: function(sid)
4952 {
4953 return this.ucivalue(sid);
4954 }
4955 });
4956
4957 this.cbi.NetworkList = this.cbi.AbstractValue.extend({
4958 load: function(sid)
4959 {
4960 var self = this;
4961
4962 if (!self.interfaces)
4963 {
4964 self.interfaces = [ ];
4965 return _luci2.network.getNetworkStatus().then(function(ifaces) {
4966 self.interfaces = ifaces;
4967 self = null;
4968 });
4969 }
4970
4971 return undefined;
4972 },
4973
4974 _device_icon: function(dev)
4975 {
4976 var type = 'ethernet';
4977 var desc = _luci2.tr('Ethernet device');
4978
4979 if (dev.type == 'IP tunnel')
4980 {
4981 type = 'tunnel';
4982 desc = _luci2.tr('Tunnel interface');
4983 }
4984 else if (dev['bridge-members'])
4985 {
4986 type = 'bridge';
4987 desc = _luci2.tr('Bridge');
4988 }
4989 else if (dev.wireless)
4990 {
4991 type = 'wifi';
4992 desc = _luci2.tr('Wireless Network');
4993 }
4994 else if (dev.device.indexOf('.') > 0)
4995 {
4996 type = 'vlan';
4997 desc = _luci2.tr('VLAN interface');
4998 }
4999
5000 return $('<img />')
5001 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
5002 .attr('title', '%s (%s)'.format(desc, dev.device));
5003 },
5004
5005 widget: function(sid)
5006 {
5007 var id = this.id(sid);
5008 var ul = $('<ul />')
5009 .attr('id', id)
5010 .addClass('list-unstyled');
5011
5012 var itype = this.options.multiple ? 'checkbox' : 'radio';
5013 var value = this.ucivalue(sid);
5014 var check = { };
5015
5016 if (!this.options.multiple)
5017 check[value] = true;
5018 else
5019 for (var i = 0; i < value.length; i++)
5020 check[value[i]] = true;
5021
5022 if (this.interfaces)
5023 {
5024 for (var i = 0; i < this.interfaces.length; i++)
5025 {
5026 var iface = this.interfaces[i];
5027 var badge = $('<span />')
5028 .addClass('badge')
5029 .text('%s: '.format(iface['interface']));
5030
5031 if (iface.device && iface.device.subdevices)
5032 for (var j = 0; j < iface.device.subdevices.length; j++)
5033 badge.append(this._device_icon(iface.device.subdevices[j]));
5034 else if (iface.device)
5035 badge.append(this._device_icon(iface.device));
5036 else
5037 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
5038
5039 $('<li />')
5040 .append($('<label />')
5041 .addClass(itype + ' inline')
5042 .append($('<input />')
5043 .attr('name', itype + id)
5044 .attr('type', itype)
5045 .attr('value', iface['interface'])
5046 .prop('checked', !!check[iface['interface']]))
5047 .append(badge))
5048 .appendTo(ul);
5049 }
5050 }
5051
5052 if (!this.options.multiple)
5053 {
5054 $('<li />')
5055 .append($('<label />')
5056 .addClass(itype + ' inline text-muted')
5057 .append($('<input />')
5058 .attr('name', itype + id)
5059 .attr('type', itype)
5060 .attr('value', '')
5061 .prop('checked', !value))
5062 .append(_luci2.tr('unspecified')))
5063 .appendTo(ul);
5064 }
5065
5066 return ul;
5067 },
5068
5069 ucivalue: function(sid)
5070 {
5071 var v = this.callSuper('ucivalue', sid);
5072
5073 if (!this.options.multiple)
5074 {
5075 if ($.isArray(v))
5076 {
5077 return v[0];
5078 }
5079 else if (typeof(v) == 'string')
5080 {
5081 v = v.match(/\S+/);
5082 return v ? v[0] : undefined;
5083 }
5084
5085 return v;
5086 }
5087 else
5088 {
5089 if (typeof(v) == 'string')
5090 v = v.match(/\S+/g);
5091
5092 return v || [ ];
5093 }
5094 },
5095
5096 formvalue: function(sid)
5097 {
5098 var inputs = $('#' + this.id(sid) + ' input');
5099
5100 if (!this.options.multiple)
5101 {
5102 for (var i = 0; i < inputs.length; i++)
5103 if (inputs[i].checked && inputs[i].value !== '')
5104 return inputs[i].value;
5105
5106 return undefined;
5107 }
5108
5109 var rv = [ ];
5110
5111 for (var i = 0; i < inputs.length; i++)
5112 if (inputs[i].checked)
5113 rv.push(inputs[i].value);
5114
5115 return rv.length ? rv : undefined;
5116 }
5117 });
5118
5119
5120 this.cbi.AbstractSection = this.ui.AbstractWidget.extend({
5121 id: function()
5122 {
5123 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
5124
5125 for (var i = 1; i < arguments.length; i++)
5126 s.push(arguments[i].replace(/\./g, '_'));
5127
5128 return s.join('_');
5129 },
5130
5131 option: function(widget, name, options)
5132 {
5133 if (this.tabs.length == 0)
5134 this.tab({ id: '__default__', selected: true });
5135
5136 return this.taboption('__default__', widget, name, options);
5137 },
5138
5139 tab: function(options)
5140 {
5141 if (options.selected)
5142 this.tabs.selected = this.tabs.length;
5143
5144 this.tabs.push({
5145 id: options.id,
5146 caption: options.caption,
5147 description: options.description,
5148 fields: [ ],
5149 li: { }
5150 });
5151 },
5152
5153 taboption: function(tabid, widget, name, options)
5154 {
5155 var tab;
5156 for (var i = 0; i < this.tabs.length; i++)
5157 {
5158 if (this.tabs[i].id == tabid)
5159 {
5160 tab = this.tabs[i];
5161 break;
5162 }
5163 }
5164
5165 if (!tab)
5166 throw 'Cannot append to unknown tab ' + tabid;
5167
5168 var w = widget ? new widget(name, options) : null;
5169
5170 if (!(w instanceof _luci2.cbi.AbstractValue))
5171 throw 'Widget must be an instance of AbstractValue';
5172
5173 w.section = this;
5174 w.map = this.map;
5175
5176 this.fields[name] = w;
5177 tab.fields.push(w);
5178
5179 return w;
5180 },
5181
5182 ucipackages: function(pkg)
5183 {
5184 for (var i = 0; i < this.tabs.length; i++)
5185 for (var j = 0; j < this.tabs[i].fields.length; j++)
5186 if (this.tabs[i].fields[j].options.uci_package)
5187 pkg[this.tabs[i].fields[j].options.uci_package] = true;
5188 },
5189
5190 formvalue: function()
5191 {
5192 var rv = { };
5193
5194 this.sections(function(s) {
5195 var sid = s['.name'];
5196 var sv = rv[sid] || (rv[sid] = { });
5197
5198 for (var i = 0; i < this.tabs.length; i++)
5199 for (var j = 0; j < this.tabs[i].fields.length; j++)
5200 {
5201 var val = this.tabs[i].fields[j].formvalue(sid);
5202 sv[this.tabs[i].fields[j].name] = val;
5203 }
5204 });
5205
5206 return rv;
5207 },
5208
5209 validate_section: function(sid)
5210 {
5211 var inst = this.instance[sid];
5212
5213 var invals = 0;
5214 var badge = $('#' + this.id('teaser', sid)).children('span:first');
5215
5216 for (var i = 0; i < this.tabs.length; i++)
5217 {
5218 var inval = 0;
5219 var stbadge = $('#' + this.id('nodetab', sid, this.tabs[i].id)).children('span:first');
5220
5221 for (var j = 0; j < this.tabs[i].fields.length; j++)
5222 if (!this.tabs[i].fields[j].validate(sid))
5223 inval++;
5224
5225 if (inval > 0)
5226 stbadge.show()
5227 .text(inval)
5228 .attr('title', _luci2.trp('1 Error', '%d Errors', inval).format(inval));
5229 else
5230 stbadge.hide();
5231
5232 invals += inval;
5233 }
5234
5235 if (invals > 0)
5236 badge.show()
5237 .text(invals)
5238 .attr('title', _luci2.trp('1 Error', '%d Errors', invals).format(invals));
5239 else
5240 badge.hide();
5241
5242 return invals;
5243 },
5244
5245 validate: function()
5246 {
5247 this.error_count = 0;
5248
5249 var as = this.sections();
5250
5251 for (var i = 0; i < as.length; i++)
5252 {
5253 var invals = this.validate_section(as[i]['.name']);
5254
5255 if (invals > 0)
5256 this.error_count += invals;
5257 }
5258
5259 var badge = $('#' + this.id('sectiontab')).children('span:first');
5260
5261 if (this.error_count > 0)
5262 badge.show()
5263 .text(this.error_count)
5264 .attr('title', _luci2.trp('1 Error', '%d Errors', this.error_count).format(this.error_count));
5265 else
5266 badge.hide();
5267
5268 return (this.error_count == 0);
5269 }
5270 });
5271
5272 this.cbi.TypedSection = this.cbi.AbstractSection.extend({
5273 init: function(uci_type, options)
5274 {
5275 this.uci_type = uci_type;
5276 this.options = options;
5277 this.tabs = [ ];
5278 this.fields = { };
5279 this.error_count = 0;
5280 this.active_panel = 0;
5281 this.active_tab = { };
5282 },
5283
5284 filter: function(section)
5285 {
5286 return true;
5287 },
5288
5289 sections: function(cb)
5290 {
5291 var s1 = this.map.ucisections(this.map.uci_package);
5292 var s2 = [ ];
5293
5294 for (var i = 0; i < s1.length; i++)
5295 if (s1[i]['.type'] == this.uci_type)
5296 if (this.filter(s1[i]))
5297 s2.push(s1[i]);
5298
5299 if (typeof(cb) == 'function')
5300 for (var i = 0; i < s2.length; i++)
5301 cb.apply(this, [ s2[i] ]);
5302
5303 return s2;
5304 },
5305
5306 add: function(name)
5307 {
5308 this.map.add(this.map.uci_package, this.uci_type, name);
5309 },
5310
5311 remove: function(sid)
5312 {
5313 this.map.remove(this.map.uci_package, sid);
5314 },
5315
5316 _ev_add: function(ev)
5317 {
5318 var addb = $(this);
5319 var name = undefined;
5320 var self = ev.data.self;
5321
5322 if (addb.prev().prop('nodeName') == 'INPUT')
5323 name = addb.prev().val();
5324
5325 if (addb.prop('disabled') || name === '')
5326 return;
5327
5328 _luci2.ui.saveScrollTop();
5329
5330 self.active_panel = -1;
5331 self.map.save();
5332 self.add(name);
5333 self.map.redraw();
5334
5335 _luci2.ui.restoreScrollTop();
5336 },
5337
5338 _ev_remove: function(ev)
5339 {
5340 var self = ev.data.self;
5341 var sid = ev.data.sid;
5342
5343 _luci2.ui.saveScrollTop();
5344
5345 self.map.save();
5346 self.remove(sid);
5347 self.map.redraw();
5348
5349 _luci2.ui.restoreScrollTop();
5350
5351 ev.stopPropagation();
5352 },
5353
5354 _ev_sid: function(ev)
5355 {
5356 var self = ev.data.self;
5357 var text = $(this);
5358 var addb = text.next();
5359 var errt = addb.next();
5360 var name = text.val();
5361 var used = false;
5362
5363 if (!/^[a-zA-Z0-9_]*$/.test(name))
5364 {
5365 errt.text(_luci2.tr('Invalid section name')).show();
5366 text.addClass('error');
5367 addb.prop('disabled', true);
5368 return false;
5369 }
5370
5371 for (var sid in self.map.uci.values[self.map.uci_package])
5372 if (sid == name)
5373 {
5374 used = true;
5375 break;
5376 }
5377
5378 for (var sid in self.map.uci.creates[self.map.uci_package])
5379 if (sid == name)
5380 {
5381 used = true;
5382 break;
5383 }
5384
5385 if (used)
5386 {
5387 errt.text(_luci2.tr('Name already used')).show();
5388 text.addClass('error');
5389 addb.prop('disabled', true);
5390 return false;
5391 }
5392
5393 errt.text('').hide();
5394 text.removeClass('error');
5395 addb.prop('disabled', false);
5396 return true;
5397 },
5398
5399 _ev_tab: function(ev)
5400 {
5401 var self = ev.data.self;
5402 var sid = ev.data.sid;
5403
5404 self.validate();
5405 self.active_tab[sid] = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
5406 },
5407
5408 _ev_panel_collapse: function(ev)
5409 {
5410 var self = ev.data.self;
5411
5412 var this_panel = $(ev.target);
5413 var this_toggle = this_panel.prevAll('[data-toggle="collapse"]:first');
5414
5415 var prev_toggle = $($(ev.delegateTarget).find('[data-toggle="collapse"]:eq(%d)'.format(self.active_panel)));
5416 var prev_panel = $(prev_toggle.attr('data-target'));
5417
5418 prev_panel
5419 .removeClass('in')
5420 .addClass('collapse');
5421
5422 prev_toggle.find('.luci2-section-teaser')
5423 .show()
5424 .children('span:last')
5425 .empty()
5426 .append(self.teaser(prev_panel.attr('data-luci2-sid')));
5427
5428 this_toggle.find('.luci2-section-teaser')
5429 .hide();
5430
5431 self.active_panel = parseInt(this_panel.attr('data-luci2-panel-index'));
5432 self.validate();
5433 },
5434
5435 _ev_panel_open: function(ev)
5436 {
5437 var self = ev.data.self;
5438 var panel = $($(this).attr('data-target'));
5439 var index = parseInt(panel.attr('data-luci2-panel-index'));
5440
5441 if (index == self.active_panel)
5442 ev.stopPropagation();
5443 },
5444
5445 _ev_sort: function(ev)
5446 {
5447 var self = ev.data.self;
5448 var cur_idx = ev.data.index;
5449 var new_idx = cur_idx + (ev.data.up ? -1 : 1);
5450 var s = self.sections();
5451
5452 if (new_idx >= 0 && new_idx < s.length)
5453 {
5454 var tmp = s[cur_idx]['.index'];
5455
5456 s[cur_idx]['.index'] = s[new_idx]['.index'];
5457 s[new_idx]['.index'] = tmp;
5458
5459 if (self.active_panel == cur_idx)
5460 self.active_panel = new_idx;
5461 else if (self.active_panel == new_idx)
5462 self.active_panel = cur_idx;
5463
5464 self.map.uci.reorder = true;
5465
5466 self.map.save();
5467 self.map.redraw();
5468 }
5469
5470 ev.stopPropagation();
5471 },
5472
5473 teaser: function(sid)
5474 {
5475 var tf = this.teaser_fields;
5476
5477 if (!tf)
5478 {
5479 tf = this.teaser_fields = [ ];
5480
5481 if ($.isArray(this.options.teasers))
5482 {
5483 for (var i = 0; i < this.options.teasers.length; i++)
5484 {
5485 var f = this.options.teasers[i];
5486 if (f instanceof _luci2.cbi.AbstractValue)
5487 tf.push(f);
5488 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
5489 tf.push(this.fields[f]);
5490 }
5491 }
5492 else
5493 {
5494 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
5495 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
5496 tf.push(this.tabs[i].fields[j]);
5497 }
5498 }
5499
5500 var t = '';
5501
5502 for (var i = 0; i < tf.length; i++)
5503 {
5504 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
5505 continue;
5506
5507 var n = tf[i].options.caption || tf[i].name;
5508 var v = tf[i].textvalue(sid);
5509
5510 if (typeof(v) == 'undefined')
5511 continue;
5512
5513 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
5514 }
5515
5516 return t;
5517 },
5518
5519 _render_add: function()
5520 {
5521 if (!this.options.addremove)
5522 return null;
5523
5524 var text = _luci2.tr('Add section');
5525 var ttip = _luci2.tr('Create new section...');
5526
5527 if ($.isArray(this.options.add_caption))
5528 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
5529 else if (typeof(this.options.add_caption) == 'string')
5530 text = this.options.add_caption, ttip = '';
5531
5532 var add = $('<div />');
5533
5534 if (this.options.anonymous === false)
5535 {
5536 $('<input />')
5537 .addClass('cbi-input-text')
5538 .attr('type', 'text')
5539 .attr('placeholder', ttip)
5540 .blur({ self: this }, this._ev_sid)
5541 .keyup({ self: this }, this._ev_sid)
5542 .appendTo(add);
5543
5544 $('<img />')
5545 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
5546 .attr('title', text)
5547 .addClass('cbi-button')
5548 .click({ self: this }, this._ev_add)
5549 .appendTo(add);
5550
5551 $('<div />')
5552 .addClass('cbi-value-error')
5553 .hide()
5554 .appendTo(add);
5555 }
5556 else
5557 {
5558 _luci2.ui.button(text, 'success', ttip)
5559 .click({ self: this }, this._ev_add)
5560 .appendTo(add);
5561 }
5562
5563 return add;
5564 },
5565
5566 _render_remove: function(sid, index)
5567 {
5568 if (!this.options.addremove)
5569 return null;
5570
5571 var text = _luci2.tr('Remove');
5572 var ttip = _luci2.tr('Remove this section');
5573
5574 if ($.isArray(this.options.remove_caption))
5575 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
5576 else if (typeof(this.options.remove_caption) == 'string')
5577 text = this.options.remove_caption, ttip = '';
5578
5579 return _luci2.ui.button(text, 'danger', ttip)
5580 .click({ self: this, sid: sid, index: index }, this._ev_remove);
5581 },
5582
5583 _render_sort: function(sid, index)
5584 {
5585 if (!this.options.sortable)
5586 return null;
5587
5588 var b1 = _luci2.ui.button('↑', 'info', _luci2.tr('Move up'))
5589 .click({ self: this, index: index, up: true }, this._ev_sort);
5590
5591 var b2 = _luci2.ui.button('↓', 'info', _luci2.tr('Move down'))
5592 .click({ self: this, index: index, up: false }, this._ev_sort);
5593
5594 return b1.add(b2);
5595 },
5596
5597 _render_caption: function()
5598 {
5599 return $('<h3 />')
5600 .addClass('panel-title')
5601 .append(this.label('caption') || this.uci_type);
5602 },
5603
5604 _render_description: function()
5605 {
5606 var text = this.label('description');
5607
5608 if (text)
5609 return $('<div />')
5610 .addClass('luci2-section-description')
5611 .text(text);
5612
5613 return null;
5614 },
5615
5616 _render_teaser: function(sid, index)
5617 {
5618 if (this.options.collabsible || this.map.options.collabsible)
5619 {
5620 return $('<div />')
5621 .attr('id', this.id('teaser', sid))
5622 .addClass('luci2-section-teaser well well-sm')
5623 .append($('<span />')
5624 .addClass('badge'))
5625 .append($('<span />'));
5626 }
5627
5628 return null;
5629 },
5630
5631 _render_head: function(condensed)
5632 {
5633 if (condensed)
5634 return null;
5635
5636 return $('<div />')
5637 .addClass('panel-heading')
5638 .append(this._render_caption())
5639 .append(this._render_description());
5640 },
5641
5642 _render_tab_description: function(sid, index, tab_index)
5643 {
5644 var tab = this.tabs[tab_index];
5645
5646 if (typeof(tab.description) == 'string')
5647 {
5648 return $('<div />')
5649 .addClass('cbi-tab-descr')
5650 .text(tab.description);
5651 }
5652
5653 return null;
5654 },
5655
5656 _render_tab_head: function(sid, index, tab_index)
5657 {
5658 var tab = this.tabs[tab_index];
5659 var cur = this.active_tab[sid] || 0;
5660
5661 var tabh = $('<li />')
5662 .append($('<a />')
5663 .attr('id', this.id('nodetab', sid, tab.id))
5664 .attr('href', '#' + this.id('node', sid, tab.id))
5665 .attr('data-toggle', 'tab')
5666 .attr('data-luci2-tab-index', tab_index)
5667 .text((tab.caption ? tab.caption.format(tab.id) : tab.id) + ' ')
5668 .append($('<span />')
5669 .addClass('badge'))
5670 .on('shown.bs.tab', { self: this, sid: sid }, this._ev_tab));
5671
5672 if (cur == tab_index)
5673 tabh.addClass('active');
5674
5675 return tabh;
5676 },
5677
5678 _render_tab_body: function(sid, index, tab_index)
5679 {
5680 var tab = this.tabs[tab_index];
5681 var cur = this.active_tab[sid] || 0;
5682
5683 var tabb = $('<div />')
5684 .addClass('tab-pane')
5685 .attr('id', this.id('node', sid, tab.id))
5686 .attr('data-luci2-tab-index', tab_index)
5687 .append(this._render_tab_description(sid, index, tab_index));
5688
5689 if (cur == tab_index)
5690 tabb.addClass('active');
5691
5692 for (var i = 0; i < tab.fields.length; i++)
5693 tabb.append(tab.fields[i].render(sid));
5694
5695 return tabb;
5696 },
5697
5698 _render_section_head: function(sid, index)
5699 {
5700 var head = $('<div />')
5701 .addClass('luci2-section-header')
5702 .append(this._render_teaser(sid, index))
5703 .append($('<div />')
5704 .addClass('btn-group')
5705 .append(this._render_sort(sid, index))
5706 .append(this._render_remove(sid, index)));
5707
5708 if (this.options.collabsible)
5709 {
5710 head.attr('data-toggle', 'collapse')
5711 .attr('data-parent', this.id('sectiongroup'))
5712 .attr('data-target', '#' + this.id('panel', sid))
5713 .on('click', { self: this }, this._ev_panel_open);
5714 }
5715
5716 return head;
5717 },
5718
5719 _render_section_body: function(sid, index)
5720 {
5721 var body = $('<div />')
5722 .attr('id', this.id('panel', sid))
5723 .attr('data-luci2-panel-index', index)
5724 .attr('data-luci2-sid', sid);
5725
5726 if (this.options.collabsible || this.map.options.collabsible)
5727 {
5728 body.addClass('panel-collapse collapse');
5729
5730 if (index == this.active_panel)
5731 body.addClass('in');
5732 }
5733
5734 var tab_heads = $('<ul />')
5735 .addClass('nav nav-tabs');
5736
5737 var tab_bodies = $('<div />')
5738 .addClass('form-horizontal tab-content')
5739 .append(tab_heads);
5740
5741 for (var j = 0; j < this.tabs.length; j++)
5742 {
5743 tab_heads.append(this._render_tab_head(sid, index, j));
5744 tab_bodies.append(this._render_tab_body(sid, index, j));
5745 }
5746
5747 body.append(tab_bodies);
5748
5749 if (this.tabs.length <= 1)
5750 tab_heads.hide();
5751
5752 return body;
5753 },
5754
5755 _render_body: function(condensed)
5756 {
5757 var s = this.sections();
5758
5759 if (this.active_panel < 0)
5760 this.active_panel += s.length;
5761 else if (this.active_panel >= s.length)
5762 this.active_panel = s.length - 1;
5763
5764 var body = $('<ul />')
5765 .addClass('list-group');
5766
5767 if (this.options.collabsible)
5768 {
5769 body.attr('id', this.id('sectiongroup'))
5770 .on('show.bs.collapse', { self: this }, this._ev_panel_collapse);
5771 }
5772
5773 if (s.length == 0)
5774 {
5775 body.append($('<li />')
5776 .addClass('list-group-item text-muted')
5777 .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.')))
5778 }
5779
5780 for (var i = 0; i < s.length; i++)
5781 {
5782 var sid = s[i]['.name'];
5783 var inst = this.instance[sid] = { tabs: [ ] };
5784
5785 body.append($('<li />')
5786 .addClass('list-group-item')
5787 .append(this._render_section_head(sid, i))
5788 .append(this._render_section_body(sid, i)));
5789 }
5790
5791 return body;
5792 },
5793
5794 render: function(condensed)
5795 {
5796 this.instance = { };
5797
5798 var panel = $('<div />')
5799 .addClass('panel panel-default')
5800 .append(this._render_head(condensed))
5801 .append(this._render_body(condensed));
5802
5803 if (this.options.addremove)
5804 panel.append($('<div />')
5805 .addClass('panel-footer')
5806 .append(this._render_add()));
5807
5808 return panel;
5809 },
5810
5811 finish: function()
5812 {
5813 var s = this.sections();
5814
5815 for (var i = 0; i < s.length; i++)
5816 {
5817 var sid = s[i]['.name'];
5818
5819 this.validate_section(sid);
5820
5821 if (i != this.active_panel)
5822 $('#' + this.id('teaser', sid)).children('span:last')
5823 .append(this.teaser(sid));
5824 else
5825 $('#' + this.id('teaser', sid))
5826 .hide();
5827 }
5828 }
5829 });
5830
5831 this.cbi.TableSection = this.cbi.TypedSection.extend({
5832 _render_table_head: function()
5833 {
5834 var thead = $('<thead />')
5835 .append($('<tr />')
5836 .addClass('cbi-section-table-titles'));
5837
5838 for (var j = 0; j < this.tabs[0].fields.length; j++)
5839 thead.children().append($('<th />')
5840 .addClass('cbi-section-table-cell')
5841 .css('width', this.tabs[0].fields[j].options.width || '')
5842 .append(this.tabs[0].fields[j].label('caption')));
5843
5844 if (this.options.addremove !== false || this.options.sortable)
5845 thead.children().append($('<th />')
5846 .addClass('cbi-section-table-cell')
5847 .text(' '));
5848
5849 return thead;
5850 },
5851
5852 _render_table_row: function(sid, index)
5853 {
5854 var row = $('<tr />')
5855 .attr('data-luci2-sid', sid);
5856
5857 for (var j = 0; j < this.tabs[0].fields.length; j++)
5858 {
5859 row.append($('<td />')
5860 .css('width', this.tabs[0].fields[j].options.width || '')
5861 .append(this.tabs[0].fields[j].render(sid, true)));
5862 }
5863
5864 if (this.options.addremove !== false || this.options.sortable)
5865 {
5866 row.append($('<td />')
5867 .addClass('text-right')
5868 .append($('<div />')
5869 .addClass('btn-group')
5870 .append(this._render_sort(sid, index))
5871 .append(this._render_remove(sid, index))));
5872 }
5873
5874 return row;
5875 },
5876
5877 _render_table_body: function()
5878 {
5879 var s = this.sections();
5880
5881 var tbody = $('<tbody />');
5882
5883 if (s.length == 0)
5884 {
5885 var cols = this.tabs[0].fields.length;
5886
5887 if (this.options.addremove !== false || this.options.sortable)
5888 cols++;
5889
5890 tbody.append($('<tr />')
5891 .append($('<td />')
5892 .addClass('text-muted')
5893 .attr('colspan', cols)
5894 .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.'))));
5895 }
5896
5897 for (var i = 0; i < s.length; i++)
5898 {
5899 var sid = s[i]['.name'];
5900 var inst = this.instance[sid] = { tabs: [ ] };
5901
5902 tbody.append(this._render_table_row(sid, i));
5903 }
5904
5905 return tbody;
5906 },
5907
5908 _render_body: function(condensed)
5909 {
5910 return $('<table />')
5911 .addClass('table table-condensed table-hover')
5912 .append(this._render_table_head())
5913 .append(this._render_table_body());
5914 }
5915 });
5916
5917 this.cbi.NamedSection = this.cbi.TypedSection.extend({
5918 sections: function(cb)
5919 {
5920 var sa = [ ];
5921 var pkg = this.map.uci.values[this.map.uci_package];
5922
5923 for (var s in pkg)
5924 if (pkg[s]['.name'] == this.uci_type)
5925 {
5926 sa.push(pkg[s]);
5927 break;
5928 }
5929
5930 if (typeof(cb) == 'function' && sa.length > 0)
5931 cb.apply(this, [ sa[0] ]);
5932
5933 return sa;
5934 }
5935 });
5936
5937 this.cbi.DummySection = this.cbi.TypedSection.extend({
5938 sections: function(cb)
5939 {
5940 if (typeof(cb) == 'function')
5941 cb.apply(this, [ { '.name': this.uci_type } ]);
5942
5943 return [ { '.name': this.uci_type } ];
5944 }
5945 });
5946
5947 this.cbi.Map = this.ui.AbstractWidget.extend({
5948 init: function(uci_package, options)
5949 {
5950 var self = this;
5951
5952 this.uci_package = uci_package;
5953 this.sections = [ ];
5954 this.options = _luci2.defaults(options, {
5955 save: function() { },
5956 prepare: function() {
5957 return _luci2.uci.writable(function(writable) {
5958 self.options.readonly = !writable;
5959 });
5960 }
5961 });
5962 },
5963
5964 _load_cb: function(packages)
5965 {
5966 for (var i = 0; i < packages.length; i++)
5967 {
5968 this.uci.values[packages[i]['.package']] = packages[i];
5969 delete packages[i]['.package'];
5970 }
5971
5972 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
5973
5974 for (var i = 0; i < this.sections.length; i++)
5975 {
5976 for (var f in this.sections[i].fields)
5977 {
5978 if (typeof(this.sections[i].fields[f].load) != 'function')
5979 continue;
5980
5981 var s = this.sections[i].sections();
5982 for (var j = 0; j < s.length; j++)
5983 {
5984 var rv = this.sections[i].fields[f].load(s[j]['.name']);
5985 if (_luci2.isDeferred(rv))
5986 deferreds.push(rv);
5987 }
5988 }
5989 }
5990
5991 return $.when.apply($, deferreds);
5992 },
5993
5994 load: function()
5995 {
5996 var self = this;
5997
5998 this.uci = {
5999 newid: 0,
6000 values: { },
6001 creates: { },
6002 changes: { },
6003 deletes: { },
6004 reorder: false
6005 };
6006
6007 var packages = { };
6008
6009 for (var i = 0; i < this.sections.length; i++)
6010 this.sections[i].ucipackages(packages);
6011
6012 packages[this.uci_package] = true;
6013
6014 _luci2.rpc.batch();
6015
6016 for (var pkg in packages)
6017 _luci2.uci.get_all(pkg);
6018
6019 return _luci2.rpc.flush().then(function(packages) {
6020 return self._load_cb(packages);
6021 });
6022 },
6023
6024 _ev_tab: function(ev)
6025 {
6026 var self = ev.data.self;
6027
6028 self.validate();
6029 self.active_tab = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
6030 },
6031
6032 _render_tab_head: function(tab_index)
6033 {
6034 var section = this.sections[tab_index];
6035 var cur = this.active_tab || 0;
6036
6037 var tabh = $('<li />')
6038 .append($('<a />')
6039 .attr('id', section.id('sectiontab'))
6040 .attr('href', '#' + section.id('section'))
6041 .attr('data-toggle', 'tab')
6042 .attr('data-luci2-tab-index', tab_index)
6043 .text(section.label('caption') + ' ')
6044 .append($('<span />')
6045 .addClass('badge'))
6046 .on('shown.bs.tab', { self: this }, this._ev_tab));
6047
6048 if (cur == tab_index)
6049 tabh.addClass('active');
6050
6051 return tabh;
6052 },
6053
6054 _render_tab_body: function(tab_index)
6055 {
6056 var section = this.sections[tab_index];
6057 var desc = section.label('description');
6058 var cur = this.active_tab || 0;
6059
6060 var tabb = $('<div />')
6061 .addClass('tab-pane')
6062 .attr('id', section.id('section'))
6063 .attr('data-luci2-tab-index', tab_index);
6064
6065 if (cur == tab_index)
6066 tabb.addClass('active');
6067
6068 if (desc)
6069 tabb.append($('<p />')
6070 .text(desc));
6071
6072 var s = section.render(this.options.tabbed);
6073
6074 if (this.options.readonly || section.options.readonly)
6075 s.find('input, select, button, img.cbi-button').attr('disabled', true);
6076
6077 tabb.append(s);
6078
6079 return tabb;
6080 },
6081
6082 _render_body: function()
6083 {
6084 var tabs = $('<ul />')
6085 .addClass('nav nav-tabs');
6086
6087 var body = $('<div />')
6088 .append(tabs);
6089
6090 for (var i = 0; i < this.sections.length; i++)
6091 {
6092 tabs.append(this._render_tab_head(i));
6093 body.append(this._render_tab_body(i));
6094 }
6095
6096 if (this.options.tabbed)
6097 body.addClass('tab-content');
6098 else
6099 tabs.hide();
6100
6101 return body;
6102 },
6103
6104 render: function()
6105 {
6106 var map = $('<form />');
6107
6108 if (typeof(this.options.caption) == 'string')
6109 map.append($('<h2 />')
6110 .text(this.options.caption));
6111
6112 if (typeof(this.options.description) == 'string')
6113 map.append($('<p />')
6114 .text(this.options.description));
6115
6116 map.append(this._render_body());
6117
6118 if (this.options.pageaction !== false)
6119 {
6120 map.append($('<div />')
6121 .addClass('panel panel-default panel-body text-right')
6122 .append($('<div />')
6123 .addClass('btn-group')
6124 .append(_luci2.ui.button(_luci2.tr('Save & Apply'), 'primary')
6125 .click({ self: this }, function(ev) { }))
6126 .append(_luci2.ui.button(_luci2.tr('Save'), 'default')
6127 .click({ self: this }, function(ev) { ev.data.self.send(); }))
6128 .append(_luci2.ui.button(_luci2.tr('Reset'), 'default')
6129 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); }))));
6130 }
6131
6132 return map;
6133 },
6134
6135 finish: function()
6136 {
6137 for (var i = 0; i < this.sections.length; i++)
6138 this.sections[i].finish();
6139
6140 this.validate();
6141 },
6142
6143 redraw: function()
6144 {
6145 this.target.hide().empty().append(this.render());
6146 this.finish();
6147 this.target.show();
6148 },
6149
6150 section: function(widget, uci_type, options)
6151 {
6152 var w = widget ? new widget(uci_type, options) : null;
6153
6154 if (!(w instanceof _luci2.cbi.AbstractSection))
6155 throw 'Widget must be an instance of AbstractSection';
6156
6157 w.map = this;
6158 w.index = this.sections.length;
6159
6160 this.sections.push(w);
6161 return w;
6162 },
6163
6164 formvalue: function()
6165 {
6166 var rv = { };
6167
6168 for (var i = 0; i < this.sections.length; i++)
6169 {
6170 var sids = this.sections[i].formvalue();
6171 for (var sid in sids)
6172 {
6173 var s = rv[sid] || (rv[sid] = { });
6174 $.extend(s, sids[sid]);
6175 }
6176 }
6177
6178 return rv;
6179 },
6180
6181 add: function(conf, type, name)
6182 {
6183 var c = this.uci.creates;
6184 var s = '.new.%d'.format(this.uci.newid++);
6185
6186 if (!c[conf])
6187 c[conf] = { };
6188
6189 c[conf][s] = {
6190 '.type': type,
6191 '.name': s,
6192 '.create': name,
6193 '.anonymous': !name,
6194 '.index': 1000 + this.uci.newid
6195 };
6196
6197 return s;
6198 },
6199
6200 remove: function(conf, sid)
6201 {
6202 var n = this.uci.creates;
6203 var c = this.uci.changes;
6204 var d = this.uci.deletes;
6205
6206 /* requested deletion of a just created section */
6207 if (sid.indexOf('.new.') == 0)
6208 {
6209 if (n[conf])
6210 delete n[conf][sid];
6211 }
6212 else
6213 {
6214 if (c[conf])
6215 delete c[conf][sid];
6216
6217 if (!d[conf])
6218 d[conf] = { };
6219
6220 d[conf][sid] = true;
6221 }
6222 },
6223
6224 ucisections: function(conf, cb)
6225 {
6226 var sa = [ ];
6227 var pkg = this.uci.values[conf];
6228 var crt = this.uci.creates[conf];
6229 var del = this.uci.deletes[conf];
6230
6231 if (!pkg)
6232 return sa;
6233
6234 for (var s in pkg)
6235 if (!del || del[s] !== true)
6236 sa.push(pkg[s]);
6237
6238 if (crt)
6239 for (var s in crt)
6240 sa.push(crt[s]);
6241
6242 sa.sort(function(a, b) {
6243 return a['.index'] - b['.index'];
6244 });
6245
6246 for (var i = 0; i < sa.length; i++)
6247 sa[i]['.index'] = i;
6248
6249 if (typeof(cb) == 'function')
6250 for (var i = 0; i < sa.length; i++)
6251 cb.apply(this, [ sa[i] ]);
6252
6253 return sa;
6254 },
6255
6256 get: function(conf, sid, opt)
6257 {
6258 var v = this.uci.values;
6259 var n = this.uci.creates;
6260 var c = this.uci.changes;
6261 var d = this.uci.deletes;
6262
6263 /* requested option in a just created section */
6264 if (sid.indexOf('.new.') == 0)
6265 {
6266 if (!n[conf])
6267 return undefined;
6268
6269 if (typeof(opt) == 'undefined')
6270 return (n[conf][sid] || { });
6271
6272 return n[conf][sid][opt];
6273 }
6274
6275 /* requested an option value */
6276 if (typeof(opt) != 'undefined')
6277 {
6278 /* check whether option was deleted */
6279 if (d[conf] && d[conf][sid])
6280 {
6281 if (d[conf][sid] === true)
6282 return undefined;
6283
6284 for (var i = 0; i < d[conf][sid].length; i++)
6285 if (d[conf][sid][i] == opt)
6286 return undefined;
6287 }
6288
6289 /* check whether option was changed */
6290 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
6291 return c[conf][sid][opt];
6292
6293 /* return base value */
6294 if (v[conf] && v[conf][sid])
6295 return v[conf][sid][opt];
6296
6297 return undefined;
6298 }
6299
6300 /* requested an entire section */
6301 if (v[conf])
6302 return (v[conf][sid] || { });
6303
6304 return undefined;
6305 },
6306
6307 set: function(conf, sid, opt, val)
6308 {
6309 var n = this.uci.creates;
6310 var c = this.uci.changes;
6311 var d = this.uci.deletes;
6312
6313 if (sid.indexOf('.new.') == 0)
6314 {
6315 if (n[conf] && n[conf][sid])
6316 {
6317 if (typeof(val) != 'undefined')
6318 n[conf][sid][opt] = val;
6319 else
6320 delete n[conf][sid][opt];
6321 }
6322 }
6323 else if (typeof(val) != 'undefined')
6324 {
6325 if (!c[conf])
6326 c[conf] = { };
6327
6328 if (!c[conf][sid])
6329 c[conf][sid] = { };
6330
6331 c[conf][sid][opt] = val;
6332 }
6333 else
6334 {
6335 if (!d[conf])
6336 d[conf] = { };
6337
6338 if (!d[conf][sid])
6339 d[conf][sid] = [ ];
6340
6341 d[conf][sid].push(opt);
6342 }
6343 },
6344
6345 validate: function()
6346 {
6347 var rv = true;
6348
6349 for (var i = 0; i < this.sections.length; i++)
6350 {
6351 if (!this.sections[i].validate())
6352 rv = false;
6353 }
6354
6355 return rv;
6356 },
6357
6358 save: function()
6359 {
6360 if (this.options.readonly)
6361 return _luci2.deferrable();
6362
6363 var deferreds = [ _luci2.deferrable(this.options.save()) ];
6364
6365 for (var i = 0; i < this.sections.length; i++)
6366 {
6367 if (this.sections[i].options.readonly)
6368 continue;
6369
6370 for (var f in this.sections[i].fields)
6371 {
6372 if (typeof(this.sections[i].fields[f].save) != 'function')
6373 continue;
6374
6375 var s = this.sections[i].sections();
6376 for (var j = 0; j < s.length; j++)
6377 {
6378 var rv = this.sections[i].fields[f].save(s[j]['.name']);
6379 if (_luci2.isDeferred(rv))
6380 deferreds.push(rv);
6381 }
6382 }
6383 }
6384
6385 return $.when.apply($, deferreds);
6386 },
6387
6388 _send_uci_reorder: function()
6389 {
6390 if (!this.uci.reorder)
6391 return _luci2.deferrable();
6392
6393 _luci2.rpc.batch();
6394
6395 /*
6396 gather all created and existing sections, sort them according
6397 to their index value and issue an uci order call
6398 */
6399 for (var c in this.uci.values)
6400 {
6401 var o = [ ];
6402
6403 if (this.uci.creates && this.uci.creates[c])
6404 for (var s in this.uci.creates[c])
6405 o.push(this.uci.creates[c][s]);
6406
6407 for (var s in this.uci.values[c])
6408 o.push(this.uci.values[c][s]);
6409
6410 if (o.length > 0)
6411 {
6412 o.sort(function(a, b) {
6413 return (a['.index'] - b['.index']);
6414 });
6415
6416 var sids = [ ];
6417
6418 for (var i = 0; i < o.length; i++)
6419 sids.push(o[i]['.name']);
6420
6421 _luci2.uci.order(c, sids);
6422 }
6423 }
6424
6425 return _luci2.rpc.flush();
6426 },
6427
6428 _send_uci: function()
6429 {
6430 _luci2.rpc.batch();
6431
6432 var self = this;
6433 var snew = [ ];
6434
6435 if (this.uci.creates)
6436 for (var c in this.uci.creates)
6437 for (var s in this.uci.creates[c])
6438 {
6439 var r = {
6440 config: c,
6441 values: { }
6442 };
6443
6444 for (var k in this.uci.creates[c][s])
6445 {
6446 if (k == '.type')
6447 r.type = this.uci.creates[c][s][k];
6448 else if (k == '.create')
6449 r.name = this.uci.creates[c][s][k];
6450 else if (k.charAt(0) != '.')
6451 r.values[k] = this.uci.creates[c][s][k];
6452 }
6453
6454 snew.push(this.uci.creates[c][s]);
6455
6456 _luci2.uci.add(r.config, r.type, r.name, r.values);
6457 }
6458
6459 if (this.uci.changes)
6460 for (var c in this.uci.changes)
6461 for (var s in this.uci.changes[c])
6462 _luci2.uci.set(c, s, this.uci.changes[c][s]);
6463
6464 if (this.uci.deletes)
6465 for (var c in this.uci.deletes)
6466 for (var s in this.uci.deletes[c])
6467 {
6468 var o = this.uci.deletes[c][s];
6469 _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
6470 }
6471
6472 return _luci2.rpc.flush().then(function(responses) {
6473 /*
6474 array "snew" holds references to the created uci sections,
6475 use it to assign the returned names of the new sections
6476 */
6477 for (var i = 0; i < snew.length; i++)
6478 snew[i]['.name'] = responses[i];
6479
6480 return self._send_uci_reorder();
6481 });
6482 },
6483
6484 send: function()
6485 {
6486 if (!this.validate())
6487 return _luci2.deferrable();
6488
6489 var self = this;
6490
6491 _luci2.ui.saveScrollTop();
6492 _luci2.ui.loading(true);
6493
6494 return this.save().then(function() {
6495 return self._send_uci();
6496 }).then(function() {
6497 return _luci2.ui.updateChanges();
6498 }).then(function() {
6499 return self.load();
6500 }).then(function() {
6501 self.redraw();
6502 self = null;
6503
6504 _luci2.ui.loading(false);
6505 _luci2.ui.restoreScrollTop();
6506 });
6507 },
6508
6509 insertInto: function(id)
6510 {
6511 var self = this;
6512 self.target = $(id);
6513
6514 _luci2.ui.loading(true);
6515 self.target.hide();
6516
6517 return self.load().then(function() {
6518 self.target.empty().append(self.render());
6519 self.finish();
6520 self.target.show();
6521 self = null;
6522 _luci2.ui.loading(false);
6523 });
6524 }
6525 });
6526 };