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