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