2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
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
10 http://www.apache.org/licenses/LICENSE-2.0
13 String.prototype.format = function()
15 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
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;
29 while ((a = re.exec(str)) != null)
32 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33 var pPrecision = a[6], pType = a[7];
43 if (numSubstitutions < arguments.length)
45 var param = arguments[numSubstitutions++];
48 if (pPad && pPad.substr(0,1) == "'")
49 pad = leftpart.substr(1,1);
53 var justifyRight = true;
54 if (pJustify && pJustify === "-")
59 minLength = parseInt(pMinLength);
62 if (pPrecision && pType == 'f')
63 precision = parseInt(pPrecision.substring(1));
70 subst = (parseInt(param) || 0).toString(2);
74 subst = String.fromCharCode(parseInt(param) || 0);
78 subst = (parseInt(param) || 0);
82 subst = Math.abs(parseInt(param) || 0);
86 subst = (precision > -1)
87 ? ((parseFloat(param) || 0.0)).toFixed(precision)
88 : (parseFloat(param) || 0.0);
92 subst = (parseInt(param) || 0).toString(8);
100 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
104 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
108 subst = esc(param, html_esc);
112 subst = esc(param, quot_esc);
116 subst = String.serialize(param);
123 var ts = (param || 0);
126 tm = Math.floor(ts / 60);
131 th = Math.floor(tm / 60);
136 td = Math.floor(th / 24);
141 ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142 : '%dh %dm %ds'.format(th, tm, ts);
147 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
151 var val = parseFloat(param || 0);
152 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i = 0; (i < units.length) && (val > mf); i++)
157 subst = val.toFixed(pr) + ' ' + units[i];
161 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
163 if (minLength > 0 && pad.length > 0)
164 for (var i = 0; i < (minLength - subst.length); i++)
165 subst = justifyRight ? (pad + subst) : (subst + pad);
169 out += leftpart + subst;
170 str = str.substr(m.length);
180 var Class = function() { };
182 Class.extend = function(properties)
184 Class.initializing = true;
186 var prototype = new this();
187 var superprot = this.prototype;
189 Class.initializing = false;
191 $.extend(prototype, properties, {
192 callSuper: function() {
194 var meth = arguments[0];
196 if (typeof(superprot[meth]) != 'function')
199 for (var i = 1; i < arguments.length; i++)
200 args.push(arguments[i]);
202 return superprot[meth].apply(this, args);
208 this.options = arguments[0] || { };
210 if (!Class.initializing && typeof(this.init) == 'function')
211 this.init.apply(this, arguments);
214 _class.prototype = prototype;
215 _class.prototype.constructor = _class;
217 _class.extend = arguments.callee;
222 this.defaults = function(obj, def)
225 if (typeof(obj[key]) == 'undefined')
231 this.isDeferred = function(x)
233 return (typeof(x) == 'object' &&
234 typeof(x.then) == 'function' &&
235 typeof(x.promise) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments[0]))
243 var d = $.Deferred();
244 d.resolve.apply(d, arguments);
253 plural: function(n) { return 0 + (n != 1) },
256 if (_luci2.i18n.loaded)
259 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
262 for (var i = 0; i < langs.length; i++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
267 success: function(data) {
268 $.extend(_luci2.i18n.catalog, data);
270 var pe = _luci2.i18n.catalog[''];
273 delete _luci2.i18n.catalog[''];
275 var pf = new Function('n', 'return 0 + (' + pe + ')');
276 _luci2.i18n.plural = pf;
282 _luci2.i18n.loaded = true;
287 this.tr = function(msgid)
291 var msgstr = _luci2.i18n.catalog[msgid];
293 if (typeof(msgstr) == 'undefined')
295 else if (typeof(msgstr) == 'string')
301 this.trp = function(msgid, msgid_plural, count)
305 var msgstr = _luci2.i18n.catalog[msgid];
307 if (typeof(msgstr) == 'undefined')
308 return (count == 1) ? msgid : msgid_plural;
309 else if (typeof(msgstr) == 'string')
312 return msgstr[_luci2.i18n.plural(count)];
315 this.trc = function(msgctx, msgid)
319 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
321 if (typeof(msgstr) == 'undefined')
323 else if (typeof(msgstr) == 'string')
329 this.trcp = function(msgctx, msgid, msgid_plural, count)
333 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
335 if (typeof(msgstr) == 'undefined')
336 return (count == 1) ? msgid : msgid_plural;
337 else if (typeof(msgstr) == 'string')
340 return msgstr[_luci2.i18n.plural(count)];
343 this.setHash = function(key, value)
346 var data = this.getHash(undefined);
348 if (typeof(value) == 'undefined')
359 for (var i = 0; i < keys.length; i++)
364 h += keys[i] + ':' + data[keys[i]];
368 location.hash = '#' + h;
371 this.getHash = function(key)
374 var tuples = (location.hash || '#').substring(1).split(/,/);
376 for (var i = 0; i < tuples.length; i++)
378 var tuple = tuples[i].split(/:/);
379 if (tuple.length == 2)
380 data[tuple[0]] = tuple[1];
383 if (typeof(key) != 'undefined')
392 sid: '00000000000000000000000000000000'
401 _call: function(req, cb)
403 return $.ajax('/ubus', {
405 contentType: 'application/json',
406 data: JSON.stringify(req),
409 timeout: _luci2.globals.timeout
413 _list_cb: function(msg)
415 /* verify message frame */
416 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
417 throw 'Invalid JSON response';
422 _call_cb: function(msg)
425 var type = Object.prototype.toString;
430 for (var i = 0; i < msg.length; i++)
432 /* verify message frame */
433 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
434 throw 'Invalid JSON response';
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';
441 /* fetch response attribute and verify returned type */
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];
449 for (var key in req.expect)
451 if (typeof(ret) != 'undefined' && key != '')
454 if (type.call(ret) != type.call(req.expect[key]))
455 ret = req.expect[key];
462 if (typeof(req.filter) == 'function')
465 req.priv[1] = req.params;
466 ret = req.filter.apply(_luci2.rpc, req.priv);
469 /* store response data */
470 if (typeof(req.index) == 'number')
471 data[req.index] = ret;
475 /* delete request object */
476 delete _luci2.rpc._requests[msg[i].id];
485 for (var i = 0; i < arguments.length; i++)
486 params[i] = arguments[i];
492 params: (params.length > 0) ? params : undefined
495 return this._call(msg, this._list_cb);
500 if (!$.isArray(this._batch))
506 if (!$.isArray(this._batch))
507 return _luci2.deferrable([ ]);
509 var req = this._batch;
513 return this._call(req, this._call_cb);
516 declare: function(options)
521 /* build parameter object */
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];
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]);
533 /* store request info */
534 var req = _rpc._requests[_rpc._id] = {
535 expect: options.expect,
536 filter: options.filter,
541 /* build message object */
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))
558 req.index = _rpc._batch.push(msg) - 1;
559 return _luci2.deferrable(msg);
563 return _rpc._call(msg, _rpc._call_cb);
572 return _luci2.session.access('ubus', 'uci', 'commit');
575 add: _luci2.rpc.declare({
578 params: [ 'config', 'type', 'name', 'values' ],
579 expect: { section: '' }
587 configs: _luci2.rpc.declare({
590 expect: { configs: [ ] }
593 _changes: _luci2.rpc.declare({
596 params: [ 'config' ],
597 expect: { changes: [ ] }
600 changes: function(config)
602 if (typeof(config) == 'string')
603 return this._changes(config);
606 return this.configs().then(function(configs) {
608 configlist = configs;
610 for (var i = 0; i < configs.length; i++)
611 _luci2.uci._changes(configs[i]);
613 return _luci2.rpc.flush();
614 }).then(function(changes) {
617 for (var i = 0; i < configlist.length; i++)
618 if (changes[i].length)
619 rv[configlist[i]] = changes[i];
625 commit: _luci2.rpc.declare({
631 _delete_one: _luci2.rpc.declare({
634 params: [ 'config', 'section', 'option' ]
637 _delete_multiple: _luci2.rpc.declare({
640 params: [ 'config', 'section', 'options' ]
643 'delete': function(config, section, option)
645 if ($.isArray(option))
646 return this._delete_multiple(config, section, option);
648 return this._delete_one(config, section, option);
651 delete_all: _luci2.rpc.declare({
654 params: [ 'config', 'type', 'match' ]
657 _foreach: _luci2.rpc.declare({
660 params: [ 'config', 'type' ],
661 expect: { values: { } }
664 foreach: function(config, type, cb)
666 return this._foreach(config, type).then(function(sections) {
667 for (var s in sections)
672 get: _luci2.rpc.declare({
675 params: [ 'config', 'section', 'option' ],
677 filter: function(data, params) {
678 if (typeof(params.option) == 'undefined')
679 return data.values ? data.values['.type'] : undefined;
685 get_all: _luci2.rpc.declare({
688 params: [ 'config', 'section' ],
689 expect: { values: { } },
690 filter: function(data, params) {
691 if (typeof(params.section) == 'string')
692 data['.section'] = params.section;
693 else if (typeof(params.config) == 'string')
694 data['.package'] = params.config;
699 get_first: function(config, type, option)
701 return this._foreach(config, type).then(function(sections) {
702 for (var s in sections)
704 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
706 if (typeof(val) != 'undefined')
714 section: _luci2.rpc.declare({
717 params: [ 'config', 'type', 'name', 'values' ],
718 expect: { section: '' }
721 _set: _luci2.rpc.declare({
724 params: [ 'config', 'section', 'values' ]
727 set: function(config, section, option, value)
729 if (typeof(value) == 'undefined' && typeof(option) == 'string')
730 return this.section(config, section, option); /* option -> type */
731 else if ($.isPlainObject(option))
732 return this._set(config, section, option); /* option -> values */
735 values[option] = value;
737 return this._set(config, section, values);
740 order: _luci2.rpc.declare({
743 params: [ 'config', 'sections' ]
748 listNetworkNames: function() {
749 return _luci2.rpc.list('network.interface.*').then(function(list) {
751 for (var name in list)
752 if (name != 'network.interface.loopback')
753 names.push(name.substring(18));
759 listDeviceNames: _luci2.rpc.declare({
760 object: 'network.device',
763 filter: function(data) {
765 for (var name in data)
773 getNetworkStatus: function()
778 return this.listNetworkNames().then(function(names) {
781 for (var i = 0; i < names.length; i++)
782 _luci2.network.getInterfaceStatus(names[i]);
784 return _luci2.rpc.flush();
785 }).then(function(networks) {
786 for (var i = 0; i < networks.length; i++)
788 var net = nets[i] = networks[i];
789 var dev = net.l3_device || net.l2_device;
791 net.device = devs[dev] = { };
796 for (var dev in devs)
797 _luci2.network.listDeviceNamestatus(dev);
799 return _luci2.rpc.flush();
800 }).then(function(devices) {
803 for (var i = 0; i < devices.length; i++)
805 var brm = devices[i]['bridge-members'];
806 delete devices[i]['bridge-members'];
808 $.extend(devs[devices[i]['device']], devices[i]);
813 devs[devices[i]['device']].subdevices = [ ];
815 for (var j = 0; j < brm.length; j++)
820 _luci2.network.listDeviceNamestatus(brm[j]);
823 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
827 return _luci2.rpc.flush();
828 }).then(function(subdevices) {
829 for (var i = 0; i < subdevices.length; i++)
830 $.extend(devs[subdevices[i]['device']], subdevices[i]);
834 for (var dev in devs)
835 _luci2.wireless.getDeviceStatus(dev);
837 return _luci2.rpc.flush();
838 }).then(function(wifidevices) {
839 for (var i = 0; i < wifidevices.length; i++)
841 devs[wifidevices[i]['device']].wireless = wifidevices[i];
843 nets.sort(function(a, b) {
844 if (a['interface'] < b['interface'])
846 else if (a['interface'] > b['interface'])
856 findWanInterfaces: function(cb)
858 return this.listNetworkNames().then(function(names) {
861 for (var i = 0; i < names.length; i++)
862 _luci2.network.getInterfaceStatus(names[i]);
864 return _luci2.rpc.flush();
865 }).then(function(interfaces) {
866 var rv = [ undefined, undefined ];
868 for (var i = 0; i < interfaces.length; i++)
870 for (var j = 0; j < interfaces[i].route.length; j++)
872 var rt = interfaces[i].route[j];
874 if (typeof(rt.table) != 'undefined')
877 if (rt.target == '0.0.0.0' && rt.mask == 0)
878 rv[0] = interfaces[i];
879 else if (rt.target == '::' && rt.mask == 0)
880 rv[1] = interfaces[i];
888 getDHCPLeases: _luci2.rpc.declare({
889 object: 'luci2.network',
890 method: 'dhcp_leases',
891 expect: { leases: [ ] }
894 getDHCPv6Leases: _luci2.rpc.declare({
895 object: 'luci2.network',
896 method: 'dhcp6_leases',
897 expect: { leases: [ ] }
900 getRoutes: _luci2.rpc.declare({
901 object: 'luci2.network',
903 expect: { routes: [ ] }
906 getIPv6Routes: _luci2.rpc.declare({
907 object: 'luci2.network',
909 expect: { routes: [ ] }
912 getARPTable: _luci2.rpc.declare({
913 object: 'luci2.network',
915 expect: { entries: [ ] }
918 getInterfaceStatus: _luci2.rpc.declare({
919 object: 'network.interface',
921 params: [ 'interface' ],
923 filter: function(data, params) {
924 data['interface'] = params['interface'];
925 data['l2_device'] = data['device'];
926 delete data['device'];
931 listDeviceNamestatus: _luci2.rpc.declare({
932 object: 'network.device',
936 filter: function(data, params) {
937 data['device'] = params['name'];
942 getConntrackCount: _luci2.rpc.declare({
943 object: 'luci2.network',
944 method: 'conntrack_count',
945 expect: { '': { count: 0, limit: 0 } }
950 listDeviceNames: _luci2.rpc.declare({
953 expect: { 'devices': [ ] },
954 filter: function(data) {
960 getDeviceStatus: _luci2.rpc.declare({
963 params: [ 'device' ],
965 filter: function(data, params) {
966 if (!$.isEmptyObject(data))
968 data['device'] = params['device'];
975 getAssocList: _luci2.rpc.declare({
978 params: [ 'device' ],
979 expect: { results: [ ] },
980 filter: function(data, params) {
981 for (var i = 0; i < data.length; i++)
982 data[i]['device'] = params['device'];
984 data.sort(function(a, b) {
985 if (a.bssid < b.bssid)
987 else if (a.bssid > b.bssid)
997 getWirelessStatus: function() {
998 return this.listDeviceNames().then(function(names) {
1001 for (var i = 0; i < names.length; i++)
1002 _luci2.wireless.getDeviceStatus(names[i]);
1004 return _luci2.rpc.flush();
1005 }).then(function(networks) {
1009 'country', 'channel', 'frequency', 'frequency_offset',
1010 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1014 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1015 'signal', 'noise', 'bitrate', 'encryption'
1018 for (var i = 0; i < networks.length; i++)
1020 var phy = rv[networks[i].phy] || (
1021 rv[networks[i].phy] = { networks: [ ] }
1025 device: networks[i].device
1028 for (var j = 0; j < phy_attrs.length; j++)
1029 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1031 for (var j = 0; j < net_attrs.length; j++)
1032 net[net_attrs[j]] = networks[i][net_attrs[j]];
1034 phy.networks.push(net);
1041 getAssocLists: function()
1043 return this.listDeviceNames().then(function(names) {
1046 for (var i = 0; i < names.length; i++)
1047 _luci2.wireless.getAssocList(names[i]);
1049 return _luci2.rpc.flush();
1050 }).then(function(assoclists) {
1053 for (var i = 0; i < assoclists.length; i++)
1054 for (var j = 0; j < assoclists[i].length; j++)
1055 rv.push(assoclists[i][j]);
1061 formatEncryption: function(enc)
1063 var format_list = function(l, s)
1066 for (var i = 0; i < l.length; i++)
1067 rv.push(l[i].toUpperCase());
1068 return rv.join(s ? s : ', ');
1071 if (!enc || !enc.enabled)
1072 return _luci2.tr('None');
1076 if (enc.wep.length == 2)
1077 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1078 else if (enc.wep[0] == 'shared')
1079 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1081 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1085 if (enc.wpa.length == 2)
1086 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1087 format_list(enc.authentication, '/'),
1088 format_list(enc.ciphers, ', ')
1090 else if (enc.wpa[0] == 2)
1091 return 'WPA2 %s (%s)'.format(
1092 format_list(enc.authentication, '/'),
1093 format_list(enc.ciphers, ', ')
1096 return 'WPA %s (%s)'.format(
1097 format_list(enc.authentication, '/'),
1098 format_list(enc.ciphers, ', ')
1102 return _luci2.tr('Unknown');
1107 getSystemInfo: _luci2.rpc.declare({
1113 getBoardInfo: _luci2.rpc.declare({
1119 getDiskInfo: _luci2.rpc.declare({
1120 object: 'luci2.system',
1125 getInfo: function(cb)
1129 this.getSystemInfo();
1130 this.getBoardInfo();
1133 return _luci2.rpc.flush().then(function(info) {
1136 $.extend(rv, info[0]);
1137 $.extend(rv, info[1]);
1138 $.extend(rv, info[2]);
1144 getProcessList: _luci2.rpc.declare({
1145 object: 'luci2.system',
1146 method: 'process_list',
1147 expect: { processes: [ ] },
1148 filter: function(data) {
1149 data.sort(function(a, b) { return a.pid - b.pid });
1154 getSystemLog: _luci2.rpc.declare({
1155 object: 'luci2.system',
1160 getKernelLog: _luci2.rpc.declare({
1161 object: 'luci2.system',
1166 getZoneInfo: function(cb)
1168 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1171 sendSignal: _luci2.rpc.declare({
1172 object: 'luci2.system',
1173 method: 'process_signal',
1174 params: [ 'pid', 'signal' ],
1175 filter: function(data) {
1180 initList: _luci2.rpc.declare({
1181 object: 'luci2.system',
1182 method: 'init_list',
1183 expect: { initscripts: [ ] },
1184 filter: function(data) {
1185 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1190 initEnabled: function(init, cb)
1192 return this.initList().then(function(list) {
1193 for (var i = 0; i < list.length; i++)
1194 if (list[i].name == init)
1195 return !!list[i].enabled;
1201 initRun: _luci2.rpc.declare({
1202 object: 'luci2.system',
1203 method: 'init_action',
1204 params: [ 'name', 'action' ],
1205 filter: function(data) {
1210 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1211 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1212 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1213 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1214 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1215 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1218 getRcLocal: _luci2.rpc.declare({
1219 object: 'luci2.system',
1220 method: 'rclocal_get',
1221 expect: { data: '' }
1224 setRcLocal: _luci2.rpc.declare({
1225 object: 'luci2.system',
1226 method: 'rclocal_set',
1231 getCrontab: _luci2.rpc.declare({
1232 object: 'luci2.system',
1233 method: 'crontab_get',
1234 expect: { data: '' }
1237 setCrontab: _luci2.rpc.declare({
1238 object: 'luci2.system',
1239 method: 'crontab_set',
1244 getSSHKeys: _luci2.rpc.declare({
1245 object: 'luci2.system',
1246 method: 'sshkeys_get',
1247 expect: { keys: [ ] }
1250 setSSHKeys: _luci2.rpc.declare({
1251 object: 'luci2.system',
1252 method: 'sshkeys_set',
1257 setPassword: _luci2.rpc.declare({
1258 object: 'luci2.system',
1259 method: 'password_set',
1260 params: [ 'user', 'password' ]
1264 listLEDs: _luci2.rpc.declare({
1265 object: 'luci2.system',
1267 expect: { leds: [ ] }
1270 listUSBDevices: _luci2.rpc.declare({
1271 object: 'luci2.system',
1273 expect: { devices: [ ] }
1277 testUpgrade: _luci2.rpc.declare({
1278 object: 'luci2.system',
1279 method: 'upgrade_test',
1283 startUpgrade: _luci2.rpc.declare({
1284 object: 'luci2.system',
1285 method: 'upgrade_start',
1289 cleanUpgrade: _luci2.rpc.declare({
1290 object: 'luci2.system',
1291 method: 'upgrade_clean'
1295 restoreBackup: _luci2.rpc.declare({
1296 object: 'luci2.system',
1297 method: 'backup_restore'
1300 cleanBackup: _luci2.rpc.declare({
1301 object: 'luci2.system',
1302 method: 'backup_clean'
1306 getBackupConfig: _luci2.rpc.declare({
1307 object: 'luci2.system',
1308 method: 'backup_config_get',
1309 expect: { config: '' }
1312 setBackupConfig: _luci2.rpc.declare({
1313 object: 'luci2.system',
1314 method: 'backup_config_set',
1319 listBackup: _luci2.rpc.declare({
1320 object: 'luci2.system',
1321 method: 'backup_list',
1322 expect: { files: [ ] }
1326 testReset: _luci2.rpc.declare({
1327 object: 'luci2.system',
1328 method: 'reset_test',
1329 expect: { supported: false }
1332 startReset: _luci2.rpc.declare({
1333 object: 'luci2.system',
1334 method: 'reset_start'
1338 performReboot: _luci2.rpc.declare({
1339 object: 'luci2.system',
1345 updateLists: _luci2.rpc.declare({
1346 object: 'luci2.opkg',
1351 _allPackages: _luci2.rpc.declare({
1352 object: 'luci2.opkg',
1354 params: [ 'offset', 'limit', 'pattern' ],
1358 _installedPackages: _luci2.rpc.declare({
1359 object: 'luci2.opkg',
1360 method: 'list_installed',
1361 params: [ 'offset', 'limit', 'pattern' ],
1365 _findPackages: _luci2.rpc.declare({
1366 object: 'luci2.opkg',
1368 params: [ 'offset', 'limit', 'pattern' ],
1372 _fetchPackages: function(action, offset, limit, pattern)
1376 return action(offset, limit, pattern).then(function(list) {
1377 if (!list.total || !list.packages)
1378 return { length: 0, total: 0 };
1380 packages.push.apply(packages, list.packages);
1381 packages.total = list.total;
1386 if (packages.length >= limit)
1391 for (var i = offset + packages.length; i < limit; i += 100)
1392 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1394 return _luci2.rpc.flush();
1395 }).then(function(lists) {
1396 for (var i = 0; i < lists.length; i++)
1398 if (!lists[i].total || !lists[i].packages)
1401 packages.push.apply(packages, lists[i].packages);
1402 packages.total = lists[i].total;
1409 listPackages: function(offset, limit, pattern)
1411 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1414 installedPackages: function(offset, limit, pattern)
1416 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1419 findPackages: function(offset, limit, pattern)
1421 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1424 installPackage: _luci2.rpc.declare({
1425 object: 'luci2.opkg',
1427 params: [ 'package' ],
1431 removePackage: _luci2.rpc.declare({
1432 object: 'luci2.opkg',
1434 params: [ 'package' ],
1438 getConfig: _luci2.rpc.declare({
1439 object: 'luci2.opkg',
1440 method: 'config_get',
1441 expect: { config: '' }
1444 setConfig: _luci2.rpc.declare({
1445 object: 'luci2.opkg',
1446 method: 'config_set',
1453 login: _luci2.rpc.declare({
1456 params: [ 'username', 'password' ],
1460 access: _luci2.rpc.declare({
1463 params: [ 'scope', 'object', 'function' ],
1464 expect: { access: false }
1469 return _luci2.session.access('ubus', 'session', 'access');
1472 startHeartbeat: function()
1474 this._hearbeatInterval = window.setInterval(function() {
1475 _luci2.session.isAlive().then(function(alive) {
1478 _luci2.session.stopHeartbeat();
1479 _luci2.ui.login(true);
1483 }, _luci2.globals.timeout * 2);
1486 stopHeartbeat: function()
1488 if (typeof(this._hearbeatInterval) != 'undefined')
1490 window.clearInterval(this._hearbeatInterval);
1491 delete this._hearbeatInterval;
1498 saveScrollTop: function()
1500 this._scroll_top = $(document).scrollTop();
1503 restoreScrollTop: function()
1505 if (typeof(this._scroll_top) == 'undefined')
1508 $(document).scrollTop(this._scroll_top);
1510 delete this._scroll_top;
1513 loading: function(enable)
1515 var win = $(window);
1516 var body = $('body');
1518 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1520 .addClass('cbi-modal-loader')
1521 .append($('<div />').text(_luci2.tr('Loading data...')))
1527 body.css('overflow', 'hidden');
1528 body.css('padding', 0);
1529 body.css('width', win.width());
1530 body.css('height', win.height());
1531 state.modal.css('width', win.width());
1532 state.modal.css('height', win.height());
1538 body.css('overflow', '');
1539 body.css('padding', '');
1540 body.css('width', '');
1541 body.css('height', '');
1545 dialog: function(title, content, options)
1547 var win = $(window);
1548 var body = $('body');
1550 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1551 dialog: $('<div />')
1552 .addClass('cbi-modal-dialog')
1553 .append($('<div />')
1554 .append($('<div />')
1555 .addClass('cbi-modal-dialog-header'))
1556 .append($('<div />')
1557 .addClass('cbi-modal-dialog-body'))
1558 .append($('<div />')
1559 .addClass('cbi-modal-dialog-footer')
1560 .append($('<button />')
1561 .addClass('cbi-button')
1562 .text(_luci2.tr('Close'))
1565 .css('overflow', '')
1570 $(this).parent().parent().parent().hide();
1575 if (typeof(options) != 'object')
1578 if (title === false)
1581 .css('overflow', '')
1586 state.dialog.hide();
1591 var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1592 var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1596 if (options.style == 'confirm')
1598 ftr.append($('<button />')
1599 .addClass('cbi-button')
1600 .text(_luci2.tr('Ok'))
1601 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1603 ftr.append($('<button />')
1604 .addClass('cbi-button')
1605 .text(_luci2.tr('Cancel'))
1606 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1608 else if (options.style == 'close')
1610 ftr.append($('<button />')
1611 .addClass('cbi-button')
1612 .text(_luci2.tr('Close'))
1613 .click(options.close || function() { _luci2.ui.dialog(false) }));
1615 else if (options.style == 'wait')
1617 ftr.append($('<button />')
1618 .addClass('cbi-button')
1619 .text(_luci2.tr('Close'))
1620 .attr('disabled', true));
1623 state.dialog.find('div.cbi-modal-dialog-header').text(title);
1624 state.dialog.show();
1627 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1631 state.dialog.children()
1632 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1634 body.css('overflow', 'hidden');
1635 body.css('padding', 0);
1636 body.css('width', win.width());
1637 body.css('height', win.height());
1638 state.dialog.css('width', win.width());
1639 state.dialog.css('height', win.height());
1642 upload: function(title, content, options)
1644 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1646 .attr('method', 'post')
1647 .attr('action', '/cgi-bin/luci-upload')
1648 .attr('enctype', 'multipart/form-data')
1649 .attr('target', 'cbi-fileupload-frame')
1651 .append($('<input />')
1652 .attr('type', 'hidden')
1653 .attr('name', 'sessionid'))
1654 .append($('<input />')
1655 .attr('type', 'hidden')
1656 .attr('name', 'filename'))
1657 .append($('<input />')
1658 .attr('type', 'file')
1659 .attr('name', 'filedata')
1660 .addClass('cbi-input-file'))
1661 .append($('<div />')
1662 .css('width', '100%')
1663 .addClass('progressbar')
1664 .addClass('intermediate')
1665 .append($('<div />')
1666 .css('width', '100%')))
1667 .append($('<iframe />')
1668 .attr('name', 'cbi-fileupload-frame')
1669 .css('width', '1px')
1670 .css('height', '1px')
1671 .css('visibility', 'hidden')),
1673 finish_cb: function(ev) {
1674 $(this).off('load');
1676 var body = (this.contentDocument || this.contentWindow.document).body;
1677 if (body.firstChild.tagName.toLowerCase() == 'pre')
1678 body = body.firstChild;
1682 json = $.parseJSON(body.innerHTML);
1685 message: _luci2.tr('Invalid server response received'),
1686 error: [ -1, _luci2.tr('Invalid data') ]
1692 L.ui.dialog(L.tr('File upload'), [
1693 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1694 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1695 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1696 ], { style: 'close' });
1698 else if (typeof(state.success_cb) == 'function')
1700 state.success_cb(json);
1704 confirm_cb: function() {
1705 var f = state.form.find('.cbi-input-file');
1706 var b = state.form.find('.progressbar');
1707 var p = state.form.find('p');
1712 state.form.find('iframe').on('load', state.finish_cb);
1713 state.form.submit();
1717 p.text(_luci2.tr('File upload in progress …'));
1719 state.form.parent().parent().find('button').prop('disabled', true);
1723 state.form.find('.progressbar').hide();
1724 state.form.find('.cbi-input-file').val('').show();
1725 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1727 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1728 state.form.find('[name=filename]').val(options.filename);
1730 state.success_cb = options.success;
1732 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1734 confirm: state.confirm_cb
1738 reconnect: function()
1740 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1741 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1742 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1744 var interval, timeout;
1747 _luci2.tr('Waiting for device'), [
1748 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1750 .css('width', '100%')
1751 .addClass('progressbar')
1752 .addClass('intermediate')
1753 .append($('<div />')
1754 .css('width', '100%'))
1755 ], { style: 'wait' }
1758 for (var i = 0; i < protocols.length; i++)
1759 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1761 //_luci2.network.getNetworkStatus(function(s) {
1762 // for (var i = 0; i < protocols.length; i++)
1764 // for (var j = 0; j < s.length; j++)
1766 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1767 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1769 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1770 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1773 //}).then(function() {
1774 images.on('load', function() {
1775 var url = this.getAttribute('url');
1776 _luci2.session.isAlive().then(function(access) {
1779 window.clearTimeout(timeout);
1780 window.clearInterval(interval);
1781 _luci2.ui.dialog(false);
1786 location.href = url;
1791 interval = window.setInterval(function() {
1792 images.each(function() {
1793 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1797 timeout = window.setTimeout(function() {
1798 window.clearInterval(interval);
1802 _luci2.tr('Device not responding'),
1803 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1810 login: function(invalid)
1812 var state = _luci2.ui._login || (_luci2.ui._login = {
1815 .attr('method', 'post')
1817 .addClass('alert-message')
1818 .text(_luci2.tr('Wrong username or password given!')))
1820 .append($('<label />')
1821 .text(_luci2.tr('Username'))
1822 .append($('<br />'))
1823 .append($('<input />')
1824 .attr('type', 'text')
1825 .attr('name', 'username')
1826 .attr('value', 'root')
1827 .addClass('cbi-input-text')
1828 .keypress(function(ev) {
1829 if (ev.which == 10 || ev.which == 13)
1833 .append($('<label />')
1834 .text(_luci2.tr('Password'))
1835 .append($('<br />'))
1836 .append($('<input />')
1837 .attr('type', 'password')
1838 .attr('name', 'password')
1839 .addClass('cbi-input-password')
1840 .keypress(function(ev) {
1841 if (ev.which == 10 || ev.which == 13)
1845 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1847 response_cb: function(response) {
1848 if (!response.ubus_rpc_session)
1850 _luci2.ui.login(true);
1854 _luci2.globals.sid = response.ubus_rpc_session;
1855 _luci2.setHash('id', _luci2.globals.sid);
1856 _luci2.session.startHeartbeat();
1857 _luci2.ui.dialog(false);
1858 state.deferred.resolve();
1862 confirm_cb: function() {
1863 var u = state.form.find('[name=username]').val();
1864 var p = state.form.find('[name=password]').val();
1870 _luci2.tr('Logging in'), [
1871 $('<p />').text(_luci2.tr('Log in in progress …')),
1873 .css('width', '100%')
1874 .addClass('progressbar')
1875 .addClass('intermediate')
1876 .append($('<div />')
1877 .css('width', '100%'))
1878 ], { style: 'wait' }
1881 _luci2.globals.sid = '00000000000000000000000000000000';
1882 _luci2.session.login(u, p).then(state.response_cb);
1886 if (!state.deferred || state.deferred.state() != 'pending')
1887 state.deferred = $.Deferred();
1889 /* try to find sid from hash */
1890 var sid = _luci2.getHash('id');
1891 if (sid && sid.match(/^[a-f0-9]{32}$/))
1893 _luci2.globals.sid = sid;
1894 _luci2.session.isAlive().then(function(access) {
1897 _luci2.session.startHeartbeat();
1898 state.deferred.resolve();
1902 _luci2.setHash('id', undefined);
1907 return state.deferred;
1911 state.form.find('.alert-message').show();
1913 state.form.find('.alert-message').hide();
1915 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
1917 confirm: state.confirm_cb
1920 state.form.find('[name=password]').focus();
1922 return state.deferred;
1925 cryptPassword: _luci2.rpc.declare({
1929 expect: { crypt: '' }
1933 _acl_merge_scope: function(acl_scope, scope)
1935 if ($.isArray(scope))
1937 for (var i = 0; i < scope.length; i++)
1938 acl_scope[scope[i]] = true;
1940 else if ($.isPlainObject(scope))
1942 for (var object_name in scope)
1944 if (!$.isArray(scope[object_name]))
1947 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
1949 for (var i = 0; i < scope[object_name].length; i++)
1950 acl_object[scope[object_name][i]] = true;
1955 _acl_merge_permission: function(acl_perm, perm)
1957 if ($.isPlainObject(perm))
1959 for (var scope_name in perm)
1961 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
1962 this._acl_merge_scope(acl_scope, perm[scope_name]);
1967 _acl_merge_group: function(acl_group, group)
1969 if ($.isPlainObject(group))
1971 if (!acl_group.description)
1972 acl_group.description = group.description;
1976 var acl_perm = acl_group.read || (acl_group.read = { });
1977 this._acl_merge_permission(acl_perm, group.read);
1982 var acl_perm = acl_group.write || (acl_group.write = { });
1983 this._acl_merge_permission(acl_perm, group.write);
1988 _acl_merge_tree: function(acl_tree, tree)
1990 if ($.isPlainObject(tree))
1992 for (var group_name in tree)
1994 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
1995 this._acl_merge_group(acl_group, tree[group_name]);
2000 listAvailableACLs: _luci2.rpc.declare({
2003 expect: { acls: [ ] },
2004 filter: function(trees) {
2006 for (var i = 0; i < trees.length; i++)
2007 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2012 renderMainMenu: _luci2.rpc.declare({
2015 expect: { menu: { } },
2016 filter: function(entries) {
2017 _luci2.globals.mainMenu = new _luci2.ui.menu();
2018 _luci2.globals.mainMenu.entries(entries);
2022 .append(_luci2.globals.mainMenu.render(0, 1));
2026 renderViewMenu: function()
2030 .append(_luci2.globals.mainMenu.render(2, 900));
2033 renderView: function(node)
2035 var name = node.view.split(/\//).join('.');
2037 _luci2.ui.renderViewMenu();
2040 _luci2._views = { };
2042 _luci2.setHash('view', node.view);
2044 if (_luci2._views[name] instanceof _luci2.ui.view)
2045 return _luci2._views[name].render();
2047 var url = _luci2.globals.resource + '/view/' + name + '.js';
2049 return $.ajax(url, {
2053 }).then(function(data) {
2055 var viewConstructorSource = (
2056 '(function(L, $) {\n' +
2058 '})(_luci2, $);\n\n' +
2060 ).format(data, url);
2062 var viewConstructor = eval(viewConstructorSource);
2064 _luci2._views[name] = new viewConstructor({
2066 acls: node.write || { }
2069 return _luci2._views[name].render();
2072 alert('Unable to instantiate view "%s": %s'.format(url, e));
2075 return $.Deferred().resolve();
2079 updateHostname: function()
2081 return _luci2.system.getBoardInfo().then(function(info) {
2083 $('#hostname').text(info.hostname);
2087 updateChanges: function()
2089 return _luci2.uci.changes().then(function(changes) {
2093 for (var config in changes)
2097 for (var i = 0; i < changes[config].length; i++)
2099 var c = changes[config][i];
2108 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2110 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2115 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2117 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2121 log.push('uci add %s (= <ins><strong>%s</strong></ins>)'.format(config, c[1]));
2125 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2129 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2134 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2136 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2141 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2142 n += changes[config].length;
2153 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2154 .click(function(ev) {
2155 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2156 ev.preventDefault();
2166 _luci2.ui.loading(true);
2169 _luci2.ui.updateHostname(),
2170 _luci2.ui.updateChanges(),
2171 _luci2.ui.renderMainMenu()
2173 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2174 _luci2.ui.loading(false);
2180 var AbstractWidget = Class.extend({
2181 i18n: function(text) {
2185 toString: function() {
2186 var x = document.createElement('div');
2187 x.appendChild(this.render());
2192 insertInto: function(id) {
2193 return $(id).empty().append(this.render());
2197 this.ui.view = AbstractWidget.extend({
2198 _fetch_template: function()
2200 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2204 success: function(data) {
2205 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2206 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2213 return _luci2.tr(p2);
2216 return _luci2.globals[p2] || '';
2219 return '(?' + match + ')';
2223 $('#maincontent').append(data);
2230 throw "Not implemented";
2235 var container = $('#maincontent');
2240 container.append($('<h2 />').append(this.title));
2242 if (this.description)
2243 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2246 return this._fetch_template().then(function() {
2247 return _luci2.deferrable(self.execute());
2252 this.ui.menu = AbstractWidget.extend({
2257 entries: function(entries)
2259 for (var entry in entries)
2261 var path = entry.split(/\//);
2262 var node = this._nodes;
2264 for (i = 0; i < path.length; i++)
2269 if (!node.childs[path[i]])
2270 node.childs[path[i]] = { };
2272 node = node.childs[path[i]];
2275 $.extend(node, entries[entry]);
2279 _indexcmp: function(a, b)
2281 var x = a.index || 0;
2282 var y = b.index || 0;
2286 firstChildView: function(node)
2292 for (var child in (node.childs || { }))
2293 nodes.push(node.childs[child]);
2295 nodes.sort(this._indexcmp);
2297 for (var i = 0; i < nodes.length; i++)
2299 var child = this.firstChildView(nodes[i]);
2302 $.extend(node, child);
2310 _onclick: function(ev)
2312 _luci2.ui.loading(true);
2313 _luci2.ui.renderView(ev.data).then(function() {
2314 _luci2.ui.loading(false);
2317 ev.preventDefault();
2321 _render: function(childs, level, min, max)
2324 for (var node in childs)
2326 var child = this.firstChildView(childs[node]);
2328 nodes.push(childs[node]);
2331 nodes.sort(this._indexcmp);
2333 var list = $('<ul />');
2336 list.addClass('nav');
2337 else if (level == 1)
2338 list.addClass('dropdown-menu');
2340 for (var i = 0; i < nodes.length; i++)
2342 if (!_luci2.globals.defaultNode)
2344 var v = _luci2.getHash('view');
2345 if (!v || v == nodes[i].view)
2346 _luci2.globals.defaultNode = nodes[i];
2349 var item = $('<li />')
2352 .text(_luci2.tr(nodes[i].title))
2353 .click(nodes[i], this._onclick))
2356 if (nodes[i].childs && level < max)
2358 item.addClass('dropdown');
2359 item.find('a').addClass('menu');
2360 item.append(this._render(nodes[i].childs, level + 1));
2367 render: function(min, max)
2369 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2370 return this._render(top.childs, 0, min, max);
2373 getNode: function(path, max)
2375 var p = path.split(/\//);
2376 var n = this._nodes;
2378 if (typeof(max) == 'undefined')
2381 for (var i = 0; i < max; i++)
2383 if (!n.childs[p[i]])
2393 this.ui.table = AbstractWidget.extend({
2399 row: function(values)
2401 if ($.isArray(values))
2403 this._rows.push(values);
2405 else if ($.isPlainObject(values))
2408 for (var i = 0; i < this.options.columns.length; i++)
2410 var col = this.options.columns[i];
2412 if (typeof col.key == 'string')
2413 v.push(values[col.key]);
2421 rows: function(rows)
2423 for (var i = 0; i < rows.length; i++)
2427 render: function(id)
2429 var fieldset = document.createElement('fieldset');
2430 fieldset.className = 'cbi-section';
2432 if (this.options.caption)
2434 var legend = document.createElement('legend');
2435 $(legend).append(this.options.caption);
2436 fieldset.appendChild(legend);
2439 var table = document.createElement('table');
2440 table.className = 'cbi-section-table';
2442 var has_caption = false;
2443 var has_description = false;
2445 for (var i = 0; i < this.options.columns.length; i++)
2446 if (this.options.columns[i].caption)
2451 else if (this.options.columns[i].description)
2453 has_description = true;
2459 var tr = table.insertRow(-1);
2460 tr.className = 'cbi-section-table-titles';
2462 for (var i = 0; i < this.options.columns.length; i++)
2464 var col = this.options.columns[i];
2465 var th = document.createElement('th');
2466 th.className = 'cbi-section-table-cell';
2471 th.style.width = col.width;
2474 th.style.textAlign = col.align;
2477 $(th).append(col.caption);
2481 if (has_description)
2483 var tr = table.insertRow(-1);
2484 tr.className = 'cbi-section-table-descr';
2486 for (var i = 0; i < this.options.columns.length; i++)
2488 var col = this.options.columns[i];
2489 var th = document.createElement('th');
2490 th.className = 'cbi-section-table-cell';
2495 th.style.width = col.width;
2498 th.style.textAlign = col.align;
2500 if (col.description)
2501 $(th).append(col.description);
2505 if (this._rows.length == 0)
2507 if (this.options.placeholder)
2509 var tr = table.insertRow(-1);
2510 var td = tr.insertCell(-1);
2511 td.className = 'cbi-section-table-cell';
2513 td.colSpan = this.options.columns.length;
2514 $(td).append(this.options.placeholder);
2519 for (var i = 0; i < this._rows.length; i++)
2521 var tr = table.insertRow(-1);
2523 for (var j = 0; j < this.options.columns.length; j++)
2525 var col = this.options.columns[j];
2526 var td = tr.insertCell(-1);
2528 var val = this._rows[i][j];
2530 if (typeof(val) == 'undefined')
2531 val = col.placeholder;
2533 if (typeof(val) == 'undefined')
2537 td.style.width = col.width;
2540 td.style.textAlign = col.align;
2542 if (typeof col.format == 'string')
2543 $(td).append(col.format.format(val));
2544 else if (typeof col.format == 'function')
2545 $(td).append(col.format(val, i));
2553 fieldset.appendChild(table);
2559 this.ui.progress = AbstractWidget.extend({
2562 var vn = parseInt(this.options.value) || 0;
2563 var mn = parseInt(this.options.max) || 100;
2564 var pc = Math.floor((100 / mn) * vn);
2566 var bar = document.createElement('div');
2567 bar.className = 'progressbar';
2569 bar.appendChild(document.createElement('div'));
2570 bar.lastChild.appendChild(document.createElement('div'));
2571 bar.lastChild.style.width = pc + '%';
2573 if (typeof(this.options.format) == 'string')
2574 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2575 else if (typeof(this.options.format) == 'function')
2576 $(bar.lastChild.lastChild).append(this.options.format(pc));
2578 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2584 this.ui.devicebadge = AbstractWidget.extend({
2587 var dev = this.options.l3_device || this.options.device || '?';
2589 var span = document.createElement('span');
2590 span.className = 'ifacebadge';
2592 if (typeof(this.options.signal) == 'number' ||
2593 typeof(this.options.noise) == 'number')
2596 if (typeof(this.options.signal) != 'undefined' &&
2597 typeof(this.options.noise) != 'undefined')
2599 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2612 span.appendChild(document.createElement('img'));
2613 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2616 span.title = _luci2.tr('No signal');
2618 span.title = '%s: %d %s / %s: %d %s'.format(
2619 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2620 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2625 var type = 'ethernet';
2626 var desc = _luci2.tr('Ethernet device');
2628 if (this.options.l3_device != this.options.device)
2631 desc = _luci2.tr('Tunnel interface');
2633 else if (dev.indexOf('br-') == 0)
2636 desc = _luci2.tr('Bridge');
2638 else if (dev.indexOf('.') > 0)
2641 desc = _luci2.tr('VLAN interface');
2643 else if (dev.indexOf('wlan') == 0 ||
2644 dev.indexOf('ath') == 0 ||
2645 dev.indexOf('wl') == 0)
2648 desc = _luci2.tr('Wireless Network');
2651 span.appendChild(document.createElement('img'));
2652 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2656 $(span).append(' ');
2657 $(span).append(dev);
2663 var type = function(f, l)
2673 _luci2.cbi.validation.message = _luci2.tr(msg);
2676 compile: function(code)
2681 var types = _luci2.cbi.validation.types;
2686 for (var i = 0; i < code.length; i++)
2694 switch (code.charCodeAt(i))
2706 var label = code.substring(pos, i);
2707 label = label.replace(/\\(.)/g, '$1');
2708 label = label.replace(/^[ \t]+/g, '');
2709 label = label.replace(/[ \t]+$/g, '');
2711 if (label && !isNaN(label))
2713 stack.push(parseFloat(label));
2715 else if (label.match(/^(['"]).*\1$/))
2717 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2719 else if (typeof types[label] == 'function')
2721 stack.push(types[label]);
2726 throw "Syntax error, unhandled token '"+label+"'";
2731 depth += (code.charCodeAt(i) == 40);
2737 if (typeof stack[stack.length-2] != 'function')
2738 throw "Syntax error, argument list follows non-function";
2740 stack[stack.length-1] =
2741 arguments.callee(code.substring(pos, i));
2754 var validation = this.cbi.validation;
2756 validation.types = {
2757 'integer': function()
2759 if (this.match(/^-?[0-9]+$/) != null)
2762 validation.i18n('Must be a valid integer');
2766 'uinteger': function()
2768 if (validation.types['integer'].apply(this) && (this >= 0))
2771 validation.i18n('Must be a positive integer');
2777 if (!isNaN(parseFloat(this)))
2780 validation.i18n('Must be a valid number');
2784 'ufloat': function()
2786 if (validation.types['float'].apply(this) && (this >= 0))
2789 validation.i18n('Must be a positive number');
2793 'ipaddr': function()
2795 if (validation.types['ip4addr'].apply(this) ||
2796 validation.types['ip6addr'].apply(this))
2799 validation.i18n('Must be a valid IP address');
2803 'ip4addr': function()
2805 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2807 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2808 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2809 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2810 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2811 ((RegExp.$6.indexOf('.') < 0)
2812 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2813 : (validation.types['ip4addr'].apply(RegExp.$6))))
2817 validation.i18n('Must be a valid IPv4 address');
2821 'ip6addr': function()
2823 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2825 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2827 var addr = RegExp.$1;
2834 if (addr.indexOf('.') > 0)
2836 var off = addr.lastIndexOf(':');
2838 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2840 validation.i18n('Must be a valid IPv6 address');
2844 addr = addr.substr(0, off) + ':0:0';
2847 if (addr.indexOf('::') >= 0)
2852 for (var i = 1; i < (addr.length-1); i++)
2853 if (addr.charAt(i) == ':')
2858 validation.i18n('Must be a valid IPv6 address');
2862 for (var i = 0; i < (7 - colons); i++)
2865 if (addr.match(/^(.*?)::(.*?)$/))
2866 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2867 (RegExp.$2 ? ':' + RegExp.$2 : '');
2870 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2873 validation.i18n('Must be a valid IPv6 address');
2883 if (validation.types['integer'].apply(this) &&
2884 (this >= 0) && (this <= 65535))
2887 validation.i18n('Must be a valid port number');
2891 'portrange': function()
2893 if (this.match(/^(\d+)-(\d+)$/))
2898 if (validation.types['port'].apply(p1) &&
2899 validation.types['port'].apply(p2) &&
2900 (parseInt(p1) <= parseInt(p2)))
2903 else if (validation.types['port'].apply(this))
2908 validation.i18n('Must be a valid port range');