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