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