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