d2ad812b5549b2be20f9508c8a844b4ea9c00e8c
[project/luci2/ui.git] / luci2 / htdocs / luci2 / luci2.js
1 /*
2         LuCI2 - OpenWrt Web Interface
3
4         Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
5
6         Licensed under the Apache License, Version 2.0 (the "License");
7         you may not use this file except in compliance with the License.
8         You may obtain a copy of the License at
9
10                 http://www.apache.org/licenses/LICENSE-2.0
11 */
12
13 String.prototype.format = function()
14 {
15         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
16         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
17
18         function esc(s, r) {
19                 for( var i = 0; i < r.length; i += 2 )
20                         s = s.replace(r[i], r[i+1]);
21                 return s;
22         }
23
24         var str = this;
25         var out = '';
26         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27         var a = b = [], numSubstitutions = 0, numMatches = 0;
28
29         while ((a = re.exec(str)) != null)
30         {
31                 var m = a[1];
32                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33                 var pPrecision = a[6], pType = a[7];
34
35                 numMatches++;
36
37                 if (pType == '%')
38                 {
39                         subst = '%';
40                 }
41                 else
42                 {
43                         if (numSubstitutions < arguments.length)
44                         {
45                                 var param = arguments[numSubstitutions++];
46
47                                 var pad = '';
48                                 if (pPad && pPad.substr(0,1) == "'")
49                                         pad = leftpart.substr(1,1);
50                                 else if (pPad)
51                                         pad = pPad;
52
53                                 var justifyRight = true;
54                                 if (pJustify && pJustify === "-")
55                                         justifyRight = false;
56
57                                 var minLength = -1;
58                                 if (pMinLength)
59                                         minLength = parseInt(pMinLength);
60
61                                 var precision = -1;
62                                 if (pPrecision && pType == 'f')
63                                         precision = parseInt(pPrecision.substring(1));
64
65                                 var subst = param;
66
67                                 switch(pType)
68                                 {
69                                         case 'b':
70                                                 subst = (parseInt(param) || 0).toString(2);
71                                                 break;
72
73                                         case 'c':
74                                                 subst = String.fromCharCode(parseInt(param) || 0);
75                                                 break;
76
77                                         case 'd':
78                                                 subst = (parseInt(param) || 0);
79                                                 break;
80
81                                         case 'u':
82                                                 subst = Math.abs(parseInt(param) || 0);
83                                                 break;
84
85                                         case 'f':
86                                                 subst = (precision > -1)
87                                                         ? ((parseFloat(param) || 0.0)).toFixed(precision)
88                                                         : (parseFloat(param) || 0.0);
89                                                 break;
90
91                                         case 'o':
92                                                 subst = (parseInt(param) || 0).toString(8);
93                                                 break;
94
95                                         case 's':
96                                                 subst = param;
97                                                 break;
98
99                                         case 'x':
100                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
101                                                 break;
102
103                                         case 'X':
104                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
105                                                 break;
106
107                                         case 'h':
108                                                 subst = esc(param, html_esc);
109                                                 break;
110
111                                         case 'q':
112                                                 subst = esc(param, quot_esc);
113                                                 break;
114
115                                         case 'j':
116                                                 subst = String.serialize(param);
117                                                 break;
118
119                                         case 't':
120                                                 var td = 0;
121                                                 var th = 0;
122                                                 var tm = 0;
123                                                 var ts = (param || 0);
124
125                                                 if (ts > 60) {
126                                                         tm = Math.floor(ts / 60);
127                                                         ts = (ts % 60);
128                                                 }
129
130                                                 if (tm > 60) {
131                                                         th = Math.floor(tm / 60);
132                                                         tm = (tm % 60);
133                                                 }
134
135                                                 if (th > 24) {
136                                                         td = Math.floor(th / 24);
137                                                         th = (th % 24);
138                                                 }
139
140                                                 subst = (td > 0)
141                                                         ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142                                                         : '%dh %dm %ds'.format(th, tm, ts);
143
144                                                 break;
145
146                                         case 'm':
147                                                 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148                                                 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
149
150                                                 var i = 0;
151                                                 var val = parseFloat(param || 0);
152                                                 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
153
154                                                 for (i = 0; (i < units.length) && (val > mf); i++)
155                                                         val /= mf;
156
157                                                 subst = val.toFixed(pr) + ' ' + units[i];
158                                                 break;
159                                 }
160
161                                 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
162
163                                 if (minLength > 0 && pad.length > 0)
164                                         for (var i = 0; i < (minLength - subst.length); i++)
165                                                 subst = justifyRight ? (pad + subst) : (subst + pad);
166                         }
167                 }
168
169                 out += leftpart + subst;
170                 str = str.substr(m.length);
171         }
172
173         return out + str;
174 }
175
176 function LuCI2()
177 {
178         var _luci2 = this;
179
180         var Class = function() { };
181
182         Class.extend = function(properties)
183         {
184                 Class.initializing = true;
185
186                 var prototype = new this();
187                 var superprot = this.prototype;
188
189                 Class.initializing = false;
190
191                 $.extend(prototype, properties, {
192                         callSuper: function() {
193                                 var args = [ ];
194                                 var meth = arguments[0];
195
196                                 if (typeof(superprot[meth]) != 'function')
197                                         return undefined;
198
199                                 for (var i = 1; i < arguments.length; i++)
200                                         args.push(arguments[i]);
201
202                                 return superprot[meth].apply(this, args);
203                         }
204                 });
205
206                 function _class()
207                 {
208                         this.options = arguments[0] || { };
209
210                         if (!Class.initializing && typeof(this.init) == 'function')
211                                 this.init.apply(this, arguments);
212                 }
213
214                 _class.prototype = prototype;
215                 _class.prototype.constructor = _class;
216
217                 _class.extend = arguments.callee;
218
219                 return _class;
220         };
221
222         this.defaults = function(obj, def)
223         {
224                 for (var key in def)
225                         if (typeof(obj[key]) == 'undefined')
226                                 obj[key] = def[key];
227
228                 return obj;
229         };
230
231         this.isDeferred = function(x)
232         {
233                 return (typeof(x) == 'object' &&
234                         typeof(x.then) == 'function' &&
235                         typeof(x.promise) == 'function');
236         };
237
238         this.deferrable = function()
239         {
240                 if (this.isDeferred(arguments[0]))
241                         return arguments[0];
242
243                 var d = $.Deferred();
244                     d.resolve.apply(d, arguments);
245
246                 return d.promise();
247         };
248
249         this.i18n = {
250
251                 loaded: false,
252                 catalog: { },
253                 plural:  function(n) { return 0 + (n != 1) },
254
255                 init: function() {
256                         if (_luci2.i18n.loaded)
257                                 return;
258
259                         var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260                         var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
261
262                         for (var i = 0; i < langs.length; i++)
263                                 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
264                                         async:    false,
265                                         cache:    true,
266                                         dataType: 'json',
267                                         success:  function(data) {
268                                                 $.extend(_luci2.i18n.catalog, data);
269
270                                                 var pe = _luci2.i18n.catalog[''];
271                                                 if (pe)
272                                                 {
273                                                         delete _luci2.i18n.catalog[''];
274                                                         try {
275                                                                 var pf = new Function('n', 'return 0 + (' + pe + ')');
276                                                                 _luci2.i18n.plural = pf;
277                                                         } catch (e) { };
278                                                 }
279                                         }
280                                 });
281
282                         _luci2.i18n.loaded = true;
283                 }
284
285         };
286
287         this.tr = function(msgid)
288         {
289                 _luci2.i18n.init();
290
291                 var msgstr = _luci2.i18n.catalog[msgid];
292
293                 if (typeof(msgstr) == 'undefined')
294                         return msgid;
295                 else if (typeof(msgstr) == 'string')
296                         return msgstr;
297                 else
298                         return msgstr[0];
299         };
300
301         this.trp = function(msgid, msgid_plural, count)
302         {
303                 _luci2.i18n.init();
304
305                 var msgstr = _luci2.i18n.catalog[msgid];
306
307                 if (typeof(msgstr) == 'undefined')
308                         return (count == 1) ? msgid : msgid_plural;
309                 else if (typeof(msgstr) == 'string')
310                         return msgstr;
311                 else
312                         return msgstr[_luci2.i18n.plural(count)];
313         };
314
315         this.trc = function(msgctx, msgid)
316         {
317                 _luci2.i18n.init();
318
319                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
320
321                 if (typeof(msgstr) == 'undefined')
322                         return msgid;
323                 else if (typeof(msgstr) == 'string')
324                         return msgstr;
325                 else
326                         return msgstr[0];
327         };
328
329         this.trcp = function(msgctx, msgid, msgid_plural, count)
330         {
331                 _luci2.i18n.init();
332
333                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
334
335                 if (typeof(msgstr) == 'undefined')
336                         return (count == 1) ? msgid : msgid_plural;
337                 else if (typeof(msgstr) == 'string')
338                         return msgstr;
339                 else
340                         return msgstr[_luci2.i18n.plural(count)];
341         };
342
343         this.setHash = function(key, value)
344         {
345                 var h = '';
346                 var data = this.getHash(undefined);
347
348                 if (typeof(value) == 'undefined')
349                         delete data[key];
350                 else
351                         data[key] = value;
352
353                 var keys = [ ];
354                 for (var k in data)
355                         keys.push(k);
356
357                 keys.sort();
358
359                 for (var i = 0; i < keys.length; i++)
360                 {
361                         if (i > 0)
362                                 h += ',';
363
364                         h += keys[i] + ':' + data[keys[i]];
365                 }
366
367                 if (h)
368                         location.hash = '#' + h;
369         };
370
371         this.getHash = function(key)
372         {
373                 var data = { };
374                 var tuples = (location.hash || '#').substring(1).split(/,/);
375
376                 for (var i = 0; i < tuples.length; i++)
377                 {
378                         var tuple = tuples[i].split(/:/);
379                         if (tuple.length == 2)
380                                 data[tuple[0]] = tuple[1];
381                 }
382
383                 if (typeof(key) != 'undefined')
384                         return data[key];
385
386                 return data;
387         };
388
389         this.globals = {
390                 timeout:  15000,
391                 resource: '/luci2',
392                 sid:      '00000000000000000000000000000000'
393         };
394
395         this.rpc = {
396
397                 _id: 1,
398                 _batch: undefined,
399                 _requests: { },
400
401                 _call: function(req, cb)
402                 {
403                         return $.ajax('/ubus', {
404                                 cache:       false,
405                                 contentType: 'application/json',
406                                 data:        JSON.stringify(req),
407                                 dataType:    'json',
408                                 type:        'POST',
409                                 timeout:     _luci2.globals.timeout
410                         }).then(cb);
411                 },
412
413                 _list_cb: function(msg)
414                 {
415                         /* verify message frame */
416                         if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
417                                 throw 'Invalid JSON response';
418
419                         return msg.result;
420                 },
421
422                 _call_cb: function(msg)
423                 {
424                         var data = [ ];
425                         var type = Object.prototype.toString;
426
427                         if (!$.isArray(msg))
428                                 msg = [ msg ];
429
430                         for (var i = 0; i < msg.length; i++)
431                         {
432                                 /* verify message frame */
433                                 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
434                                         throw 'Invalid JSON response';
435
436                                 /* fetch related request info */
437                                 var req = _luci2.rpc._requests[msg[i].id];
438                                 if (typeof(req) != 'object')
439                                         throw 'No related request for JSON response';
440
441                                 /* fetch response attribute and verify returned type */
442                                 var ret = undefined;
443
444                                 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
445                                         ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
446
447                                 if (req.expect)
448                                 {
449                                         for (var key in req.expect)
450                                         {
451                                                 if (typeof(ret) != 'undefined' && key != '')
452                                                         ret = ret[key];
453
454                                                 if (type.call(ret) != type.call(req.expect[key]))
455                                                         ret = req.expect[key];
456
457                                                 break;
458                                         }
459                                 }
460
461                                 /* apply filter */
462                                 if (typeof(req.filter) == 'function')
463                                 {
464                                         req.priv[0] = ret;
465                                         req.priv[1] = req.params;
466                                         ret = req.filter.apply(_luci2.rpc, req.priv);
467                                 }
468
469                                 /* store response data */
470                                 if (typeof(req.index) == 'number')
471                                         data[req.index] = ret;
472                                 else
473                                         data = ret;
474
475                                 /* delete request object */
476                                 delete _luci2.rpc._requests[msg[i].id];
477                         }
478
479                         return data;
480                 },
481
482                 list: function()
483                 {
484                         var params = [ ];
485                         for (var i = 0; i < arguments.length; i++)
486                                 params[i] = arguments[i];
487
488                         var msg = {
489                                 jsonrpc: '2.0',
490                                 id:      this._id++,
491                                 method:  'list',
492                                 params:  (params.length > 0) ? params : undefined
493                         };
494
495                         return this._call(msg, this._list_cb);
496                 },
497
498                 batch: function()
499                 {
500                         if (!$.isArray(this._batch))
501                                 this._batch = [ ];
502                 },
503
504                 flush: function()
505                 {
506                         if (!$.isArray(this._batch))
507                                 return _luci2.deferrable([ ]);
508
509                         var req = this._batch;
510                         delete this._batch;
511
512                         /* call rpc */
513                         return this._call(req, this._call_cb);
514                 },
515
516                 declare: function(options)
517                 {
518                         var _rpc = this;
519
520                         return function() {
521                                 /* build parameter object */
522                                 var p_off = 0;
523                                 var params = { };
524                                 if ($.isArray(options.params))
525                                         for (p_off = 0; p_off < options.params.length; p_off++)
526                                                 params[options.params[p_off]] = arguments[p_off];
527
528                                 /* all remaining arguments are private args */
529                                 var priv = [ undefined, undefined ];
530                                 for (; p_off < arguments.length; p_off++)
531                                         priv.push(arguments[p_off]);
532
533                                 /* store request info */
534                                 var req = _rpc._requests[_rpc._id] = {
535                                         expect: options.expect,
536                                         filter: options.filter,
537                                         params: params,
538                                         priv:   priv
539                                 };
540
541                                 /* build message object */
542                                 var msg = {
543                                         jsonrpc: '2.0',
544                                         id:      _rpc._id++,
545                                         method:  'call',
546                                         params:  [
547                                                 _luci2.globals.sid,
548                                                 options.object,
549                                                 options.method,
550                                                 params
551                                         ]
552                                 };
553
554                                 /* when a batch is in progress then store index in request data
555                                  * and push message object onto the stack */
556                                 if ($.isArray(_rpc._batch))
557                                 {
558                                         req.index = _rpc._batch.push(msg) - 1;
559                                         return _luci2.deferrable(msg);
560                                 }
561
562                                 /* call rpc */
563                                 return _rpc._call(msg, _rpc._call_cb);
564                         };
565                 }
566         };
567
568         this.uci = {
569
570                 writable: function()
571                 {
572                         return _luci2.session.access('ubus', 'uci', 'commit');
573                 },
574
575                 add: _luci2.rpc.declare({
576                         object: 'uci',
577                         method: 'add',
578                         params: [ 'config', 'type', 'name', 'values' ],
579                         expect: { section: '' }
580                 }),
581
582                 apply: function()
583                 {
584
585                 },
586
587                 configs: _luci2.rpc.declare({
588                         object: 'uci',
589                         method: 'configs',
590                         expect: { configs: [ ] }
591                 }),
592
593                 _changes: _luci2.rpc.declare({
594                         object: 'uci',
595                         method: 'changes',
596                         params: [ 'config' ],
597                         expect: { changes: [ ] }
598                 }),
599
600                 changes: function(config)
601                 {
602                         if (typeof(config) == 'string')
603                                 return this._changes(config);
604
605                         var configlist;
606                         return this.configs().then(function(configs) {
607                                 _luci2.rpc.batch();
608                                 configlist = configs;
609
610                                 for (var i = 0; i < configs.length; i++)
611                                         _luci2.uci._changes(configs[i]);
612
613                                 return _luci2.rpc.flush();
614                         }).then(function(changes) {
615                                 var rv = { };
616
617                                 for (var i = 0; i < configlist.length; i++)
618                                         if (changes[i].length)
619                                                 rv[configlist[i]] = changes[i];
620
621                                 return rv;
622                         });
623                 },
624
625                 commit: _luci2.rpc.declare({
626                         object: 'uci',
627                         method: 'commit',
628                         params: [ 'config' ]
629                 }),
630
631                 _delete_one: _luci2.rpc.declare({
632                         object: 'uci',
633                         method: 'delete',
634                         params: [ 'config', 'section', 'option' ]
635                 }),
636
637                 _delete_multiple: _luci2.rpc.declare({
638                         object: 'uci',
639                         method: 'delete',
640                         params: [ 'config', 'section', 'options' ]
641                 }),
642
643                 'delete': function(config, section, option)
644                 {
645                         if ($.isArray(option))
646                                 return this._delete_multiple(config, section, option);
647                         else
648                                 return this._delete_one(config, section, option);
649                 },
650
651                 delete_all: _luci2.rpc.declare({
652                         object: 'uci',
653                         method: 'delete',
654                         params: [ 'config', 'type', 'match' ]
655                 }),
656
657                 _foreach: _luci2.rpc.declare({
658                         object: 'uci',
659                         method: 'get',
660                         params: [ 'config', 'type' ],
661                         expect: { values: { } }
662                 }),
663
664                 foreach: function(config, type, cb)
665                 {
666                         return this._foreach(config, type).then(function(sections) {
667                                 for (var s in sections)
668                                         cb(sections[s]);
669                         });
670                 },
671
672                 get: _luci2.rpc.declare({
673                         object: 'uci',
674                         method: 'get',
675                         params: [ 'config', 'section', 'option' ],
676                         expect: { '': { } },
677                         filter: function(data, params) {
678                                 if (typeof(params.option) == 'undefined')
679                                         return data.values ? data.values['.type'] : undefined;
680                                 else
681                                         return data.value;
682                         }
683                 }),
684
685                 get_all: _luci2.rpc.declare({
686                         object: 'uci',
687                         method: 'get',
688                         params: [ 'config', 'section' ],
689                         expect: { values: { } },
690                         filter: function(data, params) {
691                                 if (typeof(params.section) == 'string')
692                                         data['.section'] = params.section;
693                                 else if (typeof(params.config) == 'string')
694                                         data['.package'] = params.config;
695                                 return data;
696                         }
697                 }),
698
699                 get_first: function(config, type, option)
700                 {
701                         return this._foreach(config, type).then(function(sections) {
702                                 for (var s in sections)
703                                 {
704                                         var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
705
706                                         if (typeof(val) != 'undefined')
707                                                 return val;
708                                 }
709
710                                 return undefined;
711                         });
712                 },
713
714                 section: _luci2.rpc.declare({
715                         object: 'uci',
716                         method: 'add',
717                         params: [ 'config', 'type', 'name', 'values' ],
718                         expect: { section: '' }
719                 }),
720
721                 _set: _luci2.rpc.declare({
722                         object: 'uci',
723                         method: 'set',
724                         params: [ 'config', 'section', 'values' ]
725                 }),
726
727                 set: function(config, section, option, value)
728                 {
729                         if (typeof(value) == 'undefined' && typeof(option) == 'string')
730                                 return this.section(config, section, option); /* option -> type */
731                         else if ($.isPlainObject(option))
732                                 return this._set(config, section, option); /* option -> values */
733
734                         var values = { };
735                             values[option] = value;
736
737                         return this._set(config, section, values);
738                 },
739
740                 order: _luci2.rpc.declare({
741                         object: 'uci',
742                         method: 'order',
743                         params: [ 'config', 'sections' ]
744                 })
745         };
746
747         this.network = {
748                 listNetworkNames: function() {
749                         return _luci2.rpc.list('network.interface.*').then(function(list) {
750                                 var names = [ ];
751                                 for (var name in list)
752                                         if (name != 'network.interface.loopback')
753                                                 names.push(name.substring(18));
754                                 names.sort();
755                                 return names;
756                         });
757                 },
758
759                 listDeviceNames: _luci2.rpc.declare({
760                         object: 'network.device',
761                         method: 'status',
762                         expect: { '': { } },
763                         filter: function(data) {
764                                 var names = [ ];
765                                 for (var name in data)
766                                         if (name != 'lo')
767                                                 names.push(name);
768                                 names.sort();
769                                 return names;
770                         }
771                 }),
772
773                 getNetworkStatus: function()
774                 {
775                         var nets = [ ];
776                         var devs = { };
777
778                         return this.listNetworkNames().then(function(names) {
779                                 _luci2.rpc.batch();
780
781                                 for (var i = 0; i < names.length; i++)
782                                         _luci2.network.getInterfaceStatus(names[i]);
783
784                                 return _luci2.rpc.flush();
785                         }).then(function(networks) {
786                                 for (var i = 0; i < networks.length; i++)
787                                 {
788                                         var net = nets[i] = networks[i];
789                                         var dev = net.l3_device || net.l2_device;
790                                         if (dev)
791                                                 net.device = devs[dev] || (devs[dev] = { });
792                                 }
793
794                                 _luci2.rpc.batch();
795
796                                 for (var dev in devs)
797                                         _luci2.network.getDeviceStatus(dev);
798
799                                 return _luci2.rpc.flush();
800                         }).then(function(devices) {
801                                 _luci2.rpc.batch();
802
803                                 for (var i = 0; i < devices.length; i++)
804                                 {
805                                         var brm = devices[i]['bridge-members'];
806                                         delete devices[i]['bridge-members'];
807
808                                         $.extend(devs[devices[i]['device']], devices[i]);
809
810                                         if (!brm)
811                                                 continue;
812
813                                         devs[devices[i]['device']].subdevices = [ ];
814
815                                         for (var j = 0; j < brm.length; j++)
816                                         {
817                                                 if (!devs[brm[j]])
818                                                 {
819                                                         devs[brm[j]] = { };
820                                                         _luci2.network.getDeviceStatus(brm[j]);
821                                                 }
822
823                                                 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
824                                         }
825                                 }
826
827                                 return _luci2.rpc.flush();
828                         }).then(function(subdevices) {
829                                 for (var i = 0; i < subdevices.length; i++)
830                                         $.extend(devs[subdevices[i]['device']], subdevices[i]);
831
832                                 _luci2.rpc.batch();
833
834                                 for (var dev in devs)
835                                         _luci2.wireless.getDeviceStatus(dev);
836
837                                 return _luci2.rpc.flush();
838                         }).then(function(wifidevices) {
839                                 for (var i = 0; i < wifidevices.length; i++)
840                                         if (wifidevices[i])
841                                                 devs[wifidevices[i]['device']].wireless = wifidevices[i];
842
843                                 nets.sort(function(a, b) {
844                                         if (a['interface'] < b['interface'])
845                                                 return -1;
846                                         else if (a['interface'] > b['interface'])
847                                                 return 1;
848                                         else
849                                                 return 0;
850                                 });
851
852                                 return nets;
853                         });
854                 },
855
856                 findWanInterfaces: function(cb)
857                 {
858                         return this.listNetworkNames().then(function(names) {
859                                 _luci2.rpc.batch();
860
861                                 for (var i = 0; i < names.length; i++)
862                                         _luci2.network.getInterfaceStatus(names[i]);
863
864                                 return _luci2.rpc.flush();
865                         }).then(function(interfaces) {
866                                 var rv = [ undefined, undefined ];
867
868                                 for (var i = 0; i < interfaces.length; i++)
869                                 {
870                                         if (!interfaces[i].route)
871                                                 continue;
872
873                                         for (var j = 0; j < interfaces[i].route.length; j++)
874                                         {
875                                                 var rt = interfaces[i].route[j];
876
877                                                 if (typeof(rt.table) != 'undefined')
878                                                         continue;
879
880                                                 if (rt.target == '0.0.0.0' && rt.mask == 0)
881                                                         rv[0] = interfaces[i];
882                                                 else if (rt.target == '::' && rt.mask == 0)
883                                                         rv[1] = interfaces[i];
884                                         }
885                                 }
886
887                                 return rv;
888                         });
889                 },
890
891                 getDHCPLeases: _luci2.rpc.declare({
892                         object: 'luci2.network',
893                         method: 'dhcp_leases',
894                         expect: { leases: [ ] }
895                 }),
896
897                 getDHCPv6Leases: _luci2.rpc.declare({
898                         object: 'luci2.network',
899                         method: 'dhcp6_leases',
900                         expect: { leases: [ ] }
901                 }),
902
903                 getRoutes: _luci2.rpc.declare({
904                         object: 'luci2.network',
905                         method: 'routes',
906                         expect: { routes: [ ] }
907                 }),
908
909                 getIPv6Routes: _luci2.rpc.declare({
910                         object: 'luci2.network',
911                         method: 'routes',
912                         expect: { routes: [ ] }
913                 }),
914
915                 getARPTable: _luci2.rpc.declare({
916                         object: 'luci2.network',
917                         method: 'arp_table',
918                         expect: { entries: [ ] }
919                 }),
920
921                 getInterfaceStatus: _luci2.rpc.declare({
922                         object: 'network.interface',
923                         method: 'status',
924                         params: [ 'interface' ],
925                         expect: { '': { } },
926                         filter: function(data, params) {
927                                 data['interface'] = params['interface'];
928                                 data['l2_device'] = data['device'];
929                                 delete data['device'];
930                                 return data;
931                         }
932                 }),
933
934                 getDeviceStatus: _luci2.rpc.declare({
935                         object: 'network.device',
936                         method: 'status',
937                         params: [ 'name' ],
938                         expect: { '': { } },
939                         filter: function(data, params) {
940                                 data['device'] = params['name'];
941                                 return data;
942                         }
943                 }),
944
945                 getConntrackCount: _luci2.rpc.declare({
946                         object: 'luci2.network',
947                         method: 'conntrack_count',
948                         expect: { '': { count: 0, limit: 0 } }
949                 }),
950
951                 listSwitchNames: _luci2.rpc.declare({
952                         object: 'luci2.network',
953                         method: 'switch_list',
954                         expect: { switches: [ ] }
955                 }),
956
957                 getSwitchInfo: _luci2.rpc.declare({
958                         object: 'luci2.network',
959                         method: 'switch_info',
960                         params: [ 'switch' ],
961                         expect: { info: { } },
962                         filter: function(data, params) {
963                                 data['attrs']      = data['switch'];
964                                 data['vlan_attrs'] = data['vlan'];
965                                 data['port_attrs'] = data['port'];
966                                 data['switch']     = params['switch'];
967
968                                 delete data.vlan;
969                                 delete data.port;
970
971                                 return data;
972                         }
973                 }),
974
975                 getSwitchStatus: _luci2.rpc.declare({
976                         object: 'luci2.network',
977                         method: 'switch_status',
978                         params: [ 'switch' ],
979                         expect: { ports: [ ] }
980                 }),
981
982
983                 runPing: _luci2.rpc.declare({
984                         object: 'luci2.network',
985                         method: 'ping',
986                         params: [ 'data' ],
987                         expect: { '': { code: -1 } }
988                 }),
989
990                 runPing6: _luci2.rpc.declare({
991                         object: 'luci2.network',
992                         method: 'ping6',
993                         params: [ 'data' ],
994                         expect: { '': { code: -1 } }
995                 }),
996
997                 runTraceroute: _luci2.rpc.declare({
998                         object: 'luci2.network',
999                         method: 'traceroute',
1000                         params: [ 'data' ],
1001                         expect: { '': { code: -1 } }
1002                 }),
1003
1004                 runTraceroute6: _luci2.rpc.declare({
1005                         object: 'luci2.network',
1006                         method: 'traceroute6',
1007                         params: [ 'data' ],
1008                         expect: { '': { code: -1 } }
1009                 }),
1010
1011                 runNslookup: _luci2.rpc.declare({
1012                         object: 'luci2.network',
1013                         method: 'nslookup',
1014                         params: [ 'data' ],
1015                         expect: { '': { code: -1 } }
1016                 }),
1017
1018
1019                 setUp: _luci2.rpc.declare({
1020                         object: 'luci2.network',
1021                         method: 'ifup',
1022                         params: [ 'data' ],
1023                         expect: { '': { code: -1 } }
1024                 }),
1025
1026                 setDown: _luci2.rpc.declare({
1027                         object: 'luci2.network',
1028                         method: 'ifdown',
1029                         params: [ 'data' ],
1030                         expect: { '': { code: -1 } }
1031                 })
1032         };
1033
1034         this.wireless = {
1035                 listDeviceNames: _luci2.rpc.declare({
1036                         object: 'iwinfo',
1037                         method: 'devices',
1038                         expect: { 'devices': [ ] },
1039                         filter: function(data) {
1040                                 data.sort();
1041                                 return data;
1042                         }
1043                 }),
1044
1045                 getDeviceStatus: _luci2.rpc.declare({
1046                         object: 'iwinfo',
1047                         method: 'info',
1048                         params: [ 'device' ],
1049                         expect: { '': { } },
1050                         filter: function(data, params) {
1051                                 if (!$.isEmptyObject(data))
1052                                 {
1053                                         data['device'] = params['device'];
1054                                         return data;
1055                                 }
1056                                 return undefined;
1057                         }
1058                 }),
1059
1060                 getAssocList: _luci2.rpc.declare({
1061                         object: 'iwinfo',
1062                         method: 'assoclist',
1063                         params: [ 'device' ],
1064                         expect: { results: [ ] },
1065                         filter: function(data, params) {
1066                                 for (var i = 0; i < data.length; i++)
1067                                         data[i]['device'] = params['device'];
1068
1069                                 data.sort(function(a, b) {
1070                                         if (a.bssid < b.bssid)
1071                                                 return -1;
1072                                         else if (a.bssid > b.bssid)
1073                                                 return 1;
1074                                         else
1075                                                 return 0;
1076                                 });
1077
1078                                 return data;
1079                         }
1080                 }),
1081
1082                 getWirelessStatus: function() {
1083                         return this.listDeviceNames().then(function(names) {
1084                                 _luci2.rpc.batch();
1085
1086                                 for (var i = 0; i < names.length; i++)
1087                                         _luci2.wireless.getDeviceStatus(names[i]);
1088
1089                                 return _luci2.rpc.flush();
1090                         }).then(function(networks) {
1091                                 var rv = { };
1092
1093                                 var phy_attrs = [
1094                                         'country', 'channel', 'frequency', 'frequency_offset',
1095                                         'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1096                                 ];
1097
1098                                 var net_attrs = [
1099                                         'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1100                                         'signal', 'noise', 'bitrate', 'encryption'
1101                                 ];
1102
1103                                 for (var i = 0; i < networks.length; i++)
1104                                 {
1105                                         var phy = rv[networks[i].phy] || (
1106                                                 rv[networks[i].phy] = { networks: [ ] }
1107                                         );
1108
1109                                         var net = {
1110                                                 device: networks[i].device
1111                                         };
1112
1113                                         for (var j = 0; j < phy_attrs.length; j++)
1114                                                 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1115
1116                                         for (var j = 0; j < net_attrs.length; j++)
1117                                                 net[net_attrs[j]] = networks[i][net_attrs[j]];
1118
1119                                         phy.networks.push(net);
1120                                 }
1121
1122                                 return rv;
1123                         });
1124                 },
1125
1126                 getAssocLists: function()
1127                 {
1128                         return this.listDeviceNames().then(function(names) {
1129                                 _luci2.rpc.batch();
1130
1131                                 for (var i = 0; i < names.length; i++)
1132                                         _luci2.wireless.getAssocList(names[i]);
1133
1134                                 return _luci2.rpc.flush();
1135                         }).then(function(assoclists) {
1136                                 var rv = [ ];
1137
1138                                 for (var i = 0; i < assoclists.length; i++)
1139                                         for (var j = 0; j < assoclists[i].length; j++)
1140                                                 rv.push(assoclists[i][j]);
1141
1142                                 return rv;
1143                         });
1144                 },
1145
1146                 formatEncryption: function(enc)
1147                 {
1148                         var format_list = function(l, s)
1149                         {
1150                                 var rv = [ ];
1151                                 for (var i = 0; i < l.length; i++)
1152                                         rv.push(l[i].toUpperCase());
1153                                 return rv.join(s ? s : ', ');
1154                         }
1155
1156                         if (!enc || !enc.enabled)
1157                                 return _luci2.tr('None');
1158
1159                         if (enc.wep)
1160                         {
1161                                 if (enc.wep.length == 2)
1162                                         return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1163                                 else if (enc.wep[0] == 'shared')
1164                                         return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1165                                 else
1166                                         return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1167                         }
1168                         else if (enc.wpa)
1169                         {
1170                                 if (enc.wpa.length == 2)
1171                                         return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1172                                                 format_list(enc.authentication, '/'),
1173                                                 format_list(enc.ciphers, ', ')
1174                                         );
1175                                 else if (enc.wpa[0] == 2)
1176                                         return 'WPA2 %s (%s)'.format(
1177                                                 format_list(enc.authentication, '/'),
1178                                                 format_list(enc.ciphers, ', ')
1179                                         );
1180                                 else
1181                                         return 'WPA %s (%s)'.format(
1182                                                 format_list(enc.authentication, '/'),
1183                                                 format_list(enc.ciphers, ', ')
1184                                         );
1185                         }
1186
1187                         return _luci2.tr('Unknown');
1188                 }
1189         };
1190
1191         this.system = {
1192                 getSystemInfo: _luci2.rpc.declare({
1193                         object: 'system',
1194                         method: 'info',
1195                         expect: { '': { } }
1196                 }),
1197
1198                 getBoardInfo: _luci2.rpc.declare({
1199                         object: 'system',
1200                         method: 'board',
1201                         expect: { '': { } }
1202                 }),
1203
1204                 getDiskInfo: _luci2.rpc.declare({
1205                         object: 'luci2.system',
1206                         method: 'diskfree',
1207                         expect: { '': { } }
1208                 }),
1209
1210                 getInfo: function(cb)
1211                 {
1212                         _luci2.rpc.batch();
1213
1214                         this.getSystemInfo();
1215                         this.getBoardInfo();
1216                         this.getDiskInfo();
1217
1218                         return _luci2.rpc.flush().then(function(info) {
1219                                 var rv = { };
1220
1221                                 $.extend(rv, info[0]);
1222                                 $.extend(rv, info[1]);
1223                                 $.extend(rv, info[2]);
1224
1225                                 return rv;
1226                         });
1227                 },
1228
1229                 getProcessList: _luci2.rpc.declare({
1230                         object: 'luci2.system',
1231                         method: 'process_list',
1232                         expect: { processes: [ ] },
1233                         filter: function(data) {
1234                                 data.sort(function(a, b) { return a.pid - b.pid });
1235                                 return data;
1236                         }
1237                 }),
1238
1239                 getSystemLog: _luci2.rpc.declare({
1240                         object: 'luci2.system',
1241                         method: 'syslog',
1242                         expect: { log: '' }
1243                 }),
1244
1245                 getKernelLog: _luci2.rpc.declare({
1246                         object: 'luci2.system',
1247                         method: 'dmesg',
1248                         expect: { log: '' }
1249                 }),
1250
1251                 getZoneInfo: function(cb)
1252                 {
1253                         return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1254                 },
1255
1256                 sendSignal: _luci2.rpc.declare({
1257                         object: 'luci2.system',
1258                         method: 'process_signal',
1259                         params: [ 'pid', 'signal' ],
1260                         filter: function(data) {
1261                                 return (data == 0);
1262                         }
1263                 }),
1264
1265                 initList: _luci2.rpc.declare({
1266                         object: 'luci2.system',
1267                         method: 'init_list',
1268                         expect: { initscripts: [ ] },
1269                         filter: function(data) {
1270                                 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1271                                 return data;
1272                         }
1273                 }),
1274
1275                 initEnabled: function(init, cb)
1276                 {
1277                         return this.initList().then(function(list) {
1278                                 for (var i = 0; i < list.length; i++)
1279                                         if (list[i].name == init)
1280                                                 return !!list[i].enabled;
1281
1282                                 return false;
1283                         });
1284                 },
1285
1286                 initRun: _luci2.rpc.declare({
1287                         object: 'luci2.system',
1288                         method: 'init_action',
1289                         params: [ 'name', 'action' ],
1290                         filter: function(data) {
1291                                 return (data == 0);
1292                         }
1293                 }),
1294
1295                 initStart:   function(init, cb) { return _luci2.system.initRun(init, 'start',   cb) },
1296                 initStop:    function(init, cb) { return _luci2.system.initRun(init, 'stop',    cb) },
1297                 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1298                 initReload:  function(init, cb) { return _luci2.system.initRun(init, 'reload',  cb) },
1299                 initEnable:  function(init, cb) { return _luci2.system.initRun(init, 'enable',  cb) },
1300                 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1301
1302
1303                 getRcLocal: _luci2.rpc.declare({
1304                         object: 'luci2.system',
1305                         method: 'rclocal_get',
1306                         expect: { data: '' }
1307                 }),
1308
1309                 setRcLocal: _luci2.rpc.declare({
1310                         object: 'luci2.system',
1311                         method: 'rclocal_set',
1312                         params: [ 'data' ]
1313                 }),
1314
1315
1316                 getCrontab: _luci2.rpc.declare({
1317                         object: 'luci2.system',
1318                         method: 'crontab_get',
1319                         expect: { data: '' }
1320                 }),
1321
1322                 setCrontab: _luci2.rpc.declare({
1323                         object: 'luci2.system',
1324                         method: 'crontab_set',
1325                         params: [ 'data' ]
1326                 }),
1327
1328
1329                 getSSHKeys: _luci2.rpc.declare({
1330                         object: 'luci2.system',
1331                         method: 'sshkeys_get',
1332                         expect: { keys: [ ] }
1333                 }),
1334
1335                 setSSHKeys: _luci2.rpc.declare({
1336                         object: 'luci2.system',
1337                         method: 'sshkeys_set',
1338                         params: [ 'keys' ]
1339                 }),
1340
1341
1342                 setPassword: _luci2.rpc.declare({
1343                         object: 'luci2.system',
1344                         method: 'password_set',
1345                         params: [ 'user', 'password' ]
1346                 }),
1347
1348
1349                 listLEDs: _luci2.rpc.declare({
1350                         object: 'luci2.system',
1351                         method: 'led_list',
1352                         expect: { leds: [ ] }
1353                 }),
1354
1355                 listUSBDevices: _luci2.rpc.declare({
1356                         object: 'luci2.system',
1357                         method: 'usb_list',
1358                         expect: { devices: [ ] }
1359                 }),
1360
1361
1362                 testUpgrade: _luci2.rpc.declare({
1363                         object: 'luci2.system',
1364                         method: 'upgrade_test',
1365                         expect: { '': { } }
1366                 }),
1367
1368                 startUpgrade: _luci2.rpc.declare({
1369                         object: 'luci2.system',
1370                         method: 'upgrade_start',
1371                         params: [ 'keep' ]
1372                 }),
1373
1374                 cleanUpgrade: _luci2.rpc.declare({
1375                         object: 'luci2.system',
1376                         method: 'upgrade_clean'
1377                 }),
1378
1379
1380                 restoreBackup: _luci2.rpc.declare({
1381                         object: 'luci2.system',
1382                         method: 'backup_restore'
1383                 }),
1384
1385                 cleanBackup: _luci2.rpc.declare({
1386                         object: 'luci2.system',
1387                         method: 'backup_clean'
1388                 }),
1389
1390
1391                 getBackupConfig: _luci2.rpc.declare({
1392                         object: 'luci2.system',
1393                         method: 'backup_config_get',
1394                         expect: { config: '' }
1395                 }),
1396
1397                 setBackupConfig: _luci2.rpc.declare({
1398                         object: 'luci2.system',
1399                         method: 'backup_config_set',
1400                         params: [ 'data' ]
1401                 }),
1402
1403
1404                 listBackup: _luci2.rpc.declare({
1405                         object: 'luci2.system',
1406                         method: 'backup_list',
1407                         expect: { files: [ ] }
1408                 }),
1409
1410
1411                 testReset: _luci2.rpc.declare({
1412                         object: 'luci2.system',
1413                         method: 'reset_test',
1414                         expect: { supported: false }
1415                 }),
1416
1417                 startReset: _luci2.rpc.declare({
1418                         object: 'luci2.system',
1419                         method: 'reset_start'
1420                 }),
1421
1422
1423                 performReboot: _luci2.rpc.declare({
1424                         object: 'luci2.system',
1425                         method: 'reboot'
1426                 })
1427         };
1428
1429         this.opkg = {
1430                 updateLists: _luci2.rpc.declare({
1431                         object: 'luci2.opkg',
1432                         method: 'update',
1433                         expect: { '': { } }
1434                 }),
1435
1436                 _allPackages: _luci2.rpc.declare({
1437                         object: 'luci2.opkg',
1438                         method: 'list',
1439                         params: [ 'offset', 'limit', 'pattern' ],
1440                         expect: { '': { } }
1441                 }),
1442
1443                 _installedPackages: _luci2.rpc.declare({
1444                         object: 'luci2.opkg',
1445                         method: 'list_installed',
1446                         params: [ 'offset', 'limit', 'pattern' ],
1447                         expect: { '': { } }
1448                 }),
1449
1450                 _findPackages: _luci2.rpc.declare({
1451                         object: 'luci2.opkg',
1452                         method: 'find',
1453                         params: [ 'offset', 'limit', 'pattern' ],
1454                         expect: { '': { } }
1455                 }),
1456
1457                 _fetchPackages: function(action, offset, limit, pattern)
1458                 {
1459                         var packages = [ ];
1460
1461                         return action(offset, limit, pattern).then(function(list) {
1462                                 if (!list.total || !list.packages)
1463                                         return { length: 0, total: 0 };
1464
1465                                 packages.push.apply(packages, list.packages);
1466                                 packages.total = list.total;
1467
1468                                 if (limit <= 0)
1469                                         limit = list.total;
1470
1471                                 if (packages.length >= limit)
1472                                         return packages;
1473
1474                                 _luci2.rpc.batch();
1475
1476                                 for (var i = offset + packages.length; i < limit; i += 100)
1477                                         action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1478
1479                                 return _luci2.rpc.flush();
1480                         }).then(function(lists) {
1481                                 for (var i = 0; i < lists.length; i++)
1482                                 {
1483                                         if (!lists[i].total || !lists[i].packages)
1484                                                 continue;
1485
1486                                         packages.push.apply(packages, lists[i].packages);
1487                                         packages.total = lists[i].total;
1488                                 }
1489
1490                                 return packages;
1491                         });
1492                 },
1493
1494                 listPackages: function(offset, limit, pattern)
1495                 {
1496                         return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1497                 },
1498
1499                 installedPackages: function(offset, limit, pattern)
1500                 {
1501                         return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1502                 },
1503
1504                 findPackages: function(offset, limit, pattern)
1505                 {
1506                         return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1507                 },
1508
1509                 installPackage: _luci2.rpc.declare({
1510                         object: 'luci2.opkg',
1511                         method: 'install',
1512                         params: [ 'package' ],
1513                         expect: { '': { } }
1514                 }),
1515
1516                 removePackage: _luci2.rpc.declare({
1517                         object: 'luci2.opkg',
1518                         method: 'remove',
1519                         params: [ 'package' ],
1520                         expect: { '': { } }
1521                 }),
1522
1523                 getConfig: _luci2.rpc.declare({
1524                         object: 'luci2.opkg',
1525                         method: 'config_get',
1526                         expect: { config: '' }
1527                 }),
1528
1529                 setConfig: _luci2.rpc.declare({
1530                         object: 'luci2.opkg',
1531                         method: 'config_set',
1532                         params: [ 'data' ]
1533                 })
1534         };
1535
1536         this.session = {
1537
1538                 login: _luci2.rpc.declare({
1539                         object: 'session',
1540                         method: 'login',
1541                         params: [ 'username', 'password' ],
1542                         expect: { '': { } }
1543                 }),
1544
1545                 access: _luci2.rpc.declare({
1546                         object: 'session',
1547                         method: 'access',
1548                         params: [ 'scope', 'object', 'function' ],
1549                         expect: { access: false }
1550                 }),
1551
1552                 isAlive: function()
1553                 {
1554                         return _luci2.session.access('ubus', 'session', 'access');
1555                 },
1556
1557                 startHeartbeat: function()
1558                 {
1559                         this._hearbeatInterval = window.setInterval(function() {
1560                                 _luci2.session.isAlive().then(function(alive) {
1561                                         if (!alive)
1562                                         {
1563                                                 _luci2.session.stopHeartbeat();
1564                                                 _luci2.ui.login(true);
1565                                         }
1566
1567                                 });
1568                         }, _luci2.globals.timeout * 2);
1569                 },
1570
1571                 stopHeartbeat: function()
1572                 {
1573                         if (typeof(this._hearbeatInterval) != 'undefined')
1574                         {
1575                                 window.clearInterval(this._hearbeatInterval);
1576                                 delete this._hearbeatInterval;
1577                         }
1578                 }
1579         };
1580
1581         this.ui = {
1582
1583                 saveScrollTop: function()
1584                 {
1585                         this._scroll_top = $(document).scrollTop();
1586                 },
1587
1588                 restoreScrollTop: function()
1589                 {
1590                         if (typeof(this._scroll_top) == 'undefined')
1591                                 return;
1592
1593                         $(document).scrollTop(this._scroll_top);
1594
1595                         delete this._scroll_top;
1596                 },
1597
1598                 loading: function(enable)
1599                 {
1600                         var win = $(window);
1601                         var body = $('body');
1602
1603                         var state = _luci2.ui._loading || (_luci2.ui._loading = {
1604                                 modal: $('<div />')
1605                                         .addClass('cbi-modal-loader')
1606                                         .append($('<div />').text(_luci2.tr('Loading data...')))
1607                                         .appendTo(body)
1608                         });
1609
1610                         if (enable)
1611                         {
1612                                 body.css('overflow', 'hidden');
1613                                 body.css('padding', 0);
1614                                 body.css('width', win.width());
1615                                 body.css('height', win.height());
1616                                 state.modal.css('width', win.width());
1617                                 state.modal.css('height', win.height());
1618                                 state.modal.show();
1619                         }
1620                         else
1621                         {
1622                                 state.modal.hide();
1623                                 body.css('overflow', '');
1624                                 body.css('padding', '');
1625                                 body.css('width', '');
1626                                 body.css('height', '');
1627                         }
1628                 },
1629
1630                 dialog: function(title, content, options)
1631                 {
1632                         var win = $(window);
1633                         var body = $('body');
1634
1635                         var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1636                                 dialog: $('<div />')
1637                                         .addClass('cbi-modal-dialog')
1638                                         .append($('<div />')
1639                                                 .append($('<div />')
1640                                                         .addClass('cbi-modal-dialog-header'))
1641                                                 .append($('<div />')
1642                                                         .addClass('cbi-modal-dialog-body'))
1643                                                 .append($('<div />')
1644                                                         .addClass('cbi-modal-dialog-footer')
1645                                                         .append($('<button />')
1646                                                                 .addClass('cbi-button')
1647                                                                 .text(_luci2.tr('Close'))
1648                                                                 .click(function() {
1649                                                                         $('body')
1650                                                                                 .css('overflow', '')
1651                                                                                 .css('padding', '')
1652                                                                                 .css('width', '')
1653                                                                                 .css('height', '');
1654
1655                                                                         $(this).parent().parent().parent().hide();
1656                                                                 }))))
1657                                         .appendTo(body)
1658                         });
1659
1660                         if (typeof(options) != 'object')
1661                                 options = { };
1662
1663                         if (title === false)
1664                         {
1665                                 body
1666                                         .css('overflow', '')
1667                                         .css('padding', '')
1668                                         .css('width', '')
1669                                         .css('height', '');
1670
1671                                 state.dialog.hide();
1672
1673                                 return;
1674                         }
1675
1676                         var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1677                         var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1678
1679                         ftr.empty();
1680
1681                         if (options.style == 'confirm')
1682                         {
1683                                 ftr.append($('<button />')
1684                                         .addClass('cbi-button')
1685                                         .text(_luci2.tr('Ok'))
1686                                         .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1687
1688                                 ftr.append($('<button />')
1689                                         .addClass('cbi-button')
1690                                         .text(_luci2.tr('Cancel'))
1691                                         .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1692                         }
1693                         else if (options.style == 'close')
1694                         {
1695                                 ftr.append($('<button />')
1696                                         .addClass('cbi-button')
1697                                         .text(_luci2.tr('Close'))
1698                                         .click(options.close || function() { _luci2.ui.dialog(false) }));
1699                         }
1700                         else if (options.style == 'wait')
1701                         {
1702                                 ftr.append($('<button />')
1703                                         .addClass('cbi-button')
1704                                         .text(_luci2.tr('Close'))
1705                                         .attr('disabled', true));
1706                         }
1707
1708                         state.dialog.find('div.cbi-modal-dialog-header').text(title);
1709                         state.dialog.show();
1710
1711                         cnt
1712                                 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1713                                 .empty()
1714                                 .append(content);
1715
1716                         state.dialog.children()
1717                                 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1718
1719                         body.css('overflow', 'hidden');
1720                         body.css('padding', 0);
1721                         body.css('width', win.width());
1722                         body.css('height', win.height());
1723                         state.dialog.css('width', win.width());
1724                         state.dialog.css('height', win.height());
1725                 },
1726
1727                 upload: function(title, content, options)
1728                 {
1729                         var state = _luci2.ui._upload || (_luci2.ui._upload = {
1730                                 form: $('<form />')
1731                                         .attr('method', 'post')
1732                                         .attr('action', '/cgi-bin/luci-upload')
1733                                         .attr('enctype', 'multipart/form-data')
1734                                         .attr('target', 'cbi-fileupload-frame')
1735                                         .append($('<p />'))
1736                                         .append($('<input />')
1737                                                 .attr('type', 'hidden')
1738                                                 .attr('name', 'sessionid'))
1739                                         .append($('<input />')
1740                                                 .attr('type', 'hidden')
1741                                                 .attr('name', 'filename'))
1742                                         .append($('<input />')
1743                                                 .attr('type', 'file')
1744                                                 .attr('name', 'filedata')
1745                                                 .addClass('cbi-input-file'))
1746                                         .append($('<div />')
1747                                                 .css('width', '100%')
1748                                                 .addClass('progressbar')
1749                                                 .addClass('intermediate')
1750                                                 .append($('<div />')
1751                                                         .css('width', '100%')))
1752                                         .append($('<iframe />')
1753                                                 .attr('name', 'cbi-fileupload-frame')
1754                                                 .css('width', '1px')
1755                                                 .css('height', '1px')
1756                                                 .css('visibility', 'hidden')),
1757
1758                                 finish_cb: function(ev) {
1759                                         $(this).off('load');
1760
1761                                         var body = (this.contentDocument || this.contentWindow.document).body;
1762                                         if (body.firstChild.tagName.toLowerCase() == 'pre')
1763                                                 body = body.firstChild;
1764
1765                                         var json;
1766                                         try {
1767                                                 json = $.parseJSON(body.innerHTML);
1768                                         } catch(e) {
1769                                                 json = {
1770                                                         message: _luci2.tr('Invalid server response received'),
1771                                                         error: [ -1, _luci2.tr('Invalid data') ]
1772                                                 };
1773                                         };
1774
1775                                         if (json.error)
1776                                         {
1777                                                 L.ui.dialog(L.tr('File upload'), [
1778                                                         $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1779                                                         $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1780                                                         $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1781                                                 ], { style: 'close' });
1782                                         }
1783                                         else if (typeof(state.success_cb) == 'function')
1784                                         {
1785                                                 state.success_cb(json);
1786                                         }
1787                                 },
1788
1789                                 confirm_cb: function() {
1790                                         var f = state.form.find('.cbi-input-file');
1791                                         var b = state.form.find('.progressbar');
1792                                         var p = state.form.find('p');
1793
1794                                         if (!f.val())
1795                                                 return;
1796
1797                                         state.form.find('iframe').on('load', state.finish_cb);
1798                                         state.form.submit();
1799
1800                                         f.hide();
1801                                         b.show();
1802                                         p.text(_luci2.tr('File upload in progress â€¦'));
1803
1804                                         state.form.parent().parent().find('button').prop('disabled', true);
1805                                 }
1806                         });
1807
1808                         state.form.find('.progressbar').hide();
1809                         state.form.find('.cbi-input-file').val('').show();
1810                         state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1811
1812                         state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1813                         state.form.find('[name=filename]').val(options.filename);
1814
1815                         state.success_cb = options.success;
1816
1817                         _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1818                                 style: 'confirm',
1819                                 confirm: state.confirm_cb
1820                         });
1821                 },
1822
1823                 reconnect: function()
1824                 {
1825                         var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1826                         var ports     = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1827                         var address   = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1828                         var images    = $();
1829                         var interval, timeout;
1830
1831                         _luci2.ui.dialog(
1832                                 _luci2.tr('Waiting for device'), [
1833                                         $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring â€¦')),
1834                                         $('<div />')
1835                                                 .css('width', '100%')
1836                                                 .addClass('progressbar')
1837                                                 .addClass('intermediate')
1838                                                 .append($('<div />')
1839                                                         .css('width', '100%'))
1840                                 ], { style: 'wait' }
1841                         );
1842
1843                         for (var i = 0; i < protocols.length; i++)
1844                                 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1845
1846                         //_luci2.network.getNetworkStatus(function(s) {
1847                         //      for (var i = 0; i < protocols.length; i++)
1848                         //      {
1849                         //              for (var j = 0; j < s.length; j++)
1850                         //              {
1851                         //                      for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1852                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1853                         //
1854                         //                      for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1855                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1856                         //              }
1857                         //      }
1858                         //}).then(function() {
1859                                 images.on('load', function() {
1860                                         var url = this.getAttribute('url');
1861                                         _luci2.session.isAlive().then(function(access) {
1862                                                 if (access)
1863                                                 {
1864                                                         window.clearTimeout(timeout);
1865                                                         window.clearInterval(interval);
1866                                                         _luci2.ui.dialog(false);
1867                                                         images = null;
1868                                                 }
1869                                                 else
1870                                                 {
1871                                                         location.href = url;
1872                                                 }
1873                                         });
1874                                 });
1875
1876                                 interval = window.setInterval(function() {
1877                                         images.each(function() {
1878                                                 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1879                                         });
1880                                 }, 5000);
1881
1882                                 timeout = window.setTimeout(function() {
1883                                         window.clearInterval(interval);
1884                                         images.off('load');
1885
1886                                         _luci2.ui.dialog(
1887                                                 _luci2.tr('Device not responding'),
1888                                                 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1889                                                 { style: 'close' }
1890                                         );
1891                                 }, 180000);
1892                         //});
1893                 },
1894
1895                 login: function(invalid)
1896                 {
1897                         var state = _luci2.ui._login || (_luci2.ui._login = {
1898                                 form: $('<form />')
1899                                         .attr('target', '')
1900                                         .attr('method', 'post')
1901                                         .append($('<p />')
1902                                                 .addClass('alert-message')
1903                                                 .text(_luci2.tr('Wrong username or password given!')))
1904                                         .append($('<p />')
1905                                                 .append($('<label />')
1906                                                         .text(_luci2.tr('Username'))
1907                                                         .append($('<br />'))
1908                                                         .append($('<input />')
1909                                                                 .attr('type', 'text')
1910                                                                 .attr('name', 'username')
1911                                                                 .attr('value', 'root')
1912                                                                 .addClass('cbi-input-text')
1913                                                                 .keypress(function(ev) {
1914                                                                         if (ev.which == 10 || ev.which == 13)
1915                                                                                 state.confirm_cb();
1916                                                                 }))))
1917                                         .append($('<p />')
1918                                                 .append($('<label />')
1919                                                         .text(_luci2.tr('Password'))
1920                                                         .append($('<br />'))
1921                                                         .append($('<input />')
1922                                                                 .attr('type', 'password')
1923                                                                 .attr('name', 'password')
1924                                                                 .addClass('cbi-input-password')
1925                                                                 .keypress(function(ev) {
1926                                                                         if (ev.which == 10 || ev.which == 13)
1927                                                                                 state.confirm_cb();
1928                                                                 }))))
1929                                         .append($('<p />')
1930                                                 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1931
1932                                 response_cb: function(response) {
1933                                         if (!response.ubus_rpc_session)
1934                                         {
1935                                                 _luci2.ui.login(true);
1936                                         }
1937                                         else
1938                                         {
1939                                                 _luci2.globals.sid = response.ubus_rpc_session;
1940                                                 _luci2.setHash('id', _luci2.globals.sid);
1941                                                 _luci2.session.startHeartbeat();
1942                                                 _luci2.ui.dialog(false);
1943                                                 state.deferred.resolve();
1944                                         }
1945                                 },
1946
1947                                 confirm_cb: function() {
1948                                         var u = state.form.find('[name=username]').val();
1949                                         var p = state.form.find('[name=password]').val();
1950
1951                                         if (!u)
1952                                                 return;
1953
1954                                         _luci2.ui.dialog(
1955                                                 _luci2.tr('Logging in'), [
1956                                                         $('<p />').text(_luci2.tr('Log in in progress â€¦')),
1957                                                         $('<div />')
1958                                                                 .css('width', '100%')
1959                                                                 .addClass('progressbar')
1960                                                                 .addClass('intermediate')
1961                                                                 .append($('<div />')
1962                                                                         .css('width', '100%'))
1963                                                 ], { style: 'wait' }
1964                                         );
1965
1966                                         _luci2.globals.sid = '00000000000000000000000000000000';
1967                                         _luci2.session.login(u, p).then(state.response_cb);
1968                                 }
1969                         });
1970
1971                         if (!state.deferred || state.deferred.state() != 'pending')
1972                                 state.deferred = $.Deferred();
1973
1974                         /* try to find sid from hash */
1975                         var sid = _luci2.getHash('id');
1976                         if (sid && sid.match(/^[a-f0-9]{32}$/))
1977                         {
1978                                 _luci2.globals.sid = sid;
1979                                 _luci2.session.isAlive().then(function(access) {
1980                                         if (access)
1981                                         {
1982                                                 _luci2.session.startHeartbeat();
1983                                                 state.deferred.resolve();
1984                                         }
1985                                         else
1986                                         {
1987                                                 _luci2.setHash('id', undefined);
1988                                                 _luci2.ui.login();
1989                                         }
1990                                 });
1991
1992                                 return state.deferred;
1993                         }
1994
1995                         if (invalid)
1996                                 state.form.find('.alert-message').show();
1997                         else
1998                                 state.form.find('.alert-message').hide();
1999
2000                         _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2001                                 style: 'confirm',
2002                                 confirm: state.confirm_cb
2003                         });
2004
2005                         state.form.find('[name=password]').focus();
2006
2007                         return state.deferred;
2008                 },
2009
2010                 cryptPassword: _luci2.rpc.declare({
2011                         object: 'luci2.ui',
2012                         method: 'crypt',
2013                         params: [ 'data' ],
2014                         expect: { crypt: '' }
2015                 }),
2016
2017
2018                 _acl_merge_scope: function(acl_scope, scope)
2019                 {
2020                         if ($.isArray(scope))
2021                         {
2022                                 for (var i = 0; i < scope.length; i++)
2023                                         acl_scope[scope[i]] = true;
2024                         }
2025                         else if ($.isPlainObject(scope))
2026                         {
2027                                 for (var object_name in scope)
2028                                 {
2029                                         if (!$.isArray(scope[object_name]))
2030                                                 continue;
2031
2032                                         var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2033
2034                                         for (var i = 0; i < scope[object_name].length; i++)
2035                                                 acl_object[scope[object_name][i]] = true;
2036                                 }
2037                         }
2038                 },
2039
2040                 _acl_merge_permission: function(acl_perm, perm)
2041                 {
2042                         if ($.isPlainObject(perm))
2043                         {
2044                                 for (var scope_name in perm)
2045                                 {
2046                                         var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2047                                         this._acl_merge_scope(acl_scope, perm[scope_name]);
2048                                 }
2049                         }
2050                 },
2051
2052                 _acl_merge_group: function(acl_group, group)
2053                 {
2054                         if ($.isPlainObject(group))
2055                         {
2056                                 if (!acl_group.description)
2057                                         acl_group.description = group.description;
2058
2059                                 if (group.read)
2060                                 {
2061                                         var acl_perm = acl_group.read || (acl_group.read = { });
2062                                         this._acl_merge_permission(acl_perm, group.read);
2063                                 }
2064
2065                                 if (group.write)
2066                                 {
2067                                         var acl_perm = acl_group.write || (acl_group.write = { });
2068                                         this._acl_merge_permission(acl_perm, group.write);
2069                                 }
2070                         }
2071                 },
2072
2073                 _acl_merge_tree: function(acl_tree, tree)
2074                 {
2075                         if ($.isPlainObject(tree))
2076                         {
2077                                 for (var group_name in tree)
2078                                 {
2079                                         var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2080                                         this._acl_merge_group(acl_group, tree[group_name]);
2081                                 }
2082                         }
2083                 },
2084
2085                 listAvailableACLs: _luci2.rpc.declare({
2086                         object: 'luci2.ui',
2087                         method: 'acls',
2088                         expect: { acls: [ ] },
2089                         filter: function(trees) {
2090                                 var acl_tree = { };
2091                                 for (var i = 0; i < trees.length; i++)
2092                                         _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2093                                 return acl_tree;
2094                         }
2095                 }),
2096
2097                 renderMainMenu: _luci2.rpc.declare({
2098                         object: 'luci2.ui',
2099                         method: 'menu',
2100                         expect: { menu: { } },
2101                         filter: function(entries) {
2102                                 _luci2.globals.mainMenu = new _luci2.ui.menu();
2103                                 _luci2.globals.mainMenu.entries(entries);
2104
2105                                 $('#mainmenu')
2106                                         .empty()
2107                                         .append(_luci2.globals.mainMenu.render(0, 1));
2108                         }
2109                 }),
2110
2111                 renderViewMenu: function()
2112                 {
2113                         $('#viewmenu')
2114                                 .empty()
2115                                 .append(_luci2.globals.mainMenu.render(2, 900));
2116                 },
2117
2118                 renderView: function(node)
2119                 {
2120                         var name = node.view.split(/\//).join('.');
2121
2122                         if (_luci2.globals.currentView)
2123                                 _luci2.globals.currentView.finish();
2124
2125                         _luci2.ui.renderViewMenu();
2126
2127                         if (!_luci2._views)
2128                                 _luci2._views = { };
2129
2130                         _luci2.setHash('view', node.view);
2131
2132                         if (_luci2._views[name] instanceof _luci2.ui.view)
2133                         {
2134                                 _luci2.globals.currentView = _luci2._views[name];
2135                                 return _luci2._views[name].render();
2136                         }
2137
2138                         var url = _luci2.globals.resource + '/view/' + name + '.js';
2139
2140                         return $.ajax(url, {
2141                                 method: 'GET',
2142                                 cache: true,
2143                                 dataType: 'text'
2144                         }).then(function(data) {
2145                                 try {
2146                                         var viewConstructorSource = (
2147                                                 '(function(L, $) { ' +
2148                                                         'return %s' +
2149                                                 '})(_luci2, $);\n\n' +
2150                                                 '//@ sourceURL=%s'
2151                                         ).format(data, url);
2152
2153                                         var viewConstructor = eval(viewConstructorSource);
2154
2155                                         _luci2._views[name] = new viewConstructor({
2156                                                 name: name,
2157                                                 acls: node.write || { }
2158                                         });
2159
2160                                         _luci2.globals.currentView = _luci2._views[name];
2161                                         return _luci2._views[name].render();
2162                                 }
2163                                 catch(e) {
2164                                         alert('Unable to instantiate view "%s": %s'.format(url, e));
2165                                 };
2166
2167                                 return $.Deferred().resolve();
2168                         });
2169                 },
2170
2171                 updateHostname: function()
2172                 {
2173                         return _luci2.system.getBoardInfo().then(function(info) {
2174                                 if (info.hostname)
2175                                         $('#hostname').text(info.hostname);
2176                         });
2177                 },
2178
2179                 updateChanges: function()
2180                 {
2181                         return _luci2.uci.changes().then(function(changes) {
2182                                 var n = 0;
2183                                 var html = '';
2184
2185                                 for (var config in changes)
2186                                 {
2187                                         var log = [ ];
2188
2189                                         for (var i = 0; i < changes[config].length; i++)
2190                                         {
2191                                                 var c = changes[config][i];
2192
2193                                                 switch (c[0])
2194                                                 {
2195                                                 case 'order':
2196                                                         break;
2197
2198                                                 case 'remove':
2199                                                         if (c.length < 3)
2200                                                                 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2201                                                         else
2202                                                                 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2203                                                         break;
2204
2205                                                 case 'rename':
2206                                                         if (c.length < 4)
2207                                                                 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2208                                                         else
2209                                                                 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2210                                                         break;
2211
2212                                                 case 'add':
2213                                                         log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2214                                                         break;
2215
2216                                                 case 'list-add':
2217                                                         log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2218                                                         break;
2219
2220                                                 case 'list-del':
2221                                                         log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2222                                                         break;
2223
2224                                                 case 'set':
2225                                                         if (c.length < 4)
2226                                                                 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2227                                                         else
2228                                                                 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2229                                                         break;
2230                                                 }
2231                                         }
2232
2233                                         html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2234                                         n += changes[config].length;
2235                                 }
2236
2237                                 if (n > 0)
2238                                         $('#changes')
2239                                                 .empty()
2240                                                 .show()
2241                                                 .append($('<a />')
2242                                                         .attr('href', '#')
2243                                                         .addClass('label')
2244                                                         .addClass('notice')
2245                                                         .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2246                                                         .click(function(ev) {
2247                                                                 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2248                                                                 ev.preventDefault();
2249                                                         }));
2250                                 else
2251                                         $('#changes')
2252                                                 .hide();
2253                         });
2254                 },
2255
2256                 init: function()
2257                 {
2258                         _luci2.ui.loading(true);
2259
2260                         $.when(
2261                                 _luci2.ui.updateHostname(),
2262                                 _luci2.ui.updateChanges(),
2263                                 _luci2.ui.renderMainMenu()
2264                         ).then(function() {
2265                                 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2266                                         _luci2.ui.loading(false);
2267                                 })
2268                         });
2269                 }
2270         };
2271
2272         var AbstractWidget = Class.extend({
2273                 i18n: function(text) {
2274                         return text;
2275                 },
2276
2277                 toString: function() {
2278                         var x = document.createElement('div');
2279                                 x.appendChild(this.render());
2280
2281                         return x.innerHTML;
2282                 },
2283
2284                 insertInto: function(id) {
2285                         return $(id).empty().append(this.render());
2286                 }
2287         });
2288
2289         this.ui.view = AbstractWidget.extend({
2290                 _fetch_template: function()
2291                 {
2292                         return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2293                                 method: 'GET',
2294                                 cache: true,
2295                                 dataType: 'text',
2296                                 success: function(data) {
2297                                         data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2298                                                 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2299                                                 switch (p1)
2300                                                 {
2301                                                 case '#':
2302                                                         return '';
2303
2304                                                 case ':':
2305                                                         return _luci2.tr(p2);
2306
2307                                                 case '=':
2308                                                         return _luci2.globals[p2] || '';
2309
2310                                                 default:
2311                                                         return '(?' + match + ')';
2312                                                 }
2313                                         });
2314
2315                                         $('#maincontent').append(data);
2316                                 }
2317                         });
2318                 },
2319
2320                 execute: function()
2321                 {
2322                         throw "Not implemented";
2323                 },
2324
2325                 render: function()
2326                 {
2327                         var container = $('#maincontent');
2328
2329                         container.empty();
2330
2331                         if (this.title)
2332                                 container.append($('<h2 />').append(this.title));
2333
2334                         if (this.description)
2335                                 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2336
2337                         var self = this;
2338                         return this._fetch_template().then(function() {
2339                                 return _luci2.deferrable(self.execute());
2340                         });
2341                 },
2342
2343                 repeat: function(func, interval)
2344                 {
2345                         var self = this;
2346
2347                         if (!self._timeouts)
2348                                 self._timeouts = [ ];
2349
2350                         var index = self._timeouts.length;
2351
2352                         if (typeof(interval) != 'number')
2353                                 interval = 5000;
2354
2355                         var setTimer, runTimer;
2356
2357                         setTimer = function() {
2358                                 self._timeouts[index] = window.setTimeout(runTimer, interval);
2359                         };
2360
2361                         runTimer = function() {
2362                                 _luci2.deferrable(func.call(self)).then(setTimer);
2363                         };
2364
2365                         runTimer();
2366                 },
2367
2368                 finish: function()
2369                 {
2370                         if ($.isArray(this._timeouts))
2371                         {
2372                                 for (var i = 0; i < this._timeouts.length; i++)
2373                                         window.clearTimeout(this._timeouts[i]);
2374
2375                                 delete this._timeouts;
2376                         }
2377                 }
2378         });
2379
2380         this.ui.menu = AbstractWidget.extend({
2381                 init: function() {
2382                         this._nodes = { };
2383                 },
2384
2385                 entries: function(entries)
2386                 {
2387                         for (var entry in entries)
2388                         {
2389                                 var path = entry.split(/\//);
2390                                 var node = this._nodes;
2391
2392                                 for (i = 0; i < path.length; i++)
2393                                 {
2394                                         if (!node.childs)
2395                                                 node.childs = { };
2396
2397                                         if (!node.childs[path[i]])
2398                                                 node.childs[path[i]] = { };
2399
2400                                         node = node.childs[path[i]];
2401                                 }
2402
2403                                 $.extend(node, entries[entry]);
2404                         }
2405                 },
2406
2407                 _indexcmp: function(a, b)
2408                 {
2409                         var x = a.index || 0;
2410                         var y = b.index || 0;
2411                         return (x - y);
2412                 },
2413
2414                 firstChildView: function(node)
2415                 {
2416                         if (node.view)
2417                                 return node;
2418
2419                         var nodes = [ ];
2420                         for (var child in (node.childs || { }))
2421                                 nodes.push(node.childs[child]);
2422
2423                         nodes.sort(this._indexcmp);
2424
2425                         for (var i = 0; i < nodes.length; i++)
2426                         {
2427                                 var child = this.firstChildView(nodes[i]);
2428                                 if (child)
2429                                 {
2430                                         for (var key in child)
2431                                                 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2432                                                         node[key] = child[key];
2433
2434                                         return node;
2435                                 }
2436                         }
2437
2438                         return undefined;
2439                 },
2440
2441                 _onclick: function(ev)
2442                 {
2443                         _luci2.ui.loading(true);
2444                         _luci2.ui.renderView(ev.data).then(function() {
2445                                 _luci2.ui.loading(false);
2446                         });
2447
2448                         ev.preventDefault();
2449                         this.blur();
2450                 },
2451
2452                 _render: function(childs, level, min, max)
2453                 {
2454                         var nodes = [ ];
2455                         for (var node in childs)
2456                         {
2457                                 var child = this.firstChildView(childs[node]);
2458                                 if (child)
2459                                         nodes.push(childs[node]);
2460                         }
2461
2462                         nodes.sort(this._indexcmp);
2463
2464                         var list = $('<ul />');
2465
2466                         if (level == 0)
2467                                 list.addClass('nav');
2468                         else if (level == 1)
2469                                 list.addClass('dropdown-menu');
2470
2471                         for (var i = 0; i < nodes.length; i++)
2472                         {
2473                                 if (!_luci2.globals.defaultNode)
2474                                 {
2475                                         var v = _luci2.getHash('view');
2476                                         if (!v || v == nodes[i].view)
2477                                                 _luci2.globals.defaultNode = nodes[i];
2478                                 }
2479
2480                                 var item = $('<li />')
2481                                         .append($('<a />')
2482                                                 .attr('href', '#')
2483                                                 .text(_luci2.tr(nodes[i].title))
2484                                                 .click(nodes[i], this._onclick))
2485                                         .appendTo(list);
2486
2487                                 if (nodes[i].childs && level < max)
2488                                 {
2489                                         item.addClass('dropdown');
2490                                         item.find('a').addClass('menu');
2491                                         item.append(this._render(nodes[i].childs, level + 1));
2492                                 }
2493                         }
2494
2495                         return list.get(0);
2496                 },
2497
2498                 render: function(min, max)
2499                 {
2500                         var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2501                         return this._render(top.childs, 0, min, max);
2502                 },
2503
2504                 getNode: function(path, max)
2505                 {
2506                         var p = path.split(/\//);
2507                         var n = this._nodes;
2508
2509                         if (typeof(max) == 'undefined')
2510                                 max = p.length;
2511
2512                         for (var i = 0; i < max; i++)
2513                         {
2514                                 if (!n.childs[p[i]])
2515                                         return undefined;
2516
2517                                 n = n.childs[p[i]];
2518                         }
2519
2520                         return n;
2521                 }
2522         });
2523
2524         this.ui.table = AbstractWidget.extend({
2525                 init: function()
2526                 {
2527                         this._rows = [ ];
2528                 },
2529
2530                 row: function(values)
2531                 {
2532                         if ($.isArray(values))
2533                         {
2534                                 this._rows.push(values);
2535                         }
2536                         else if ($.isPlainObject(values))
2537                         {
2538                                 var v = [ ];
2539                                 for (var i = 0; i < this.options.columns.length; i++)
2540                                 {
2541                                         var col = this.options.columns[i];
2542
2543                                         if (typeof col.key == 'string')
2544                                                 v.push(values[col.key]);
2545                                         else
2546                                                 v.push(null);
2547                                 }
2548                                 this._rows.push(v);
2549                         }
2550                 },
2551
2552                 rows: function(rows)
2553                 {
2554                         for (var i = 0; i < rows.length; i++)
2555                                 this.row(rows[i]);
2556                 },
2557
2558                 render: function(id)
2559                 {
2560                         var fieldset = document.createElement('fieldset');
2561                                 fieldset.className = 'cbi-section';
2562
2563                         if (this.options.caption)
2564                         {
2565                                 var legend = document.createElement('legend');
2566                                 $(legend).append(this.options.caption);
2567                                 fieldset.appendChild(legend);
2568                         }
2569
2570                         var table = document.createElement('table');
2571                                 table.className = 'cbi-section-table';
2572
2573                         var has_caption = false;
2574                         var has_description = false;
2575
2576                         for (var i = 0; i < this.options.columns.length; i++)
2577                                 if (this.options.columns[i].caption)
2578                                 {
2579                                         has_caption = true;
2580                                         break;
2581                                 }
2582                                 else if (this.options.columns[i].description)
2583                                 {
2584                                         has_description = true;
2585                                         break;
2586                                 }
2587
2588                         if (has_caption)
2589                         {
2590                                 var tr = table.insertRow(-1);
2591                                         tr.className = 'cbi-section-table-titles';
2592
2593                                 for (var i = 0; i < this.options.columns.length; i++)
2594                                 {
2595                                         var col = this.options.columns[i];
2596                                         var th = document.createElement('th');
2597                                                 th.className = 'cbi-section-table-cell';
2598
2599                                         tr.appendChild(th);
2600
2601                                         if (col.width)
2602                                                 th.style.width = col.width;
2603
2604                                         if (col.align)
2605                                                 th.style.textAlign = col.align;
2606
2607                                         if (col.caption)
2608                                                 $(th).append(col.caption);
2609                                 }
2610                         }
2611
2612                         if (has_description)
2613                         {
2614                                 var tr = table.insertRow(-1);
2615                                         tr.className = 'cbi-section-table-descr';
2616
2617                                 for (var i = 0; i < this.options.columns.length; i++)
2618                                 {
2619                                         var col = this.options.columns[i];
2620                                         var th = document.createElement('th');
2621                                                 th.className = 'cbi-section-table-cell';
2622
2623                                         tr.appendChild(th);
2624
2625                                         if (col.width)
2626                                                 th.style.width = col.width;
2627
2628                                         if (col.align)
2629                                                 th.style.textAlign = col.align;
2630
2631                                         if (col.description)
2632                                                 $(th).append(col.description);
2633                                 }
2634                         }
2635
2636                         if (this._rows.length == 0)
2637                         {
2638                                 if (this.options.placeholder)
2639                                 {
2640                                         var tr = table.insertRow(-1);
2641                                         var td = tr.insertCell(-1);
2642                                                 td.className = 'cbi-section-table-cell';
2643
2644                                         td.colSpan = this.options.columns.length;
2645                                         $(td).append(this.options.placeholder);
2646                                 }
2647                         }
2648                         else
2649                         {
2650                                 for (var i = 0; i < this._rows.length; i++)
2651                                 {
2652                                         var tr = table.insertRow(-1);
2653
2654                                         for (var j = 0; j < this.options.columns.length; j++)
2655                                         {
2656                                                 var col = this.options.columns[j];
2657                                                 var td = tr.insertCell(-1);
2658
2659                                                 var val = this._rows[i][j];
2660
2661                                                 if (typeof(val) == 'undefined')
2662                                                         val = col.placeholder;
2663
2664                                                 if (typeof(val) == 'undefined')
2665                                                         val = '';
2666
2667                                                 if (col.width)
2668                                                         td.style.width = col.width;
2669
2670                                                 if (col.align)
2671                                                         td.style.textAlign = col.align;
2672
2673                                                 if (typeof col.format == 'string')
2674                                                         $(td).append(col.format.format(val));
2675                                                 else if (typeof col.format == 'function')
2676                                                         $(td).append(col.format(val, i));
2677                                                 else
2678                                                         $(td).append(val);
2679                                         }
2680                                 }
2681                         }
2682
2683                         this._rows = [ ];
2684                         fieldset.appendChild(table);
2685
2686                         return fieldset;
2687                 }
2688         });
2689
2690         this.ui.progress = AbstractWidget.extend({
2691                 render: function()
2692                 {
2693                         var vn = parseInt(this.options.value) || 0;
2694                         var mn = parseInt(this.options.max) || 100;
2695                         var pc = Math.floor((100 / mn) * vn);
2696
2697                         var bar = document.createElement('div');
2698                                 bar.className = 'progressbar';
2699
2700                         bar.appendChild(document.createElement('div'));
2701                         bar.lastChild.appendChild(document.createElement('div'));
2702                         bar.lastChild.style.width = pc + '%';
2703
2704                         if (typeof(this.options.format) == 'string')
2705                                 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2706                         else if (typeof(this.options.format) == 'function')
2707                                 $(bar.lastChild.lastChild).append(this.options.format(pc));
2708                         else
2709                                 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2710
2711                         return bar;
2712                 }
2713         });
2714
2715         this.ui.devicebadge = AbstractWidget.extend({
2716                 render: function()
2717                 {
2718                         var l2dev = this.options.l2_device || this.options.device;
2719                         var l3dev = this.options.l3_device;
2720                         var dev = l3dev || l2dev || '?';
2721
2722                         var span = document.createElement('span');
2723                                 span.className = 'ifacebadge';
2724
2725                         if (typeof(this.options.signal) == 'number' ||
2726                                 typeof(this.options.noise) == 'number')
2727                         {
2728                                 var r = 'none';
2729                                 if (typeof(this.options.signal) != 'undefined' &&
2730                                         typeof(this.options.noise) != 'undefined')
2731                                 {
2732                                         var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2733                                         if (q < 1)
2734                                                 r = '0';
2735                                         else if (q < 2)
2736                                                 r = '0-25';
2737                                         else if (q < 3)
2738                                                 r = '25-50';
2739                                         else if (q < 4)
2740                                                 r = '50-75';
2741                                         else
2742                                                 r = '75-100';
2743                                 }
2744
2745                                 span.appendChild(document.createElement('img'));
2746                                 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2747
2748                                 if (r == 'none')
2749                                         span.title = _luci2.tr('No signal');
2750                                 else
2751                                         span.title = '%s: %d %s / %s: %d %s'.format(
2752                                                 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2753                                                 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2754                                         );
2755                         }
2756                         else
2757                         {
2758                                 var type = 'ethernet';
2759                                 var desc = _luci2.tr('Ethernet device');
2760
2761                                 if (l3dev != l2dev)
2762                                 {
2763                                         type = 'tunnel';
2764                                         desc = _luci2.tr('Tunnel interface');
2765                                 }
2766                                 else if (dev.indexOf('br-') == 0)
2767                                 {
2768                                         type = 'bridge';
2769                                         desc = _luci2.tr('Bridge');
2770                                 }
2771                                 else if (dev.indexOf('.') > 0)
2772                                 {
2773                                         type = 'vlan';
2774                                         desc = _luci2.tr('VLAN interface');
2775                                 }
2776                                 else if (dev.indexOf('wlan') == 0 ||
2777                                                  dev.indexOf('ath') == 0 ||
2778                                                  dev.indexOf('wl') == 0)
2779                                 {
2780                                         type = 'wifi';
2781                                         desc = _luci2.tr('Wireless Network');
2782                                 }
2783
2784                                 span.appendChild(document.createElement('img'));
2785                                 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2786                                 span.title = desc;
2787                         }
2788
2789                         $(span).append(' ');
2790                         $(span).append(dev);
2791
2792                         return span;
2793                 }
2794         });
2795
2796         var type = function(f, l)
2797         {
2798                 f.message = l;
2799                 return f;
2800         };
2801
2802         this.cbi = {
2803                 validation: {
2804                         i18n: function(msg)
2805                         {
2806                                 _luci2.cbi.validation.message = _luci2.tr(msg);
2807                         },
2808
2809                         compile: function(code)
2810                         {
2811                                 var pos = 0;
2812                                 var esc = false;
2813                                 var depth = 0;
2814                                 var types = _luci2.cbi.validation.types;
2815                                 var stack = [ ];
2816
2817                                 code += ',';
2818
2819                                 for (var i = 0; i < code.length; i++)
2820                                 {
2821                                         if (esc)
2822                                         {
2823                                                 esc = false;
2824                                                 continue;
2825                                         }
2826
2827                                         switch (code.charCodeAt(i))
2828                                         {
2829                                         case 92:
2830                                                 esc = true;
2831                                                 break;
2832
2833                                         case 40:
2834                                         case 44:
2835                                                 if (depth <= 0)
2836                                                 {
2837                                                         if (pos < i)
2838                                                         {
2839                                                                 var label = code.substring(pos, i);
2840                                                                         label = label.replace(/\\(.)/g, '$1');
2841                                                                         label = label.replace(/^[ \t]+/g, '');
2842                                                                         label = label.replace(/[ \t]+$/g, '');
2843
2844                                                                 if (label && !isNaN(label))
2845                                                                 {
2846                                                                         stack.push(parseFloat(label));
2847                                                                 }
2848                                                                 else if (label.match(/^(['"]).*\1$/))
2849                                                                 {
2850                                                                         stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2851                                                                 }
2852                                                                 else if (typeof types[label] == 'function')
2853                                                                 {
2854                                                                         stack.push(types[label]);
2855                                                                         stack.push(null);
2856                                                                 }
2857                                                                 else
2858                                                                 {
2859                                                                         throw "Syntax error, unhandled token '"+label+"'";
2860                                                                 }
2861                                                         }
2862                                                         pos = i+1;
2863                                                 }
2864                                                 depth += (code.charCodeAt(i) == 40);
2865                                                 break;
2866
2867                                         case 41:
2868                                                 if (--depth <= 0)
2869                                                 {
2870                                                         if (typeof stack[stack.length-2] != 'function')
2871                                                                 throw "Syntax error, argument list follows non-function";
2872
2873                                                         stack[stack.length-1] =
2874                                                                 arguments.callee(code.substring(pos, i));
2875
2876                                                         pos = i+1;
2877                                                 }
2878                                                 break;
2879                                         }
2880                                 }
2881
2882                                 return stack;
2883                         }
2884                 }
2885         };
2886
2887         var validation = this.cbi.validation;
2888
2889         validation.types = {
2890                 'integer': function()
2891                 {
2892                         if (this.match(/^-?[0-9]+$/) != null)
2893                                 return true;
2894
2895                         validation.i18n('Must be a valid integer');
2896                         return false;
2897                 },
2898
2899                 'uinteger': function()
2900                 {
2901                         if (validation.types['integer'].apply(this) && (this >= 0))
2902                                 return true;
2903
2904                         validation.i18n('Must be a positive integer');
2905                         return false;
2906                 },
2907
2908                 'float': function()
2909                 {
2910                         if (!isNaN(parseFloat(this)))
2911                                 return true;
2912
2913                         validation.i18n('Must be a valid number');
2914                         return false;
2915                 },
2916
2917                 'ufloat': function()
2918                 {
2919                         if (validation.types['float'].apply(this) && (this >= 0))
2920                                 return true;
2921
2922                         validation.i18n('Must be a positive number');
2923                         return false;
2924                 },
2925
2926                 'ipaddr': function()
2927                 {
2928                         if (validation.types['ip4addr'].apply(this) ||
2929                                 validation.types['ip6addr'].apply(this))
2930                                 return true;
2931
2932                         validation.i18n('Must be a valid IP address');
2933                         return false;
2934                 },
2935
2936                 'ip4addr': function()
2937                 {
2938                         if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2939                         {
2940                                 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2941