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