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