luci2: remove newline from generated view constructor code to make debugger line...
[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] || (devs[dev] = { });
792                                 }
793
794                                 _luci2.rpc.batch();
795
796                                 for (var dev in devs)
797                                         _luci2.network.getDeviceStatus(dev);
798
799                                 return _luci2.rpc.flush();
800                         }).then(function(devices) {
801                                 _luci2.rpc.batch();
802
803                                 for (var i = 0; i < devices.length; i++)
804                                 {
805                                         var brm = devices[i]['bridge-members'];
806                                         delete devices[i]['bridge-members'];
807
808                                         $.extend(devs[devices[i]['device']], devices[i]);
809
810                                         if (!brm)
811                                                 continue;
812
813                                         devs[devices[i]['device']].subdevices = [ ];
814
815                                         for (var j = 0; j < brm.length; j++)
816                                         {
817                                                 if (!devs[brm[j]])
818                                                 {
819                                                         devs[brm[j]] = { };
820                                                         _luci2.network.getDeviceStatus(brm[j]);
821                                                 }
822
823                                                 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
824                                         }
825                                 }
826
827                                 return _luci2.rpc.flush();
828                         }).then(function(subdevices) {
829                                 for (var i = 0; i < subdevices.length; i++)
830                                         $.extend(devs[subdevices[i]['device']], subdevices[i]);
831
832                                 _luci2.rpc.batch();
833
834                                 for (var dev in devs)
835                                         _luci2.wireless.getDeviceStatus(dev);
836
837                                 return _luci2.rpc.flush();
838                         }).then(function(wifidevices) {
839                                 for (var i = 0; i < wifidevices.length; i++)
840                                         if (wifidevices[i])
841                                                 devs[wifidevices[i]['device']].wireless = wifidevices[i];
842
843                                 nets.sort(function(a, b) {
844                                         if (a['interface'] < b['interface'])
845                                                 return -1;
846                                         else if (a['interface'] > b['interface'])
847                                                 return 1;
848                                         else
849                                                 return 0;
850                                 });
851
852                                 return nets;
853                         });
854                 },
855
856                 findWanInterfaces: function(cb)
857                 {
858                         return this.listNetworkNames().then(function(names) {
859                                 _luci2.rpc.batch();
860
861                                 for (var i = 0; i < names.length; i++)
862                                         _luci2.network.getInterfaceStatus(names[i]);
863
864                                 return _luci2.rpc.flush();
865                         }).then(function(interfaces) {
866                                 var rv = [ undefined, undefined ];
867
868                                 for (var i = 0; i < interfaces.length; i++)
869                                 {
870                                         if (!interfaces[i].route)
871                                                 continue;
872
873                                         for (var j = 0; j < interfaces[i].route.length; j++)
874                                         {
875                                                 var rt = interfaces[i].route[j];
876
877                                                 if (typeof(rt.table) != 'undefined')
878                                                         continue;
879
880                                                 if (rt.target == '0.0.0.0' && rt.mask == 0)
881                                                         rv[0] = interfaces[i];
882                                                 else if (rt.target == '::' && rt.mask == 0)
883                                                         rv[1] = interfaces[i];
884                                         }
885                                 }
886
887                                 return rv;
888                         });
889                 },
890
891                 getDHCPLeases: _luci2.rpc.declare({
892                         object: 'luci2.network',
893                         method: 'dhcp_leases',
894                         expect: { leases: [ ] }
895                 }),
896
897                 getDHCPv6Leases: _luci2.rpc.declare({
898                         object: 'luci2.network',
899                         method: 'dhcp6_leases',
900                         expect: { leases: [ ] }
901                 }),
902
903                 getRoutes: _luci2.rpc.declare({
904                         object: 'luci2.network',
905                         method: 'routes',
906                         expect: { routes: [ ] }
907                 }),
908
909                 getIPv6Routes: _luci2.rpc.declare({
910                         object: 'luci2.network',
911                         method: 'routes',
912                         expect: { routes: [ ] }
913                 }),
914
915                 getARPTable: _luci2.rpc.declare({
916                         object: 'luci2.network',
917                         method: 'arp_table',
918                         expect: { entries: [ ] }
919                 }),
920
921                 getInterfaceStatus: _luci2.rpc.declare({
922                         object: 'network.interface',
923                         method: 'status',
924                         params: [ 'interface' ],
925                         expect: { '': { } },
926                         filter: function(data, params) {
927                                 data['interface'] = params['interface'];
928                                 data['l2_device'] = data['device'];
929                                 delete data['device'];
930                                 return data;
931                         }
932                 }),
933
934                 getDeviceStatus: _luci2.rpc.declare({
935                         object: 'network.device',
936                         method: 'status',
937                         params: [ 'name' ],
938                         expect: { '': { } },
939                         filter: function(data, params) {
940                                 data['device'] = params['name'];
941                                 return data;
942                         }
943                 }),
944
945                 getConntrackCount: _luci2.rpc.declare({
946                         object: 'luci2.network',
947                         method: 'conntrack_count',
948                         expect: { '': { count: 0, limit: 0 } }
949                 })
950         };
951
952         this.wireless = {
953                 listDeviceNames: _luci2.rpc.declare({
954                         object: 'iwinfo',
955                         method: 'devices',
956                         expect: { 'devices': [ ] },
957                         filter: function(data) {
958                                 data.sort();
959                                 return data;
960                         }
961                 }),
962
963                 getDeviceStatus: _luci2.rpc.declare({
964                         object: 'iwinfo',
965                         method: 'info',
966                         params: [ 'device' ],
967                         expect: { '': { } },
968                         filter: function(data, params) {
969                                 if (!$.isEmptyObject(data))
970                                 {
971                                         data['device'] = params['device'];
972                                         return data;
973                                 }
974                                 return undefined;
975                         }
976                 }),
977
978                 getAssocList: _luci2.rpc.declare({
979                         object: 'iwinfo',
980                         method: 'assoclist',
981                         params: [ 'device' ],
982                         expect: { results: [ ] },
983                         filter: function(data, params) {
984                                 for (var i = 0; i < data.length; i++)
985                                         data[i]['device'] = params['device'];
986
987                                 data.sort(function(a, b) {
988                                         if (a.bssid < b.bssid)
989                                                 return -1;
990                                         else if (a.bssid > b.bssid)
991                                                 return 1;
992                                         else
993                                                 return 0;
994                                 });
995
996                                 return data;
997                         }
998                 }),
999
1000                 getWirelessStatus: function() {
1001                         return this.listDeviceNames().then(function(names) {
1002                                 _luci2.rpc.batch();
1003
1004                                 for (var i = 0; i < names.length; i++)
1005                                         _luci2.wireless.getDeviceStatus(names[i]);
1006
1007                                 return _luci2.rpc.flush();
1008                         }).then(function(networks) {
1009                                 var rv = { };
1010
1011                                 var phy_attrs = [
1012                                         'country', 'channel', 'frequency', 'frequency_offset',
1013                                         'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1014                                 ];
1015
1016                                 var net_attrs = [
1017                                         'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1018                                         'signal', 'noise', 'bitrate', 'encryption'
1019                                 ];
1020
1021                                 for (var i = 0; i < networks.length; i++)
1022                                 {
1023                                         var phy = rv[networks[i].phy] || (
1024                                                 rv[networks[i].phy] = { networks: [ ] }
1025                                         );
1026
1027                                         var net = {
1028                                                 device: networks[i].device
1029                                         };
1030
1031                                         for (var j = 0; j < phy_attrs.length; j++)
1032                                                 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1033
1034                                         for (var j = 0; j < net_attrs.length; j++)
1035                                                 net[net_attrs[j]] = networks[i][net_attrs[j]];
1036
1037                                         phy.networks.push(net);
1038                                 }
1039
1040                                 return rv;
1041                         });
1042                 },
1043
1044                 getAssocLists: function()
1045                 {
1046                         return this.listDeviceNames().then(function(names) {
1047                                 _luci2.rpc.batch();
1048
1049                                 for (var i = 0; i < names.length; i++)
1050                                         _luci2.wireless.getAssocList(names[i]);
1051
1052                                 return _luci2.rpc.flush();
1053                         }).then(function(assoclists) {
1054                                 var rv = [ ];
1055
1056                                 for (var i = 0; i < assoclists.length; i++)
1057                                         for (var j = 0; j < assoclists[i].length; j++)
1058                                                 rv.push(assoclists[i][j]);
1059
1060                                 return rv;
1061                         });
1062                 },
1063
1064                 formatEncryption: function(enc)
1065                 {
1066                         var format_list = function(l, s)
1067                         {
1068                                 var rv = [ ];
1069                                 for (var i = 0; i < l.length; i++)
1070                                         rv.push(l[i].toUpperCase());
1071                                 return rv.join(s ? s : ', ');
1072                         }
1073
1074                         if (!enc || !enc.enabled)
1075                                 return _luci2.tr('None');
1076
1077                         if (enc.wep)
1078                         {
1079                                 if (enc.wep.length == 2)
1080                                         return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1081                                 else if (enc.wep[0] == 'shared')
1082                                         return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1083                                 else
1084                                         return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1085                         }
1086                         else if (enc.wpa)
1087                         {
1088                                 if (enc.wpa.length == 2)
1089                                         return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1090                                                 format_list(enc.authentication, '/'),
1091                                                 format_list(enc.ciphers, ', ')
1092                                         );
1093                                 else if (enc.wpa[0] == 2)
1094                                         return 'WPA2 %s (%s)'.format(
1095                                                 format_list(enc.authentication, '/'),
1096                                                 format_list(enc.ciphers, ', ')
1097                                         );
1098                                 else
1099                                         return 'WPA %s (%s)'.format(
1100                                                 format_list(enc.authentication, '/'),
1101                                                 format_list(enc.ciphers, ', ')
1102                                         );
1103                         }
1104
1105                         return _luci2.tr('Unknown');
1106                 }
1107         };
1108
1109         this.system = {
1110                 getSystemInfo: _luci2.rpc.declare({
1111                         object: 'system',
1112                         method: 'info',
1113                         expect: { '': { } }
1114                 }),
1115
1116                 getBoardInfo: _luci2.rpc.declare({
1117                         object: 'system',
1118                         method: 'board',
1119                         expect: { '': { } }
1120                 }),
1121
1122                 getDiskInfo: _luci2.rpc.declare({
1123                         object: 'luci2.system',
1124                         method: 'diskfree',
1125                         expect: { '': { } }
1126                 }),
1127
1128                 getInfo: function(cb)
1129                 {
1130                         _luci2.rpc.batch();
1131
1132                         this.getSystemInfo();
1133                         this.getBoardInfo();
1134                         this.getDiskInfo();
1135
1136                         return _luci2.rpc.flush().then(function(info) {
1137                                 var rv = { };
1138
1139                                 $.extend(rv, info[0]);
1140                                 $.extend(rv, info[1]);
1141                                 $.extend(rv, info[2]);
1142
1143                                 return rv;
1144                         });
1145                 },
1146
1147                 getProcessList: _luci2.rpc.declare({
1148                         object: 'luci2.system',
1149                         method: 'process_list',
1150                         expect: { processes: [ ] },
1151                         filter: function(data) {
1152                                 data.sort(function(a, b) { return a.pid - b.pid });
1153                                 return data;
1154                         }
1155                 }),
1156
1157                 getSystemLog: _luci2.rpc.declare({
1158                         object: 'luci2.system',
1159                         method: 'syslog',
1160                         expect: { log: '' }
1161                 }),
1162
1163                 getKernelLog: _luci2.rpc.declare({
1164                         object: 'luci2.system',
1165                         method: 'dmesg',
1166                         expect: { log: '' }
1167                 }),
1168
1169                 getZoneInfo: function(cb)
1170                 {
1171                         return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1172                 },
1173
1174                 sendSignal: _luci2.rpc.declare({
1175                         object: 'luci2.system',
1176                         method: 'process_signal',
1177                         params: [ 'pid', 'signal' ],
1178                         filter: function(data) {
1179                                 return (data == 0);
1180                         }
1181                 }),
1182
1183                 initList: _luci2.rpc.declare({
1184                         object: 'luci2.system',
1185                         method: 'init_list',
1186                         expect: { initscripts: [ ] },
1187                         filter: function(data) {
1188                                 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1189                                 return data;
1190                         }
1191                 }),
1192
1193                 initEnabled: function(init, cb)
1194                 {
1195                         return this.initList().then(function(list) {
1196                                 for (var i = 0; i < list.length; i++)
1197                                         if (list[i].name == init)
1198                                                 return !!list[i].enabled;
1199
1200                                 return false;
1201                         });
1202                 },
1203
1204                 initRun: _luci2.rpc.declare({
1205                         object: 'luci2.system',
1206                         method: 'init_action',
1207                         params: [ 'name', 'action' ],
1208                         filter: function(data) {
1209                                 return (data == 0);
1210                         }
1211                 }),
1212
1213                 initStart:   function(init, cb) { return _luci2.system.initRun(init, 'start',   cb) },
1214                 initStop:    function(init, cb) { return _luci2.system.initRun(init, 'stop',    cb) },
1215                 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1216                 initReload:  function(init, cb) { return _luci2.system.initRun(init, 'reload',  cb) },
1217                 initEnable:  function(init, cb) { return _luci2.system.initRun(init, 'enable',  cb) },
1218                 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1219
1220
1221                 getRcLocal: _luci2.rpc.declare({
1222                         object: 'luci2.system',
1223                         method: 'rclocal_get',
1224                         expect: { data: '' }
1225                 }),
1226
1227                 setRcLocal: _luci2.rpc.declare({
1228                         object: 'luci2.system',
1229                         method: 'rclocal_set',
1230                         params: [ 'data' ]
1231                 }),
1232
1233
1234                 getCrontab: _luci2.rpc.declare({
1235                         object: 'luci2.system',
1236                         method: 'crontab_get',
1237                         expect: { data: '' }
1238                 }),
1239
1240                 setCrontab: _luci2.rpc.declare({
1241                         object: 'luci2.system',
1242                         method: 'crontab_set',
1243                         params: [ 'data' ]
1244                 }),
1245
1246
1247                 getSSHKeys: _luci2.rpc.declare({
1248                         object: 'luci2.system',
1249                         method: 'sshkeys_get',
1250                         expect: { keys: [ ] }
1251                 }),
1252
1253                 setSSHKeys: _luci2.rpc.declare({
1254                         object: 'luci2.system',
1255                         method: 'sshkeys_set',
1256                         params: [ 'keys' ]
1257                 }),
1258
1259
1260                 setPassword: _luci2.rpc.declare({
1261                         object: 'luci2.system',
1262                         method: 'password_set',
1263                         params: [ 'user', 'password' ]
1264                 }),
1265
1266
1267                 listLEDs: _luci2.rpc.declare({
1268                         object: 'luci2.system',
1269                         method: 'led_list',
1270                         expect: { leds: [ ] }
1271                 }),
1272
1273                 listUSBDevices: _luci2.rpc.declare({
1274                         object: 'luci2.system',
1275                         method: 'usb_list',
1276                         expect: { devices: [ ] }
1277                 }),
1278
1279
1280                 testUpgrade: _luci2.rpc.declare({
1281                         object: 'luci2.system',
1282                         method: 'upgrade_test',
1283                         expect: { '': { } }
1284                 }),
1285
1286                 startUpgrade: _luci2.rpc.declare({
1287                         object: 'luci2.system',
1288                         method: 'upgrade_start',
1289                         params: [ 'keep' ]
1290                 }),
1291
1292                 cleanUpgrade: _luci2.rpc.declare({
1293                         object: 'luci2.system',
1294                         method: 'upgrade_clean'
1295                 }),
1296
1297
1298                 restoreBackup: _luci2.rpc.declare({
1299                         object: 'luci2.system',
1300                         method: 'backup_restore'
1301                 }),
1302
1303                 cleanBackup: _luci2.rpc.declare({
1304                         object: 'luci2.system',
1305                         method: 'backup_clean'
1306                 }),
1307
1308
1309                 getBackupConfig: _luci2.rpc.declare({
1310                         object: 'luci2.system',
1311                         method: 'backup_config_get',
1312                         expect: { config: '' }
1313                 }),
1314
1315                 setBackupConfig: _luci2.rpc.declare({
1316                         object: 'luci2.system',
1317                         method: 'backup_config_set',
1318                         params: [ 'data' ]
1319                 }),
1320
1321
1322                 listBackup: _luci2.rpc.declare({
1323                         object: 'luci2.system',
1324                         method: 'backup_list',
1325                         expect: { files: [ ] }
1326                 }),
1327
1328
1329                 testReset: _luci2.rpc.declare({
1330                         object: 'luci2.system',
1331                         method: 'reset_test',
1332                         expect: { supported: false }
1333                 }),
1334
1335                 startReset: _luci2.rpc.declare({
1336                         object: 'luci2.system',
1337                         method: 'reset_start'
1338                 }),
1339
1340
1341                 performReboot: _luci2.rpc.declare({
1342                         object: 'luci2.system',
1343                         method: 'reboot'
1344                 })
1345         };
1346
1347         this.opkg = {
1348                 updateLists: _luci2.rpc.declare({
1349                         object: 'luci2.opkg',
1350                         method: 'update',
1351                         expect: { '': { } }
1352                 }),
1353
1354                 _allPackages: _luci2.rpc.declare({
1355                         object: 'luci2.opkg',
1356                         method: 'list',
1357                         params: [ 'offset', 'limit', 'pattern' ],
1358                         expect: { '': { } }
1359                 }),
1360
1361                 _installedPackages: _luci2.rpc.declare({
1362                         object: 'luci2.opkg',
1363                         method: 'list_installed',
1364                         params: [ 'offset', 'limit', 'pattern' ],
1365                         expect: { '': { } }
1366                 }),
1367
1368                 _findPackages: _luci2.rpc.declare({
1369                         object: 'luci2.opkg',
1370                         method: 'find',
1371                         params: [ 'offset', 'limit', 'pattern' ],
1372                         expect: { '': { } }
1373                 }),
1374
1375                 _fetchPackages: function(action, offset, limit, pattern)
1376                 {
1377                         var packages = [ ];
1378
1379                         return action(offset, limit, pattern).then(function(list) {
1380                                 if (!list.total || !list.packages)
1381                                         return { length: 0, total: 0 };
1382
1383                                 packages.push.apply(packages, list.packages);
1384                                 packages.total = list.total;
1385
1386                                 if (limit <= 0)
1387                                         limit = list.total;
1388
1389                                 if (packages.length >= limit)
1390                                         return packages;
1391
1392                                 _luci2.rpc.batch();
1393
1394                                 for (var i = offset + packages.length; i < limit; i += 100)
1395                                         action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1396
1397                                 return _luci2.rpc.flush();
1398                         }).then(function(lists) {
1399                                 for (var i = 0; i < lists.length; i++)
1400                                 {
1401                                         if (!lists[i].total || !lists[i].packages)
1402                                                 continue;
1403
1404                                         packages.push.apply(packages, lists[i].packages);
1405                                         packages.total = lists[i].total;
1406                                 }
1407
1408                                 return packages;
1409                         });
1410                 },
1411
1412                 listPackages: function(offset, limit, pattern)
1413                 {
1414                         return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1415                 },
1416
1417                 installedPackages: function(offset, limit, pattern)
1418                 {
1419                         return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1420                 },
1421
1422                 findPackages: function(offset, limit, pattern)
1423                 {
1424                         return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1425                 },
1426
1427                 installPackage: _luci2.rpc.declare({
1428                         object: 'luci2.opkg',
1429                         method: 'install',
1430                         params: [ 'package' ],
1431                         expect: { '': { } }
1432                 }),
1433
1434                 removePackage: _luci2.rpc.declare({
1435                         object: 'luci2.opkg',
1436                         method: 'remove',
1437                         params: [ 'package' ],
1438                         expect: { '': { } }
1439                 }),
1440
1441                 getConfig: _luci2.rpc.declare({
1442                         object: 'luci2.opkg',
1443                         method: 'config_get',
1444                         expect: { config: '' }
1445                 }),
1446
1447                 setConfig: _luci2.rpc.declare({
1448                         object: 'luci2.opkg',
1449                         method: 'config_set',
1450                         params: [ 'data' ]
1451                 })
1452         };
1453
1454         this.session = {
1455
1456                 login: _luci2.rpc.declare({
1457                         object: 'session',
1458                         method: 'login',
1459                         params: [ 'username', 'password' ],
1460                         expect: { '': { } }
1461                 }),
1462
1463                 access: _luci2.rpc.declare({
1464                         object: 'session',
1465                         method: 'access',
1466                         params: [ 'scope', 'object', 'function' ],
1467                         expect: { access: false }
1468                 }),
1469
1470                 isAlive: function()
1471                 {
1472                         return _luci2.session.access('ubus', 'session', 'access');
1473                 },
1474
1475                 startHeartbeat: function()
1476                 {
1477                         this._hearbeatInterval = window.setInterval(function() {
1478                                 _luci2.session.isAlive().then(function(alive) {
1479                                         if (!alive)
1480                                         {
1481                                                 _luci2.session.stopHeartbeat();
1482                                                 _luci2.ui.login(true);
1483                                         }
1484
1485                                 });
1486                         }, _luci2.globals.timeout * 2);
1487                 },
1488
1489                 stopHeartbeat: function()
1490                 {
1491                         if (typeof(this._hearbeatInterval) != 'undefined')
1492                         {
1493                                 window.clearInterval(this._hearbeatInterval);
1494                                 delete this._hearbeatInterval;
1495                         }
1496                 }
1497         };
1498
1499         this.ui = {
1500
1501                 saveScrollTop: function()
1502                 {
1503                         this._scroll_top = $(document).scrollTop();
1504                 },
1505
1506                 restoreScrollTop: function()
1507                 {
1508                         if (typeof(this._scroll_top) == 'undefined')
1509                                 return;
1510
1511                         $(document).scrollTop(this._scroll_top);
1512
1513                         delete this._scroll_top;
1514                 },
1515
1516                 loading: function(enable)
1517                 {
1518                         var win = $(window);
1519                         var body = $('body');
1520
1521                         var state = _luci2.ui._loading || (_luci2.ui._loading = {
1522                                 modal: $('<div />')
1523                                         .addClass('cbi-modal-loader')
1524                                         .append($('<div />').text(_luci2.tr('Loading data...')))
1525                                         .appendTo(body)
1526                         });
1527
1528                         if (enable)
1529                         {
1530                                 body.css('overflow', 'hidden');
1531                                 body.css('padding', 0);
1532                                 body.css('width', win.width());
1533                                 body.css('height', win.height());
1534                                 state.modal.css('width', win.width());
1535                                 state.modal.css('height', win.height());
1536                                 state.modal.show();
1537                         }
1538                         else
1539                         {
1540                                 state.modal.hide();
1541                                 body.css('overflow', '');
1542                                 body.css('padding', '');
1543                                 body.css('width', '');
1544                                 body.css('height', '');
1545                         }
1546                 },
1547
1548                 dialog: function(title, content, options)
1549                 {
1550                         var win = $(window);
1551                         var body = $('body');
1552
1553                         var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1554                                 dialog: $('<div />')
1555                                         .addClass('cbi-modal-dialog')
1556                                         .append($('<div />')
1557                                                 .append($('<div />')
1558                                                         .addClass('cbi-modal-dialog-header'))
1559                                                 .append($('<div />')
1560                                                         .addClass('cbi-modal-dialog-body'))
1561                                                 .append($('<div />')
1562                                                         .addClass('cbi-modal-dialog-footer')
1563                                                         .append($('<button />')
1564                                                                 .addClass('cbi-button')
1565                                                                 .text(_luci2.tr('Close'))
1566                                                                 .click(function() {
1567                                                                         $('body')
1568                                                                                 .css('overflow', '')
1569                                                                                 .css('padding', '')
1570                                                                                 .css('width', '')
1571                                                                                 .css('height', '');
1572
1573                                                                         $(this).parent().parent().parent().hide();
1574                                                                 }))))
1575                                         .appendTo(body)
1576                         });
1577
1578                         if (typeof(options) != 'object')
1579                                 options = { };
1580
1581                         if (title === false)
1582                         {
1583                                 body
1584                                         .css('overflow', '')
1585                                         .css('padding', '')
1586                                         .css('width', '')
1587                                         .css('height', '');
1588
1589                                 state.dialog.hide();
1590
1591                                 return;
1592                         }
1593
1594                         var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1595                         var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1596
1597                         ftr.empty();
1598
1599                         if (options.style == 'confirm')
1600                         {
1601                                 ftr.append($('<button />')
1602                                         .addClass('cbi-button')
1603                                         .text(_luci2.tr('Ok'))
1604                                         .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1605
1606                                 ftr.append($('<button />')
1607                                         .addClass('cbi-button')
1608                                         .text(_luci2.tr('Cancel'))
1609                                         .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1610                         }
1611                         else if (options.style == 'close')
1612                         {
1613                                 ftr.append($('<button />')
1614                                         .addClass('cbi-button')
1615                                         .text(_luci2.tr('Close'))
1616                                         .click(options.close || function() { _luci2.ui.dialog(false) }));
1617                         }
1618                         else if (options.style == 'wait')
1619                         {
1620                                 ftr.append($('<button />')
1621                                         .addClass('cbi-button')
1622                                         .text(_luci2.tr('Close'))
1623                                         .attr('disabled', true));
1624                         }
1625
1626                         state.dialog.find('div.cbi-modal-dialog-header').text(title);
1627                         state.dialog.show();
1628
1629                         cnt
1630                                 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1631                                 .empty()
1632                                 .append(content);
1633
1634                         state.dialog.children()
1635                                 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1636
1637                         body.css('overflow', 'hidden');
1638                         body.css('padding', 0);
1639                         body.css('width', win.width());
1640                         body.css('height', win.height());
1641                         state.dialog.css('width', win.width());
1642                         state.dialog.css('height', win.height());
1643                 },
1644
1645                 upload: function(title, content, options)
1646                 {
1647                         var state = _luci2.ui._upload || (_luci2.ui._upload = {
1648                                 form: $('<form />')
1649                                         .attr('method', 'post')
1650                                         .attr('action', '/cgi-bin/luci-upload')
1651                                         .attr('enctype', 'multipart/form-data')
1652                                         .attr('target', 'cbi-fileupload-frame')
1653                                         .append($('<p />'))
1654                                         .append($('<input />')
1655                                                 .attr('type', 'hidden')
1656                                                 .attr('name', 'sessionid'))
1657                                         .append($('<input />')
1658                                                 .attr('type', 'hidden')
1659                                                 .attr('name', 'filename'))
1660                                         .append($('<input />')
1661                                                 .attr('type', 'file')
1662                                                 .attr('name', 'filedata')
1663                                                 .addClass('cbi-input-file'))
1664                                         .append($('<div />')
1665                                                 .css('width', '100%')
1666                                                 .addClass('progressbar')
1667                                                 .addClass('intermediate')
1668                                                 .append($('<div />')
1669                                                         .css('width', '100%')))
1670                                         .append($('<iframe />')
1671                                                 .attr('name', 'cbi-fileupload-frame')
1672                                                 .css('width', '1px')
1673                                                 .css('height', '1px')
1674                                                 .css('visibility', 'hidden')),
1675
1676                                 finish_cb: function(ev) {
1677                                         $(this).off('load');
1678
1679                                         var body = (this.contentDocument || this.contentWindow.document).body;
1680                                         if (body.firstChild.tagName.toLowerCase() == 'pre')
1681                                                 body = body.firstChild;
1682
1683                                         var json;
1684                                         try {
1685                                                 json = $.parseJSON(body.innerHTML);
1686                                         } catch(e) {
1687                                                 json = {
1688                                                         message: _luci2.tr('Invalid server response received'),
1689                                                         error: [ -1, _luci2.tr('Invalid data') ]
1690                                                 };
1691                                         };
1692
1693                                         if (json.error)
1694                                         {
1695                                                 L.ui.dialog(L.tr('File upload'), [
1696                                                         $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1697                                                         $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1698                                                         $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1699                                                 ], { style: 'close' });
1700                                         }
1701                                         else if (typeof(state.success_cb) == 'function')
1702                                         {
1703                                                 state.success_cb(json);
1704                                         }
1705                                 },
1706
1707                                 confirm_cb: function() {
1708                                         var f = state.form.find('.cbi-input-file');
1709                                         var b = state.form.find('.progressbar');
1710                                         var p = state.form.find('p');
1711
1712                                         if (!f.val())
1713                                                 return;
1714
1715                                         state.form.find('iframe').on('load', state.finish_cb);
1716                                         state.form.submit();
1717
1718                                         f.hide();
1719                                         b.show();
1720                                         p.text(_luci2.tr('File upload in progress …'));
1721
1722                                         state.form.parent().parent().find('button').prop('disabled', true);
1723                                 }
1724                         });
1725
1726                         state.form.find('.progressbar').hide();
1727                         state.form.find('.cbi-input-file').val('').show();
1728                         state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1729
1730                         state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1731                         state.form.find('[name=filename]').val(options.filename);
1732
1733                         state.success_cb = options.success;
1734
1735                         _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1736                                 style: 'confirm',
1737                                 confirm: state.confirm_cb
1738                         });
1739                 },
1740
1741                 reconnect: function()
1742                 {
1743                         var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1744                         var ports     = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1745                         var address   = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1746                         var images    = $();
1747                         var interval, timeout;
1748
1749                         _luci2.ui.dialog(
1750                                 _luci2.tr('Waiting for device'), [
1751                                         $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1752                                         $('<div />')
1753                                                 .css('width', '100%')
1754                                                 .addClass('progressbar')
1755                                                 .addClass('intermediate')
1756                                                 .append($('<div />')
1757                                                         .css('width', '100%'))
1758                                 ], { style: 'wait' }
1759                         );
1760
1761                         for (var i = 0; i < protocols.length; i++)
1762                                 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1763
1764                         //_luci2.network.getNetworkStatus(function(s) {
1765                         //      for (var i = 0; i < protocols.length; i++)
1766                         //      {
1767                         //              for (var j = 0; j < s.length; j++)
1768                         //              {
1769                         //                      for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1770                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1771                         //
1772                         //                      for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1773                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1774                         //              }
1775                         //      }
1776                         //}).then(function() {
1777                                 images.on('load', function() {
1778                                         var url = this.getAttribute('url');
1779                                         _luci2.session.isAlive().then(function(access) {
1780                                                 if (access)
1781                                                 {
1782                                                         window.clearTimeout(timeout);
1783                                                         window.clearInterval(interval);
1784                                                         _luci2.ui.dialog(false);
1785                                                         images = null;
1786                                                 }
1787                                                 else
1788                                                 {
1789                                                         location.href = url;
1790                                                 }
1791                                         });
1792                                 });
1793
1794                                 interval = window.setInterval(function() {
1795                                         images.each(function() {
1796                                                 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1797                                         });
1798                                 }, 5000);
1799
1800                                 timeout = window.setTimeout(function() {
1801                                         window.clearInterval(interval);
1802                                         images.off('load');
1803
1804                                         _luci2.ui.dialog(
1805                                                 _luci2.tr('Device not responding'),
1806                                                 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1807                                                 { style: 'close' }
1808                                         );
1809                                 }, 180000);
1810                         //});
1811                 },
1812
1813                 login: function(invalid)
1814                 {
1815                         var state = _luci2.ui._login || (_luci2.ui._login = {
1816                                 form: $('<form />')
1817                                         .attr('target', '')
1818                                         .attr('method', 'post')
1819                                         .append($('<p />')
1820                                                 .addClass('alert-message')
1821                                                 .text(_luci2.tr('Wrong username or password given!')))
1822                                         .append($('<p />')
1823                                                 .append($('<label />')
1824                                                         .text(_luci2.tr('Username'))
1825                                                         .append($('<br />'))
1826                                                         .append($('<input />')
1827                                                                 .attr('type', 'text')
1828                                                                 .attr('name', 'username')
1829                                                                 .attr('value', 'root')
1830                                                                 .addClass('cbi-input-text')
1831                                                                 .keypress(function(ev) {
1832                                                                         if (ev.which == 10 || ev.which == 13)
1833                                                                                 state.confirm_cb();
1834                                                                 }))))
1835                                         .append($('<p />')
1836                                                 .append($('<label />')
1837                                                         .text(_luci2.tr('Password'))
1838                                                         .append($('<br />'))
1839                                                         .append($('<input />')
1840                                                                 .attr('type', 'password')
1841                                                                 .attr('name', 'password')
1842                                                                 .addClass('cbi-input-password')
1843                                                                 .keypress(function(ev) {
1844                                                                         if (ev.which == 10 || ev.which == 13)
1845                                                                                 state.confirm_cb();
1846                                                                 }))))
1847                                         .append($('<p />')
1848                                                 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1849
1850                                 response_cb: function(response) {
1851                                         if (!response.ubus_rpc_session)
1852                                         {
1853                                                 _luci2.ui.login(true);
1854                                         }
1855                                         else
1856                                         {
1857                                                 _luci2.globals.sid = response.ubus_rpc_session;
1858                                                 _luci2.setHash('id', _luci2.globals.sid);
1859                                                 _luci2.session.startHeartbeat();
1860                                                 _luci2.ui.dialog(false);
1861                                                 state.deferred.resolve();
1862                                         }
1863                                 },
1864
1865                                 confirm_cb: function() {
1866                                         var u = state.form.find('[name=username]').val();
1867                                         var p = state.form.find('[name=password]').val();
1868
1869                                         if (!u)
1870                                                 return;
1871
1872                                         _luci2.ui.dialog(
1873                                                 _luci2.tr('Logging in'), [
1874                                                         $('<p />').text(_luci2.tr('Log in in progress …')),
1875                                                         $('<div />')
1876                                                                 .css('width', '100%')
1877                                                                 .addClass('progressbar')
1878                                                                 .addClass('intermediate')
1879                                                                 .append($('<div />')
1880                                                                         .css('width', '100%'))
1881                                                 ], { style: 'wait' }
1882                                         );
1883
1884                                         _luci2.globals.sid = '00000000000000000000000000000000';
1885                                         _luci2.session.login(u, p).then(state.response_cb);
1886                                 }
1887                         });
1888
1889                         if (!state.deferred || state.deferred.state() != 'pending')
1890                                 state.deferred = $.Deferred();
1891
1892                         /* try to find sid from hash */
1893                         var sid = _luci2.getHash('id');
1894                         if (sid && sid.match(/^[a-f0-9]{32}$/))
1895                         {
1896                                 _luci2.globals.sid = sid;
1897                                 _luci2.session.isAlive().then(function(access) {
1898                                         if (access)
1899                                         {
1900                                                 _luci2.session.startHeartbeat();
1901                                                 state.deferred.resolve();
1902                                         }
1903                                         else
1904                                         {
1905                                                 _luci2.setHash('id', undefined);
1906                                                 _luci2.ui.login();
1907                                         }
1908                                 });
1909
1910                                 return state.deferred;
1911                         }
1912
1913                         if (invalid)
1914                                 state.form.find('.alert-message').show();
1915                         else
1916                                 state.form.find('.alert-message').hide();
1917
1918                         _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
1919                                 style: 'confirm',
1920                                 confirm: state.confirm_cb
1921                         });
1922
1923                         state.form.find('[name=password]').focus();
1924
1925                         return state.deferred;
1926                 },
1927
1928                 cryptPassword: _luci2.rpc.declare({
1929                         object: 'luci2.ui',
1930                         method: 'crypt',
1931                         params: [ 'data' ],
1932                         expect: { crypt: '' }
1933                 }),
1934
1935
1936                 _acl_merge_scope: function(acl_scope, scope)
1937                 {
1938                         if ($.isArray(scope))
1939                         {
1940                                 for (var i = 0; i < scope.length; i++)
1941                                         acl_scope[scope[i]] = true;
1942                         }
1943                         else if ($.isPlainObject(scope))
1944                         {
1945                                 for (var object_name in scope)
1946                                 {
1947                                         if (!$.isArray(scope[object_name]))
1948                                                 continue;
1949
1950                                         var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
1951
1952                                         for (var i = 0; i < scope[object_name].length; i++)
1953                                                 acl_object[scope[object_name][i]] = true;
1954                                 }
1955                         }
1956                 },
1957
1958                 _acl_merge_permission: function(acl_perm, perm)
1959                 {
1960                         if ($.isPlainObject(perm))
1961                         {
1962                                 for (var scope_name in perm)
1963                                 {
1964                                         var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
1965                                         this._acl_merge_scope(acl_scope, perm[scope_name]);
1966                                 }
1967                         }
1968                 },
1969
1970                 _acl_merge_group: function(acl_group, group)
1971                 {
1972                         if ($.isPlainObject(group))
1973                         {
1974                                 if (!acl_group.description)
1975                                         acl_group.description = group.description;
1976
1977                                 if (group.read)
1978                                 {
1979                                         var acl_perm = acl_group.read || (acl_group.read = { });
1980                                         this._acl_merge_permission(acl_perm, group.read);
1981                                 }
1982
1983                                 if (group.write)
1984                                 {
1985                                         var acl_perm = acl_group.write || (acl_group.write = { });
1986                                         this._acl_merge_permission(acl_perm, group.write);
1987                                 }
1988                         }
1989                 },
1990
1991                 _acl_merge_tree: function(acl_tree, tree)
1992                 {
1993                         if ($.isPlainObject(tree))
1994                         {
1995                                 for (var group_name in tree)
1996                                 {
1997                                         var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
1998                                         this._acl_merge_group(acl_group, tree[group_name]);
1999                                 }
2000                         }
2001                 },
2002
2003                 listAvailableACLs: _luci2.rpc.declare({
2004                         object: 'luci2.ui',
2005                         method: 'acls',
2006                         expect: { acls: [ ] },
2007                         filter: function(trees) {
2008                                 var acl_tree = { };
2009                                 for (var i = 0; i < trees.length; i++)
2010                                         _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2011                                 return acl_tree;
2012                         }
2013                 }),
2014
2015                 renderMainMenu: _luci2.rpc.declare({
2016                         object: 'luci2.ui',
2017                         method: 'menu',
2018                         expect: { menu: { } },
2019                         filter: function(entries) {
2020                                 _luci2.globals.mainMenu = new _luci2.ui.menu();
2021                                 _luci2.globals.mainMenu.entries(entries);
2022
2023                                 $('#mainmenu')
2024                                         .empty()
2025                                         .append(_luci2.globals.mainMenu.render(0, 1));
2026                         }
2027                 }),
2028
2029                 renderViewMenu: function()
2030                 {
2031                         $('#viewmenu')
2032                                 .empty()
2033                                 .append(_luci2.globals.mainMenu.render(2, 900));
2034                 },
2035
2036                 renderView: function(node)
2037                 {
2038                         var name = node.view.split(/\//).join('.');
2039
2040                         _luci2.ui.renderViewMenu();
2041
2042                         if (!_luci2._views)
2043                                 _luci2._views = { };
2044
2045                         _luci2.setHash('view', node.view);
2046
2047                         if (_luci2._views[name] instanceof _luci2.ui.view)
2048                                 return _luci2._views[name].render();
2049
2050                         var url = _luci2.globals.resource + '/view/' + name + '.js';
2051
2052                         return $.ajax(url, {
2053                                 method: 'GET',
2054                                 cache: true,
2055                                 dataType: 'text'
2056                         }).then(function(data) {
2057                                 try {
2058                                         var viewConstructorSource = (
2059                                                 '(function(L, $) { ' +
2060                                                         'return %s' +
2061                                                 '})(_luci2, $);\n\n' +
2062                                                 '//@ sourceURL=%s'
2063                                         ).format(data, url);
2064
2065                                         var viewConstructor = eval(viewConstructorSource);
2066
2067                                         _luci2._views[name] = new viewConstructor({
2068                                                 name: name,
2069                                                 acls: node.write || { }
2070                                         });
2071
2072                                         return _luci2._views[name].render();
2073                                 }
2074                                 catch(e) {
2075                                         alert('Unable to instantiate view "%s": %s'.format(url, e));
2076                                 };
2077
2078                                 return $.Deferred().resolve();
2079                         });
2080                 },
2081
2082                 updateHostname: function()
2083                 {
2084                         return _luci2.system.getBoardInfo().then(function(info) {
2085                                 if (info.hostname)
2086                                         $('#hostname').text(info.hostname);
2087                         });
2088                 },
2089
2090                 updateChanges: function()
2091                 {
2092                         return _luci2.uci.changes().then(function(changes) {
2093                                 var n = 0;
2094                                 var html = '';
2095
2096                                 for (var config in changes)
2097                                 {
2098                                         var log = [ ];
2099
2100                                         for (var i = 0; i < changes[config].length; i++)
2101                                         {
2102                                                 var c = changes[config][i];
2103
2104                                                 switch (c[0])
2105                                                 {
2106                                                 case 'order':
2107                                                         break;
2108
2109                                                 case 'remove':
2110                                                         if (c.length < 3)
2111                                                                 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2112                                                         else
2113                                                                 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2114                                                         break;
2115
2116                                                 case 'rename':
2117                                                         if (c.length < 4)
2118                                                                 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2119                                                         else
2120                                                                 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2121                                                         break;
2122
2123                                                 case 'add':
2124                                                         log.push('uci add %s (= <ins><strong>%s</strong></ins>)'.format(config, c[1]));
2125                                                         break;
2126
2127                                                 case 'list-add':
2128                                                         log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2129                                                         break;
2130
2131                                                 case 'list-del':
2132                                                         log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2133                                                         break;
2134
2135                                                 case 'set':
2136                                                         if (c.length < 4)
2137                                                                 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2138                                                         else
2139                                                                 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2140                                                         break;
2141                                                 }
2142                                         }
2143
2144                                         html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2145                                         n += changes[config].length;
2146                                 }
2147
2148                                 if (n > 0)
2149                                         $('#changes')
2150                                                 .empty()
2151                                                 .show()
2152                                                 .append($('<a />')
2153                                                         .attr('href', '#')
2154                                                         .addClass('label')
2155                                                         .addClass('notice')
2156                                                         .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2157                                                         .click(function(ev) {
2158                                                                 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2159                                                                 ev.preventDefault();
2160                                                         }));
2161                                 else
2162                                         $('#changes')
2163                                                 .hide();
2164                         });
2165                 },
2166
2167                 init: function()
2168                 {
2169                         _luci2.ui.loading(true);
2170
2171                         $.when(
2172                                 _luci2.ui.updateHostname(),
2173                                 _luci2.ui.updateChanges(),
2174                                 _luci2.ui.renderMainMenu()
2175                         ).then(function() {
2176                                 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2177                                         _luci2.ui.loading(false);
2178                                 })
2179                         });
2180                 }
2181         };
2182
2183         var AbstractWidget = Class.extend({
2184                 i18n: function(text) {
2185                         return text;
2186                 },
2187
2188                 toString: function() {
2189                         var x = document.createElement('div');
2190                                 x.appendChild(this.render());
2191
2192                         return x.innerHTML;
2193                 },
2194
2195                 insertInto: function(id) {
2196                         return $(id).empty().append(this.render());
2197                 }
2198         });
2199
2200         this.ui.view = AbstractWidget.extend({
2201                 _fetch_template: function()
2202                 {
2203                         return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2204                                 method: 'GET',
2205                                 cache: true,
2206                                 dataType: 'text',
2207                                 success: function(data) {
2208                                         data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2209                                                 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2210                                                 switch (p1)
2211                                                 {
2212                                                 case '#':
2213                                                         return '';
2214
2215                                                 case ':':
2216                                                         return _luci2.tr(p2);
2217
2218                                                 case '=':
2219                                                         return _luci2.globals[p2] || '';
2220
2221                                                 default:
2222                                                         return '(?' + match + ')';
2223                                                 }
2224                                         });
2225
2226                                         $('#maincontent').append(data);
2227                                 }
2228                         });
2229                 },
2230
2231                 execute: function()
2232                 {
2233                         throw "Not implemented";
2234                 },
2235
2236                 render: function()
2237                 {
2238                         var container = $('#maincontent');
2239
2240                         container.empty();
2241
2242                         if (this.title)
2243                                 container.append($('<h2 />').append(this.title));
2244
2245                         if (this.description)
2246                                 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2247
2248                         var self = this;
2249                         return this._fetch_template().then(function() {
2250                                 return _luci2.deferrable(self.execute());
2251                         });
2252                 }
2253         });
2254
2255         this.ui.menu = AbstractWidget.extend({
2256                 init: function() {
2257                         this._nodes = { };
2258                 },
2259
2260                 entries: function(entries)
2261                 {
2262                         for (var entry in entries)
2263                         {
2264                                 var path = entry.split(/\//);
2265                                 var node = this._nodes;
2266
2267                                 for (i = 0; i < path.length; i++)
2268                                 {
2269                                         if (!node.childs)
2270                                                 node.childs = { };
2271
2272                                         if (!node.childs[path[i]])
2273                                                 node.childs[path[i]] = { };
2274
2275                                         node = node.childs[path[i]];
2276                                 }
2277
2278                                 $.extend(node, entries[entry]);
2279                         }
2280                 },
2281
2282                 _indexcmp: function(a, b)
2283                 {
2284                         var x = a.index || 0;
2285                         var y = b.index || 0;
2286                         return (x - y);
2287                 },
2288
2289                 firstChildView: function(node)
2290                 {
2291                         if (node.view)
2292                                 return node;
2293
2294                         var nodes = [ ];
2295                         for (var child in (node.childs || { }))
2296                                 nodes.push(node.childs[child]);
2297
2298                         nodes.sort(this._indexcmp);
2299
2300                         for (var i = 0; i < nodes.length; i++)
2301                         {
2302                                 var child = this.firstChildView(nodes[i]);
2303                                 if (child)
2304                                 {
2305                                         $.extend(node, child);
2306                                         return node;
2307                                 }
2308                         }
2309
2310                         return undefined;
2311                 },
2312
2313                 _onclick: function(ev)
2314                 {
2315                         _luci2.ui.loading(true);
2316                         _luci2.ui.renderView(ev.data).then(function() {
2317                                 _luci2.ui.loading(false);
2318                         });
2319
2320                         ev.preventDefault();
2321                         this.blur();
2322                 },
2323
2324                 _render: function(childs, level, min, max)
2325                 {
2326                         var nodes = [ ];
2327                         for (var node in childs)
2328                         {
2329                                 var child = this.firstChildView(childs[node]);
2330                                 if (child)
2331                                         nodes.push(childs[node]);
2332                         }
2333
2334                         nodes.sort(this._indexcmp);
2335
2336                         var list = $('<ul />');
2337
2338                         if (level == 0)
2339                                 list.addClass('nav');
2340                         else if (level == 1)
2341                                 list.addClass('dropdown-menu');
2342
2343                         for (var i = 0; i < nodes.length; i++)
2344                         {
2345                                 if (!_luci2.globals.defaultNode)
2346                                 {
2347                                         var v = _luci2.getHash('view');
2348                                         if (!v || v == nodes[i].view)
2349                                                 _luci2.globals.defaultNode = nodes[i];
2350                                 }
2351
2352                                 var item = $('<li />')
2353                                         .append($('<a />')
2354                                                 .attr('href', '#')
2355                                                 .text(_luci2.tr(nodes[i].title))
2356                                                 .click(nodes[i], this._onclick))
2357                                         .appendTo(list);
2358
2359                                 if (nodes[i].childs && level < max)
2360                                 {
2361                                         item.addClass('dropdown');
2362                                         item.find('a').addClass('menu');
2363                                         item.append(this._render(nodes[i].childs, level + 1));
2364                                 }
2365                         }
2366
2367                         return list.get(0);
2368                 },
2369
2370                 render: function(min, max)
2371                 {
2372                         var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2373                         return this._render(top.childs, 0, min, max);
2374                 },
2375
2376                 getNode: function(path, max)
2377                 {
2378                         var p = path.split(/\//);
2379                         var n = this._nodes;
2380
2381                         if (typeof(max) == 'undefined')
2382                                 max = p.length;
2383
2384                         for (var i = 0; i < max; i++)
2385                         {
2386                                 if (!n.childs[p[i]])
2387                                         return undefined;
2388
2389                                 n = n.childs[p[i]];
2390                         }
2391
2392                         return n;
2393                 }
2394         });
2395
2396         this.ui.table = AbstractWidget.extend({
2397                 init: function()
2398                 {
2399                         this._rows = [ ];
2400                 },
2401
2402                 row: function(values)
2403                 {
2404                         if ($.isArray(values))
2405                         {
2406                                 this._rows.push(values);
2407                         }
2408                         else if ($.isPlainObject(values))
2409                         {
2410                                 var v = [ ];
2411                                 for (var i = 0; i < this.options.columns.length; i++)
2412                                 {
2413                                         var col = this.options.columns[i];
2414
2415                                         if (typeof col.key == 'string')
2416                                                 v.push(values[col.key]);
2417                                         else
2418                                                 v.push(null);
2419                                 }
2420                                 this._rows.push(v);
2421                         }
2422                 },
2423
2424                 rows: function(rows)
2425                 {
2426                         for (var i = 0; i < rows.length; i++)
2427                                 this.row(rows[i]);
2428                 },
2429
2430                 render: function(id)
2431                 {
2432                         var fieldset = document.createElement('fieldset');
2433                                 fieldset.className = 'cbi-section';
2434
2435                         if (this.options.caption)
2436                         {
2437                                 var legend = document.createElement('legend');
2438                                 $(legend).append(this.options.caption);
2439                                 fieldset.appendChild(legend);
2440                         }
2441
2442                         var table = document.createElement('table');
2443                                 table.className = 'cbi-section-table';
2444
2445                         var has_caption = false;
2446                         var has_description = false;
2447
2448                         for (var i = 0; i < this.options.columns.length; i++)
2449                                 if (this.options.columns[i].caption)
2450                                 {
2451                                         has_caption = true;
2452                                         break;
2453                                 }
2454                                 else if (this.options.columns[i].description)
2455                                 {
2456                                         has_description = true;
2457                                         break;
2458                                 }
2459
2460                         if (has_caption)
2461                         {
2462                                 var tr = table.insertRow(-1);
2463                                         tr.className = 'cbi-section-table-titles';
2464
2465                                 for (var i = 0; i < this.options.columns.length; i++)
2466                                 {
2467                                         var col = this.options.columns[i];
2468                                         var th = document.createElement('th');
2469                                                 th.className = 'cbi-section-table-cell';
2470
2471                                         tr.appendChild(th);
2472
2473                                         if (col.width)
2474                                                 th.style.width = col.width;
2475
2476                                         if (col.align)
2477                                                 th.style.textAlign = col.align;
2478
2479                                         if (col.caption)
2480                                                 $(th).append(col.caption);
2481                                 }
2482                         }
2483
2484                         if (has_description)
2485                         {
2486                                 var tr = table.insertRow(-1);
2487                                         tr.className = 'cbi-section-table-descr';
2488
2489                                 for (var i = 0; i < this.options.columns.length; i++)
2490                                 {
2491                                         var col = this.options.columns[i];
2492                                         var th = document.createElement('th');
2493                                                 th.className = 'cbi-section-table-cell';
2494
2495                                         tr.appendChild(th);
2496
2497                                         if (col.width)
2498                                                 th.style.width = col.width;
2499
2500                                         if (col.align)
2501                                                 th.style.textAlign = col.align;
2502
2503                                         if (col.description)
2504                                                 $(th).append(col.description);
2505                                 }
2506                         }
2507
2508                         if (this._rows.length == 0)
2509                         {
2510                                 if (this.options.placeholder)
2511                                 {
2512                                         var tr = table.insertRow(-1);
2513                                         var td = tr.insertCell(-1);
2514                                                 td.className = 'cbi-section-table-cell';
2515
2516                                         td.colSpan = this.options.columns.length;
2517                                         $(td).append(this.options.placeholder);
2518                                 }
2519                         }
2520                         else
2521                         {
2522                                 for (var i = 0; i < this._rows.length; i++)
2523                                 {
2524                                         var tr = table.insertRow(-1);
2525
2526                                         for (var j = 0; j < this.options.columns.length; j++)
2527                                         {
2528                                                 var col = this.options.columns[j];
2529                                                 var td = tr.insertCell(-1);
2530
2531                                                 var val = this._rows[i][j];
2532
2533                                                 if (typeof(val) == 'undefined')
2534                                                         val = col.placeholder;
2535
2536                                                 if (typeof(val) == 'undefined')
2537                                                         val = '';
2538
2539                                                 if (col.width)
2540                                                         td.style.width = col.width;
2541
2542                                                 if (col.align)
2543                                                         td.style.textAlign = col.align;
2544
2545                                                 if (typeof col.format == 'string')
2546                                                         $(td).append(col.format.format(val));
2547                                                 else if (typeof col.format == 'function')
2548                                                         $(td).append(col.format(val, i));
2549                                                 else
2550                                                         $(td).append(val);
2551                                         }
2552                                 }
2553                         }
2554
2555                         this._rows = [ ];
2556                         fieldset.appendChild(table);
2557
2558                         return fieldset;
2559                 }
2560         });
2561
2562         this.ui.progress = AbstractWidget.extend({
2563                 render: function()
2564                 {
2565                         var vn = parseInt(this.options.value) || 0;
2566                         var mn = parseInt(this.options.max) || 100;
2567                         var pc = Math.floor((100 / mn) * vn);
2568
2569                         var bar = document.createElement('div');
2570                                 bar.className = 'progressbar';
2571
2572                         bar.appendChild(document.createElement('div'));
2573                         bar.lastChild.appendChild(document.createElement('div'));
2574                         bar.lastChild.style.width = pc + '%';
2575
2576                         if (typeof(this.options.format) == 'string')
2577                                 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2578                         else if (typeof(this.options.format) == 'function')
2579                                 $(bar.lastChild.lastChild).append(this.options.format(pc));
2580                         else
2581                                 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2582
2583                         return bar;
2584                 }
2585         });
2586
2587         this.ui.devicebadge = AbstractWidget.extend({
2588                 render: function()
2589                 {
2590                         var dev = this.options.l3_device || this.options.device || '?';
2591
2592                         var span = document.createElement('span');
2593                                 span.className = 'ifacebadge';
2594
2595                         if (typeof(this.options.signal) == 'number' ||
2596                                 typeof(this.options.noise) == 'number')
2597                         {
2598                                 var r = 'none';
2599                                 if (typeof(this.options.signal) != 'undefined' &&
2600                                         typeof(this.options.noise) != 'undefined')
2601                                 {
2602                                         var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2603                                         if (q < 1)
2604                                                 r = '0';
2605                                         else if (q < 2)
2606                                                 r = '0-25';
2607                                         else if (q < 3)
2608                                                 r = '25-50';
2609                                         else if (q < 4)
2610                                                 r = '50-75';
2611                                         else
2612                                                 r = '75-100';
2613                                 }
2614
2615                                 span.appendChild(document.createElement('img'));
2616                                 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2617
2618                                 if (r == 'none')