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