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 alphacmp = function(a, b)
190 var retcb = function(cb, rv)
192 if (typeof(cb) == 'function')
198 var isa = function(x, t)
200 if (typeof(x) != 'string' && typeof(t) == 'string')
201 return (Object.prototype.toString.call(x) == '[object ' + t + ']');
203 return (Object.prototype.toString.call(x) == Object.prototype.toString.call(t));
206 var rcall = function(obj, func, params, res_attr, res_default, cb, filter)
208 if (typeof(params) == 'undefined')
211 return _luci2.rpc.call(obj, func, params).then(function(res) {
212 if (res[0] != 0 || typeof(res[1]) == 'undefined')
213 return retcb(cb, res_default);
215 var rv = (typeof(res_attr) != 'undefined') ? res[1][res_attr] : res[1];
216 if (typeof(rv) == 'undefined' || (typeof(res_default) != 'undefined' && !isa(rv, res_default)))
217 return retcb(cb, res_default);
219 if (typeof(filter) == 'function')
222 return retcb(cb, rv);
226 var Class = function() { };
228 Class.extend = function(properties)
230 Class.initializing = true;
232 var prototype = new this();
233 var superprot = this.prototype;
235 Class.initializing = false;
237 $.extend(prototype, properties, {
238 callSuper: function() {
240 var meth = arguments[0];
242 if (typeof(superprot[meth]) != 'function')
245 for (var i = 1; i < arguments.length; i++)
246 args.push(arguments[i]);
248 return superprot[meth].apply(this, args);
254 this.options = arguments[0] || { };
256 if (!Class.initializing && typeof(this.init) == 'function')
257 this.init.apply(this, arguments);
260 _class.prototype = prototype;
261 _class.prototype.constructor = _class;
263 _class.extend = arguments.callee;
268 this.defaults = function(obj, def)
271 if (typeof(obj[key]) == 'undefined')
277 this.deferred = function(x)
279 return (typeof(x) == 'object' &&
280 typeof(x.then) == 'function' &&
281 typeof(x.promise) == 'function');
284 this.deferrable = function()
286 if (this.deferred(arguments[0]))
289 var d = $.Deferred();
290 d.resolve.apply(d, arguments);
299 plural: function(n) { return 0 + (n != 1) },
302 if (_luci2.i18n.loaded)
305 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
306 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
308 for (var i = 0; i < langs.length; i++)
309 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
313 success: function(data) {
314 $.extend(_luci2.i18n.catalog, data);
316 var pe = _luci2.i18n.catalog[''];
319 delete _luci2.i18n.catalog[''];
321 var pf = new Function('n', 'return 0 + (' + pe + ')');
322 _luci2.i18n.plural = pf;
328 _luci2.i18n.loaded = true;
333 this.tr = function(msgid)
337 var msgstr = _luci2.i18n.catalog[msgid];
339 if (typeof(msgstr) == 'undefined')
341 else if (typeof(msgstr) == 'string')
347 this.trp = function(msgid, msgid_plural, count)
351 var msgstr = _luci2.i18n.catalog[msgid];
353 if (typeof(msgstr) == 'undefined')
354 return (count == 1) ? msgid : msgid_plural;
355 else if (typeof(msgstr) == 'string')
358 return msgstr[_luci2.i18n.plural(count)];
361 this.trc = function(msgctx, msgid)
365 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
367 if (typeof(msgstr) == 'undefined')
369 else if (typeof(msgstr) == 'string')
375 this.trcp = function(msgctx, msgid, msgid_plural, count)
379 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
381 if (typeof(msgstr) == 'undefined')
382 return (count == 1) ? msgid : msgid_plural;
383 else if (typeof(msgstr) == 'string')
386 return msgstr[_luci2.i18n.plural(count)];
389 this.setHash = function(key, value)
392 var data = this.getHash(undefined);
394 if (typeof(value) == 'undefined')
405 for (var i = 0; i < keys.length; i++)
410 h += keys[i] + ':' + data[keys[i]];
414 location.hash = '#' + h;
417 this.getHash = function(key)
420 var tuples = (location.hash || '#').substring(1).split(/,/);
422 for (var i = 0; i < tuples.length; i++)
424 var tuple = tuples[i].split(/:/);
425 if (tuple.length == 2)
426 data[tuple[0]] = tuple[1];
429 if (typeof(key) != 'undefined')
437 sid: '00000000000000000000000000000000'
444 _wrap_msg: function(method, object, func, args)
446 if (typeof(args) != 'object')
450 id: _luci2.rpc._msg_id++,
453 params: (method == 'call') ? [ _luci2.globals.sid, object, func, args ] : object
457 _parse_response: function(keys, priv)
459 return function(data) {
462 obj = $.parseJSON(data);
465 if (typeof(obj) != 'object')
468 /* is a batched response */
472 for (var i = 0; i < obj.length; i++)
474 var p = (typeof(priv) != 'undefined') ? priv[i] : undefined;
476 if ($.isArray(obj[i].result) && typeof(priv) != 'undefined')
477 obj[i].result[2] = p;
479 if (obj[i].jsonrpc != '2.0' || obj[i].error || !obj[i].result)
480 rv[keys[i]] = [ 4 /* UBUS_STATUS_NO_DATA */, undefined, p ];
482 rv[keys[i]] = obj[i].result;
487 if (obj.jsonrpc != '2.0' || obj.error || !obj.result)
488 return [ 4 /* UBUS_STATUS_NO_DATA */, undefined, priv ];
490 if ($.isArray(obj.result) && typeof(priv) != 'undefined')
491 obj.result[2] = priv;
497 _post_msg: function(message, cb, keys, priv)
499 return $.ajax('/ubus', {
501 contentType: 'application/json',
502 data: JSON.stringify(message),
503 dataFilter: _luci2.rpc._parse_response(keys, priv),
510 _post_single: function(object, method, args, cb, priv)
512 var msg = _luci2.rpc._wrap_msg('call', object, method, args, priv);
513 return _luci2.rpc._post_msg(msg, cb, undefined, priv);
516 _post_batch: function(methods, cb)
518 if (typeof(methods) != 'object')
525 for (var k in methods)
527 if (typeof(methods[k]) != 'object' || methods[k].length < 2)
531 priv.push(methods[k][3]);
532 msgs.push(_luci2.rpc._wrap_msg('call', methods[k][0], methods[k][1], methods[k][2]));
536 return _luci2.rpc._post_msg(msgs, cb, keys, priv);
538 return _luci2.deferrable([ ]);
544 if (typeof a[0] == 'string')
545 return _luci2.rpc._post_single(a[0], a[1], a[2], a[3], a[4]);
547 return _luci2.rpc._post_batch(a[0], a[1]);
550 list: function(objects)
552 var msg = _luci2.rpc._wrap_msg('list', objects);
553 return _luci2.rpc._post_msg(msg);
556 access: function(scope, object, method, cb)
558 return _luci2.rpc._post_single('session', 'access', {
559 'sid': _luci2.globals.sid,
564 return retcb(cb, (rv[0] == 0 && rv[1] && rv[1].access == true));
571 writable: function(cb)
573 return _luci2.rpc.access('ubus', 'uci', 'commit', cb);
576 add: function(config, type, cb)
578 return rcall('uci', 'add', { config: config, type: type }, 'section', '', cb);
586 changes: function(config)
588 return rcall('uci', 'changes', { config: config }, 'changes', [ ], cb);
591 commit: function(config)
593 return rcall('uci', 'commit', { config: config }, undefined, undefined, cb);
596 'delete': function(config, section, option)
598 var req = { config: config, section: section };
600 if (isa(option, 'Array'))
601 req.options = option;
605 return rcall('uci', 'delete', req, undefined, undefined, cb);
608 delete_all: function(config, type, matches)
610 return rcall('uci', 'delete', { config: config, type: type, match: matches }, undefined, undefined, cb);
613 foreach: function(config, type, cb)
615 return rcall('uci', 'get', { config: config, type: type }, 'values', { }, function(sections) {
616 for (var s in sections)
621 get: function(config, section, option, cb)
623 return rcall('uci', 'get', { config: config, section: section, option: option }, undefined, { }, function(res) {
624 if (typeof(option) == 'undefined')
625 return retcb(cb, (res.values && res.values['.type']) ? res.values['.type'] : undefined);
627 return retcb(cb, res.value);
631 get_all: function(config, section, cb)
633 return rcall('uci', 'get', { config: config, section: section }, 'values', { }, cb);
636 get_first: function(config, type, option, cb)
638 return rcall('uci', 'get', { config: config, type: type }, 'values', { }, function(sections) {
639 for (var s in sections)
641 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
643 if (typeof(val) != 'undefined')
644 return retcb(cb, val);
647 return retcb(cb, undefined);
651 section: function(config, type, name, values, cb)
653 return rcall('uci', 'add', { config: config, type: type, name: name, values: values }, 'section', undefined, cb);
656 set: function(config, section, option, value, cb)
658 if (typeof(value) == 'undefined' && typeof(option) == 'string')
659 return rcall('uci', 'add', { config: config, section: section, type: option }, undefined, undefined, cb);
660 else if (isa(option, 'Object'))
661 return rcall('uci', 'set', { config: config, section: section, values: option }, undefined, undefined, cb);
665 values[option] = value;
667 return rcall('uci', 'set', { config: config, section: section, values: values }, undefined, undefined, cb);
670 order: function(config, sections, cb)
672 return rcall('uci', 'order', { config: config, sections: sections }, undefined, undefined, cb);
677 getNetworkStatus: function(cb)
680 var assign = function(target, key)
682 return function(value) {
683 if (typeof(value) != 'undefined' && !$.isEmptyObject(value))
688 return _luci2.rpc.list().then(function(data) {
691 for (var i = 0; i < data.length; i++)
693 if (data[i].indexOf('network.interface.') != 0)
696 var ifname = data[i].substring(18);
697 if (ifname == 'loopback')
700 var iface = { 'name': ifname };
703 requests.push(['network.interface', 'status', { 'interface': ifname }, iface]);
706 return _luci2.rpc.call(requests, function(responses) {
707 for (var key in responses)
708 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
709 $.extend(responses[key][2], responses[key][1]);
714 for (var i = 0; i < ifaces.length; i++)
716 var iface = ifaces[i];
718 var dev = iface.l3_device || iface.l2_device;
722 iface.device = { 'name': dev };
723 requests[dev] = ['network.device', 'status', { 'name': dev }, iface.device];
726 return _luci2.rpc.call(requests, function(responses) {
727 for (var key in responses)
728 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
729 $.extend(responses[key][2], responses[key][1]);
734 for (var i = 0; i < ifaces.length; i++)
736 var iface = ifaces[i];
740 var subdevs = iface.device['bridge-members'];
744 iface.subdevices = [ ];
745 for (var j = 0; j < subdevs.length; j++)
747 iface.subdevices[j] = { 'name': subdevs[j] };
748 requests.push(['network.device', 'status', { 'name': subdevs[j] }, iface.subdevices[j]]);
752 return _luci2.rpc.call(requests, function(responses) {
753 for (var key in responses)
754 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
755 $.extend(responses[key][2], responses[key][1]);
760 for (var i = 0; i < ifaces.length; i++)
762 var iface = ifaces[i];
765 requests.push(['iwinfo', 'info', { 'device': iface.device.name }, iface.device]);
767 if (iface.subdevices)
768 for (var j = 0; j < iface.subdevices.length; j++)
769 requests.push(['iwinfo', 'info', { 'device': iface.subdevices[j].name }, iface.subdevices[j]]);
772 return _luci2.rpc.call(requests, function(responses) {
773 for (var key in responses)
774 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
775 if (!$.isEmptyObject(responses[key][1]))
776 responses[key][2].wireless = responses[key][1];
779 ifaces.sort(function(a, b) {
780 if (a['interface'] < b['interface'])
782 else if (a['interface'] > b['interface'])
787 return retcb(cb, ifaces);
791 findWanInterfaces: function(cb)
793 return _luci2.rpc.list().then(function(data) {
795 for (var i = 0; i < data.length; i++)
797 if (data[i].indexOf('network.interface.') == 0)
799 var ifname = data[i].substring(18);
800 requests[ifname] = ['network.interface', 'status', { 'interface': ifname }];
803 return _luci2.rpc.call(requests);
804 }).then(function(responses) {
806 for (var ifname in responses)
808 var response = responses[ifname];
810 if (response[0] != 0 || !response[1] || !response[1].route)
813 for (var rn = 0, rt = response[1].route[rn];
814 rn < response[1].route.length;
815 rn++, rt = response[1].route[rn])
817 if (typeof(rt.table) != 'undefined')
820 if (rt.target == '0.0.0.0' && rt.mask == 0)
822 else if (rt.target == '::' && rt.mask == 0)
827 return retcb(cb, rv);
831 getDHCPLeases: function(cb)
833 return rcall('luci2.network', 'dhcp_leases', undefined, 'leases', [ ], cb);
836 getDHCPv6Leases: function(cb)
838 return rcall('luci2.network', 'dhcp6_leases', undefined, 'leases', [ ], cb);
841 getRoutes: function(cb)
843 return rcall('luci2.network', 'routes', undefined, 'routes', [ ], cb);
846 getIPv6Routes: function(cb)
848 return rcall('luci2.network', 'routes6', undefined, 'routes', [ ], cb);
851 getARPTable: function(cb)
853 return rcall('luci2.network', 'arp_table', undefined, 'entries', [ ], cb);
856 getInterfaceStatus: function(iface, cb)
858 return rcall('network.interface', 'status', { 'interface': iface }, undefined, { }, cb, function(rv) {
859 rv['interface'] = iface;
860 rv['l2_device'] = rv['device'];
865 getDeviceStatus: function(dev, cb)
867 return rcall('network.device', 'status', { name: dev }, undefined, { }, cb, function(rv) {
868 if (typeof(dev) == 'string')
874 getConntrackCount: function(cb)
876 return rcall('luci2.network', 'conntrack_count', undefined, undefined, {
884 getDevices: function(cb) {
885 return rcall('iwinfo', 'devices', undefined, 'devices', [ ], cb, function(rv) {
891 getInfo: function(dev, cb) {
892 var parse_info = function(device, info, rv)
899 var phy = rv[info.phy];
902 'country', 'channel', 'frequency', 'frequency_offset',
903 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
907 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
908 'signal', 'noise', 'bitrate', 'encryption'
911 for (var i = 0; i < phy_attrs.length; i++)
912 phy[phy_attrs[i]] = info[phy_attrs[i]];
918 for (var i = 0; i < net_attrs.length; i++)
919 net[net_attrs[i]] = info[net_attrs[i]];
921 phy.networks.push(net);
928 return _luci2.wireless.getDevices().then(function(devices) {
931 for (var i = 0; i < devices.length; i++)
933 if (devices[i].indexOf('.sta') >= 0)
936 requests[devices[i]] = [ 'iwinfo', 'info', { device: devices[i] } ];
939 return _luci2.rpc.call(requests);
940 }).then(function(responses) {
943 for (var device in responses)
945 var response = responses[device];
947 if (response[0] != 0 || !response[1])
950 parse_info(device, response[1], rv);
953 return retcb(cb, rv);
957 return _luci2.rpc.call('iwinfo', 'info', { device: dev }).then(function(response) {
958 if (response[0] != 0 || !response[1])
959 return retcb(cb, { });
961 return retcb(cb, parse_info(dev, response[1], { }));
965 getAssocList: function(dev, cb)
969 return _luci2.wireless.getDevices().then(function(devices) {
972 for (var i = 0; i < devices.length; i++)
974 if (devices[i].indexOf('.sta') >= 0)
977 requests[devices[i]] = [ 'iwinfo', 'assoclist', { device: devices[i] } ];
980 return _luci2.rpc.call(requests);
981 }).then(function(responses) {
984 for (var device in responses)
986 var response = responses[device];
988 if (response[0] != 0 || !response[1] || !response[1].results)
991 for (var i = 0; i < response[1].results.length; i++)
993 var station = response[1].results[i];
995 station.device = device;
1000 rv.sort(function(a, b) {
1001 return (a.device == b.device)
1002 ? (a.bssid < b.bssid)
1003 : (a.device > b.device)
1007 return retcb(cb, rv);
1011 return _luci2.rpc.call('iwinfo', 'assoclist', { device: dev }).then(function(response) {
1014 if (response[0] != 0 || !response[1] || !response[1].results)
1015 return retcb(cb, rv);
1017 for (var i = 0; i < response[1].results.length; i++)
1019 var station = response[1].results[i];
1021 station.device = dev;
1025 rv.sort(function(a, b) {
1026 return (a.bssid < b.bssid);
1029 return retcb(cb, rv);
1033 formatEncryption: function(enc)
1035 var format_list = function(l, s)
1038 for (var i = 0; i < l.length; i++)
1039 rv.push(l[i].toUpperCase());
1040 return rv.join(s ? s : ', ');
1043 if (!enc || !enc.enabled)
1044 return _luci2.tr('None');
1048 if (enc.wep.length == 2)
1049 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1050 else if (enc.wep[0] == 'shared')
1051 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1053 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1057 if (enc.wpa.length == 2)
1058 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1059 format_list(enc.authentication, '/'),
1060 format_list(enc.ciphers, ', ')
1062 else if (enc.wpa[0] == 2)
1063 return 'WPA2 %s (%s)'.format(
1064 format_list(enc.authentication, '/'),
1065 format_list(enc.ciphers, ', ')
1068 return 'WPA %s (%s)'.format(
1069 format_list(enc.authentication, '/'),
1070 format_list(enc.ciphers, ', ')
1074 return _luci2.tr('Unknown');
1079 getInfo: function(cb)
1081 return _luci2.rpc.call({
1082 info: [ 'system', 'info', { } ],
1083 board: [ 'system', 'board', { } ],
1084 disk: [ 'luci2.system', 'diskfree', { } ]
1085 }).then(function(responses) {
1088 if (responses.info[0] == 0)
1089 $.extend(rv, responses.info[1]);
1091 if (responses.board[0] == 0)
1092 $.extend(rv, responses.board[1]);
1094 if (responses.disk[0] == 0)
1095 $.extend(rv, responses.disk[1]);
1097 return retcb(cb, rv);
1101 getProcessList: function(cb)
1103 return rcall('luci2.system', 'process_list', undefined, 'processes', [ ], cb, function(rv) {
1104 rv.sort(function(a, b) { return a.pid - b.pid });
1109 getSystemLog: function(cb)
1111 return rcall('luci2.system', 'syslog', undefined, 'log', '', cb);
1114 getKernelLog: function(cb)
1116 return rcall('luci2.system', 'dmesg', undefined, 'log', '', cb);
1119 getZoneInfo: function(cb)
1121 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1124 canSendSignal: function(cb)
1126 return _luci2.rpc.access('ubus', 'luci2.system', 'process_signal', cb);
1129 sendSignal: function(pid, sig, cb)
1131 return _luci2.rpc.call('luci2.system', 'process_signal', { pid: pid, signal: sig }).then(function(response) {
1132 return retcb(cb, response[0] == 0);
1136 initList: function(cb)
1138 return rcall('luci2.system', 'init_list', undefined, 'initscripts', [ ], cb, function(rv) {
1139 rv.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1144 initEnabled: function(init, cb)
1146 return this.initList(function(list) {
1147 for (var i = 0; i < list.length; i++)
1148 if (list[i].name == init)
1149 return retcb(cb, !!list[i].enabled);
1151 return retcb(cb, false);
1155 initRun: function(init, action, cb)
1157 return _luci2.rpc.call('luci2.system', 'init_action', { name: init, action: action }).then(function(response) {
1158 return retcb(cb, response[0] == 0);
1162 canInitRun: function(cb)
1164 return _luci2.rpc.access('ubus', 'luci2.system', 'init_action', cb);
1167 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1168 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1169 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1170 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1171 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1172 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1175 getRcLocal: function(cb)
1177 return rcall('luci2.system', 'rclocal_get', undefined, 'data', '', cb);
1180 setRcLocal: function(data, cb)
1182 return rcall('luci2.system', 'rclocal_set', { data: data }, undefined, undefined, cb);
1185 canSetRcLocal: function(cb)
1187 return _luci2.rpc.access('ubus', 'luci2.system', 'rclocal_set', cb);
1191 getCrontab: function(cb)
1193 return rcall('luci2.system', 'crontab_get', undefined, 'data', '', cb);
1196 setCrontab: function(data, cb)
1198 return rcall('luci2.system', 'crontab_set', { data: data }, undefined, undefined, cb);
1201 canSetCrontab: function(cb)
1203 return _luci2.rpc.access('ubus', 'luci2.system', 'crontab_set', cb);
1207 getSSHKeys: function(cb)
1209 return rcall('luci2.system', 'sshkeys_get', undefined, 'keys', [ ], cb);
1212 setSSHKeys: function(keys, cb)
1214 return rcall('luci2.system', 'sshkeys_set', { keys: keys }, undefined, undefined, cb);
1217 canSetSSHKeys: function(cb)
1219 return _luci2.rpc.access('ubus', 'luci2.system', 'sshkeys_set', cb);
1223 setPassword: function(user, pass, cb)
1225 return rcall('luci2.system', 'password_set', { user: user, password: pass }, undefined, undefined, cb);
1228 canSetPassword: function(cb)
1230 return _luci2.rpc.access('ubus', 'luci2.system', 'password_set', cb);
1234 listLEDs: function(cb)
1236 return rcall('luci2.system', 'led_list', undefined, 'leds', [ ], cb);
1239 listUSBDevices: function(cb)
1241 return rcall('luci2.system', 'usb_list', undefined, 'devices', [ ], cb);
1245 testUpgrade: function(cb)
1247 return rcall('luci2.system', 'upgrade_test', undefined, undefined, { }, cb);
1250 startUpgrade: function(keep, cb)
1252 return rcall('luci2.system', 'upgrade_start', { keep: !!keep }, undefined, undefined, cb);
1255 cleanUpgrade: function(cb)
1257 return rcall('luci2.system', 'upgrade_clean', undefined, undefined, undefined, cb);
1260 canUpgrade: function(cb)
1262 return _luci2.rpc.access('ubus', 'luci2.system', 'upgrade_start', cb);
1266 restoreBackup: function(cb)
1268 return rcall('luci2.system', 'backup_restore', undefined, undefined, undefined, cb);
1271 cleanBackup: function(cb)
1273 return rcall('luci2.system', 'backup_clean', undefined, undefined, undefined, cb);
1276 canRestoreBackup: function(cb)
1278 return _luci2.rpc.access('ubus', 'luci2.system', 'backup_restore', cb);
1282 getBackupConfig: function(cb)
1284 return rcall('luci2.system', 'backup_config_get', undefined, 'config', '', cb);
1287 setBackupConfig: function(data, cb)
1289 return rcall('luci2.system', 'backup_config_set', { data: data }, undefined, undefined, cb);
1292 canSetBackupConfig: function(cb)
1294 return _luci2.rpc.access('ubus', 'luci2.system', 'backup_config_set', cb);
1298 listBackup: function(cb)
1300 return rcall('luci2.system', 'backup_list', undefined, 'files', [ ], cb);
1304 performReboot: function(cb)
1306 return rcall('luci2.system', 'reboot', undefined, undefined, undefined, cb);
1309 canPerformReboot: function(cb)
1311 return _luci2.rpc.access('ubus', 'luci2.system', 'reboot', cb);
1316 updateLists: function(cb)
1318 return rcall('luci2.opkg', 'update', undefined, undefined, { }, cb);
1321 _fetchPackages: function(action, offset, limit, pattern, cb)
1324 var reqlimit = Math.min(limit, 100);
1329 return _luci2.rpc.call('luci2.opkg', action, { offset: offset, limit: reqlimit, pattern: pattern }).then(function(response) {
1330 if (response[0] != 0 || !response[1] || !response[1].total)
1331 return retcb(cb, { length: 0, total: 0 });
1333 packages.push.apply(packages, response[1].packages);
1334 packages.total = response[1].total;
1337 limit = response[1].total;
1339 if (packages.length >= limit)
1340 return retcb(cb, packages);
1343 for (var i = offset + packages.length; i < limit; i += 100)
1344 requests.push(['luci2.opkg', action, { offset: i, limit: (Math.min(i + 100, limit) % 100) || 100, pattern: pattern }]);
1346 return _luci2.rpc.call(requests);
1347 }).then(function(responses) {
1348 for (var key in responses)
1350 var response = responses[key];
1352 if (response[0] != 0 || !response[1] || !response[1].packages)
1355 packages.push.apply(packages, response[1].packages);
1356 packages.total = response[1].total;
1359 return retcb(cb, packages);
1363 listPackages: function(offset, limit, pattern, cb)
1365 return _luci2.opkg._fetchPackages('list', offset, limit, pattern, cb);
1368 installedPackages: function(offset, limit, pattern, cb)
1370 return _luci2.opkg._fetchPackages('list_installed', offset, limit, pattern, cb);
1373 findPackages: function(offset, limit, pattern, cb)
1375 return _luci2.opkg._fetchPackages('find', offset, limit, pattern, cb);
1378 installPackage: function(name, cb)
1380 return rcall('luci2.opkg', 'install', { 'package': name }, undefined, { }, cb);
1383 removePackage: function(name, cb)
1385 return rcall('luci2.opkg', 'remove', { 'package': name }, undefined, { }, cb);
1388 getConfig: function(cb)
1390 return rcall('luci2.opkg', 'config_get', undefined, 'config', '', cb);
1393 setConfig: function(data, cb)
1395 return rcall('luci2.opkg', 'config_set', { data: data }, undefined, undefined, cb);
1398 canInstallPackage: function(cb)
1400 return _luci2.rpc.access('ubus', 'luci2.opkg', 'install', cb);
1403 canRemovePackage: function(cb)
1405 return _luci2.rpc.access('ubus', 'luci2.opkg', 'remove', cb);
1408 canSetConfig: function(cb)
1410 return _luci2.rpc.access('ubus', 'luci2.opkg', 'config_set', cb);
1416 loading: function(enable)
1418 var win = $(window);
1419 var body = $('body');
1420 var div = _luci2._modal || (
1421 _luci2._modal = $('<div />')
1422 .addClass('cbi-modal-loader')
1423 .append($('<div />').text(_luci2.tr('Loading data...')))
1429 body.css('overflow', 'hidden');
1430 body.css('padding', 0);
1431 body.css('width', win.width());
1432 body.css('height', win.height());
1433 div.css('width', win.width());
1434 div.css('height', win.height());
1440 body.css('overflow', '');
1441 body.css('padding', '');
1442 body.css('width', '');
1443 body.css('height', '');
1447 dialog: function(title, content, options)
1449 var win = $(window);
1450 var body = $('body');
1451 var div = _luci2._dialog || (
1452 _luci2._dialog = $('<div />')
1453 .addClass('cbi-modal-dialog')
1454 .append($('<div />')
1455 .append($('<div />')
1456 .addClass('cbi-modal-dialog-header'))
1457 .append($('<div />')
1458 .addClass('cbi-modal-dialog-body'))
1459 .append($('<div />')
1460 .addClass('cbi-modal-dialog-footer')
1461 .append($('<button />')
1462 .addClass('cbi-button')
1463 .text(_luci2.tr('Close'))
1466 .css('overflow', '')
1471 $(this).parent().parent().parent().hide();
1476 if (typeof(options) != 'object')
1479 if (title === false)
1482 .css('overflow', '')
1487 _luci2._dialog.hide();
1492 var cnt = div.children().children('div.cbi-modal-dialog-body');
1493 var ftr = div.children().children('div.cbi-modal-dialog-footer');
1497 if (options.style == 'confirm')
1499 ftr.append($('<button />')
1500 .addClass('cbi-button')
1501 .text(_luci2.tr('Ok'))
1502 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1504 ftr.append($('<button />')
1505 .addClass('cbi-button')
1506 .text(_luci2.tr('Cancel'))
1507 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1509 else if (options.style == 'close')
1511 ftr.append($('<button />')
1512 .addClass('cbi-button')
1513 .text(_luci2.tr('Close'))
1514 .click(options.close || function() { _luci2.ui.dialog(false) }));
1516 else if (options.style == 'wait')
1518 ftr.append($('<button />')
1519 .addClass('cbi-button')
1520 .text(_luci2.tr('Close'))
1521 .attr('disabled', true));
1524 div.find('div.cbi-modal-dialog-header').text(title);
1528 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1533 .css('margin-top', -Math.floor(div.children().height() / 2) + 'px');
1535 body.css('overflow', 'hidden');
1536 body.css('padding', 0);
1537 body.css('width', win.width());
1538 body.css('height', win.height());
1539 div.css('width', win.width());
1540 div.css('height', win.height());
1543 upload: function(title, content, options)
1545 var form = _luci2._upload || (
1546 _luci2._upload = $('<form />')
1547 .attr('method', 'post')
1548 .attr('action', '/cgi-bin/luci-upload')
1549 .attr('enctype', 'multipart/form-data')
1550 .attr('target', 'cbi-fileupload-frame')
1552 .append($('<input />')
1553 .attr('type', 'hidden')
1554 .attr('name', 'sessionid')
1555 .attr('value', _luci2.globals.sid))
1556 .append($('<input />')
1557 .attr('type', 'hidden')
1558 .attr('name', 'filename')
1559 .attr('value', options.filename))
1560 .append($('<input />')
1561 .attr('type', 'file')
1562 .attr('name', 'filedata')
1563 .addClass('cbi-input-file'))
1564 .append($('<div />')
1565 .css('width', '100%')
1566 .addClass('progressbar')
1567 .addClass('intermediate')
1568 .append($('<div />')
1569 .css('width', '100%')))
1570 .append($('<iframe />')
1571 .attr('name', 'cbi-fileupload-frame')
1572 .css('width', '1px')
1573 .css('height', '1px')
1574 .css('visibility', 'hidden'))
1577 var finish = _luci2._upload_finish_cb || (
1578 _luci2._upload_finish_cb = function(ev) {
1579 $(this).off('load');
1581 var body = (this.contentDocument || this.contentWindow.document).body;
1582 if (body.firstChild.tagName.toLowerCase() == 'pre')
1583 body = body.firstChild;
1587 json = $.parseJSON(body.innerHTML);
1590 message: _luci2.tr('Invalid server response received'),
1591 error: [ -1, _luci2.tr('Invalid data') ]
1597 L.ui.dialog(L.tr('File upload'), [
1598 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1599 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1600 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1601 ], { style: 'close' });
1603 else if (typeof(ev.data.cb) == 'function')
1610 var confirm = _luci2._upload_confirm_cb || (
1611 _luci2._upload_confirm_cb = function() {
1612 var d = _luci2._upload;
1613 var f = d.find('.cbi-input-file');
1614 var b = d.find('.progressbar');
1615 var p = d.find('p');
1620 d.find('iframe').on('load', { cb: options.success }, finish);
1625 p.text(_luci2.tr('File upload in progress …'));
1627 _luci2._dialog.find('button').prop('disabled', true);
1631 _luci2._upload.find('.progressbar').hide();
1632 _luci2._upload.find('.cbi-input-file').val('').show();
1633 _luci2._upload.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1635 _luci2.ui.dialog(title || _luci2.tr('File upload'), _luci2._upload, {
1641 reconnect: function()
1643 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1644 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1645 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1647 var interval, timeout;
1650 _luci2.tr('Waiting for device'), [
1651 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1653 .css('width', '100%')
1654 .addClass('progressbar')
1655 .addClass('intermediate')
1656 .append($('<div />')
1657 .css('width', '100%'))
1658 ], { style: 'wait' }
1661 for (var i = 0; i < protocols.length; i++)
1662 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1664 //_luci2.network.getNetworkStatus(function(s) {
1665 // for (var i = 0; i < protocols.length; i++)
1667 // for (var j = 0; j < s.length; j++)
1669 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1670 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1672 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1673 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1676 //}).then(function() {
1677 images.on('load', function() {
1678 var url = this.getAttribute('url');
1679 _luci2.rpc.access('ubus', 'session', 'access').then(function(response) {
1680 if (response[0] == 0)
1682 window.clearTimeout(timeout);
1683 window.clearInterval(interval);
1684 _luci2.ui.dialog(false);
1689 location.href = url;
1694 interval = window.setInterval(function() {
1695 images.each(function() {
1696 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1700 timeout = window.setTimeout(function() {
1701 window.clearInterval(interval);
1705 _luci2.tr('Device not responding'),
1706 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1713 login: function(invalid)
1715 if (!_luci2._login_deferred || _luci2._login_deferred.state() != 'pending')
1716 _luci2._login_deferred = $.Deferred();
1718 /* try to find sid from hash */
1719 var sid = _luci2.getHash('id');
1720 if (sid && sid.match(/^[a-f0-9]{32}$/))
1722 _luci2.globals.sid = sid;
1723 _luci2.rpc.access('ubus', 'session', 'access').then(function(response) {
1724 if (response[0] == 0)
1726 _luci2._login_deferred.resolve();
1730 _luci2.setHash('id', undefined);
1735 return _luci2._login_deferred;
1738 var form = _luci2._login || (
1739 _luci2._login = $('<div />')
1741 .addClass('alert-message')
1742 .text(_luci2.tr('Wrong username or password given!')))
1744 .append($('<label />')
1745 .text(_luci2.tr('Username'))
1746 .append($('<br />'))
1747 .append($('<input />')
1748 .attr('type', 'text')
1749 .attr('name', 'username')
1750 .attr('value', 'root')
1751 .addClass('cbi-input-text'))))
1753 .append($('<label />')
1754 .text(_luci2.tr('Password'))
1755 .append($('<br />'))
1756 .append($('<input />')
1757 .attr('type', 'password')
1758 .attr('name', 'password')
1759 .addClass('cbi-input-password'))))
1761 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok'))))
1764 var response_cb = _luci2._login_response_cb || (
1765 _luci2._login_response_cb = function(response) {
1768 _luci2.ui.login(true);
1772 _luci2.globals.sid = response.sid;
1773 _luci2.setHash('id', _luci2.globals.sid);
1775 _luci2.ui.dialog(false);
1776 _luci2._login_deferred.resolve();
1781 var confirm_cb = _luci2._login_confirm_cb || (
1782 _luci2._login_confirm_cb = function() {
1783 var d = _luci2._login;
1784 var u = d.find('[name=username]').val();
1785 var p = d.find('[name=password]').val();
1791 _luci2.tr('Logging in'), [
1792 $('<p />').text(_luci2.tr('Log in in progress …')),
1794 .css('width', '100%')
1795 .addClass('progressbar')
1796 .addClass('intermediate')
1797 .append($('<div />')
1798 .css('width', '100%'))
1799 ], { style: 'wait' }
1802 rcall('session', 'login', { username: u, password: p }, undefined, { }, response_cb);
1807 form.find('.alert-message').show();
1809 form.find('.alert-message').hide();
1811 _luci2.ui.dialog(_luci2.tr('Authorization Required'), form, {
1816 return _luci2._login_deferred;
1819 renderMainMenu: function()
1821 return rcall('luci2.ui', 'menu', undefined, 'menu', { }, function(entries) {
1822 _luci2.globals.mainMenu = new _luci2.ui.menu();
1823 _luci2.globals.mainMenu.entries(entries);
1827 .append(_luci2.globals.mainMenu.render(0, 1));
1831 renderViewMenu: function()
1835 .append(_luci2.globals.mainMenu.render(2, 900));
1838 renderView: function(node)
1840 var name = node.view.split(/\//).join('.');
1842 _luci2.ui.renderViewMenu();
1845 _luci2._views = { };
1847 _luci2.setHash('view', node.view);
1849 if (_luci2._views[name] instanceof _luci2.ui.view)
1850 return _luci2._views[name].render();
1852 return $.ajax(_luci2.globals.resource + '/view/' + name + '.js', {
1856 }).then(function(data) {
1858 var viewConstructor = (new Function(['L', '$'], 'return ' + data))(_luci2, $);
1860 _luci2._views[name] = new viewConstructor({
1862 acls: node.write || { }
1865 return _luci2._views[name].render();
1869 return $.Deferred().resolve();
1875 _luci2.ui.loading(true);
1878 _luci2.ui.renderMainMenu()
1880 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
1881 _luci2.ui.loading(false);
1887 var AbstractWidget = Class.extend({
1888 i18n: function(text) {
1892 toString: function() {
1893 var x = document.createElement('div');
1894 x.appendChild(this.render());
1899 insertInto: function(id) {
1900 return $(id).empty().append(this.render());
1904 this.ui.view = AbstractWidget.extend({
1905 _fetch_template: function()
1907 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
1911 success: function(data) {
1912 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
1913 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
1920 return _luci2.tr(p2);
1923 return _luci2.globals[p2] || '';
1926 return '(?' + match + ')';
1930 $('#maincontent').append(data);
1937 throw "Not implemented";
1942 var container = $('#maincontent');
1947 container.append($('<h2 />').append(this.title));
1949 if (this.description)
1950 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
1953 return this._fetch_template().then(function() {
1954 return _luci2.deferrable(self.execute());
1959 this.ui.menu = AbstractWidget.extend({
1964 entries: function(entries)
1966 for (var entry in entries)
1968 var path = entry.split(/\//);
1969 var node = this._nodes;
1971 for (i = 0; i < path.length; i++)
1976 if (!node.childs[path[i]])
1977 node.childs[path[i]] = { };
1979 node = node.childs[path[i]];
1982 $.extend(node, entries[entry]);
1986 _indexcmp: function(a, b)
1988 var x = a.index || 0;
1989 var y = b.index || 0;
1993 firstChildView: function(node)
1999 for (var child in (node.childs || { }))
2000 nodes.push(node.childs[child]);
2002 nodes.sort(this._indexcmp);
2004 for (var i = 0; i < nodes.length; i++)
2006 var child = this.firstChildView(nodes[i]);
2009 $.extend(node, child);
2017 _onclick: function(ev)
2019 _luci2.ui.loading(true);
2020 _luci2.ui.renderView(ev.data).then(function() {
2021 _luci2.ui.loading(false);
2024 ev.preventDefault();
2028 _render: function(childs, level, min, max)
2031 for (var node in childs)
2033 var child = this.firstChildView(childs[node]);
2035 nodes.push(childs[node]);
2038 nodes.sort(this._indexcmp);
2040 var list = $('<ul />');
2043 list.addClass('nav');
2044 else if (level == 1)
2045 list.addClass('dropdown-menu');
2047 for (var i = 0; i < nodes.length; i++)
2049 if (!_luci2.globals.defaultNode)
2051 var v = _luci2.getHash('view');
2052 if (!v || v == nodes[i].view)
2053 _luci2.globals.defaultNode = nodes[i];
2056 var item = $('<li />')
2059 .text(_luci2.tr(nodes[i].title))
2060 .click(nodes[i], this._onclick))
2063 if (nodes[i].childs && level < max)
2065 item.addClass('dropdown');
2066 item.find('a').addClass('menu');
2067 item.append(this._render(nodes[i].childs, level + 1));
2074 render: function(min, max)
2076 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2077 return this._render(top.childs, 0, min, max);
2080 getNode: function(path, max)
2082 var p = path.split(/\//);
2083 var n = this._nodes;
2085 if (typeof(max) == 'undefined')
2088 for (var i = 0; i < max; i++)
2090 if (!n.childs[p[i]])
2100 this.ui.table = AbstractWidget.extend({
2106 row: function(values)
2108 if (isa(values, 'Array'))
2110 this._rows.push(values);
2112 else if (isa(values, 'Object'))
2115 for (var i = 0; i < this.options.columns.length; i++)
2117 var col = this.options.columns[i];
2119 if (typeof col.key == 'string')
2120 v.push(values[col.key]);
2128 rows: function(rows)
2130 for (var i = 0; i < rows.length; i++)
2134 render: function(id)
2136 var fieldset = document.createElement('fieldset');
2137 fieldset.className = 'cbi-section';
2139 if (this.options.caption)
2141 var legend = document.createElement('legend');
2142 $(legend).append(this.options.caption);
2143 fieldset.appendChild(legend);
2146 var table = document.createElement('table');
2147 table.className = 'cbi-section-table';
2149 var has_caption = false;
2150 var has_description = false;
2152 for (var i = 0; i < this.options.columns.length; i++)
2153 if (this.options.columns[i].caption)
2158 else if (this.options.columns[i].description)
2160 has_description = true;
2166 var tr = table.insertRow(-1);
2167 tr.className = 'cbi-section-table-titles';
2169 for (var i = 0; i < this.options.columns.length; i++)
2171 var col = this.options.columns[i];
2172 var th = document.createElement('th');
2173 th.className = 'cbi-section-table-cell';
2178 th.style.width = col.width;
2181 th.style.textAlign = col.align;
2184 $(th).append(col.caption);
2188 if (has_description)
2190 var tr = table.insertRow(-1);
2191 tr.className = 'cbi-section-table-descr';
2193 for (var i = 0; i < this.options.columns.length; i++)
2195 var col = this.options.columns[i];
2196 var th = document.createElement('th');
2197 th.className = 'cbi-section-table-cell';
2202 th.style.width = col.width;
2205 th.style.textAlign = col.align;
2207 if (col.description)
2208 $(th).append(col.description);
2212 if (this._rows.length == 0)
2214 if (this.options.placeholder)
2216 var tr = table.insertRow(-1);
2217 var td = tr.insertCell(-1);
2218 td.className = 'cbi-section-table-cell';
2220 td.colSpan = this.options.columns.length;
2221 $(td).append(this.options.placeholder);
2226 for (var i = 0; i < this._rows.length; i++)
2228 var tr = table.insertRow(-1);
2230 for (var j = 0; j < this.options.columns.length; j++)
2232 var col = this.options.columns[j];
2233 var td = tr.insertCell(-1);
2235 var val = this._rows[i][j];
2237 if (typeof(val) == 'undefined')
2238 val = col.placeholder;
2240 if (typeof(val) == 'undefined')
2244 td.style.width = col.width;
2247 td.style.textAlign = col.align;
2249 if (typeof col.format == 'string')
2250 $(td).append(col.format.format(val));
2251 else if (typeof col.format == 'function')
2252 $(td).append(col.format(val, i));
2260 fieldset.appendChild(table);
2266 this.ui.progress = AbstractWidget.extend({
2269 var vn = parseInt(this.options.value) || 0;
2270 var mn = parseInt(this.options.max) || 100;
2271 var pc = Math.floor((100 / mn) * vn);
2273 var bar = document.createElement('div');
2274 bar.className = 'progressbar';
2276 bar.appendChild(document.createElement('div'));
2277 bar.lastChild.appendChild(document.createElement('div'));
2278 bar.lastChild.style.width = pc + '%';
2280 if (typeof(this.options.format) == 'string')
2281 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2282 else if (typeof(this.options.format) == 'function')
2283 $(bar.lastChild.lastChild).append(this.options.format(pc));
2285 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2291 this.ui.devicebadge = AbstractWidget.extend({
2294 var dev = this.options.l3_device || this.options.device || '?';
2296 var span = document.createElement('span');
2297 span.className = 'ifacebadge';
2299 if (typeof(this.options.signal) == 'number' ||
2300 typeof(this.options.noise) == 'number')
2303 if (typeof(this.options.signal) != 'undefined' &&
2304 typeof(this.options.noise) != 'undefined')
2306 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2319 span.appendChild(document.createElement('img'));
2320 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2323 span.title = _luci2.tr('No signal');
2325 span.title = '%s: %d %s / %s: %d %s'.format(
2326 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2327 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2332 var type = 'ethernet';
2333 var desc = _luci2.tr('Ethernet device');
2335 if (this.options.l3_device != this.options.device)
2338 desc = _luci2.tr('Tunnel interface');
2340 else if (dev.indexOf('br-') == 0)
2343 desc = _luci2.tr('Bridge');
2345 else if (dev.indexOf('.') > 0)
2348 desc = _luci2.tr('VLAN interface');
2350 else if (dev.indexOf('wlan') == 0 ||
2351 dev.indexOf('ath') == 0 ||
2352 dev.indexOf('wl') == 0)
2355 desc = _luci2.tr('Wireless Network');
2358 span.appendChild(document.createElement('img'));
2359 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2363 $(span).append(' ');
2364 $(span).append(dev);
2370 var type = function(f, l)
2380 _luci2.cbi.validation.message = _luci2.tr(msg);
2383 compile: function(code)
2388 var types = _luci2.cbi.validation.types;
2393 for (var i = 0; i < code.length; i++)
2401 switch (code.charCodeAt(i))
2413 var label = code.substring(pos, i);
2414 label = label.replace(/\\(.)/g, '$1');
2415 label = label.replace(/^[ \t]+/g, '');
2416 label = label.replace(/[ \t]+$/g, '');
2418 if (label && !isNaN(label))
2420 stack.push(parseFloat(label));
2422 else if (label.match(/^(['"]).*\1$/))
2424 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2426 else if (typeof types[label] == 'function')
2428 stack.push(types[label]);
2433 throw "Syntax error, unhandled token '"+label+"'";
2438 depth += (code.charCodeAt(i) == 40);
2444 if (typeof stack[stack.length-2] != 'function')
2445 throw "Syntax error, argument list follows non-function";
2447 stack[stack.length-1] =
2448 arguments.callee(code.substring(pos, i));
2461 var validation = this.cbi.validation;
2463 validation.types = {
2464 'integer': function()
2466 if (this.match(/^-?[0-9]+$/) != null)
2469 validation.i18n('Must be a valid integer');
2473 'uinteger': function()
2475 if (validation.types['integer'].apply(this) && (this >= 0))
2478 validation.i18n('Must be a positive integer');
2484 if (!isNaN(parseFloat(this)))
2487 validation.i18n('Must be a valid number');
2491 'ufloat': function()
2493 if (validation.types['float'].apply(this) && (this >= 0))
2496 validation.i18n('Must be a positive number');
2500 'ipaddr': function()
2502 if (validation.types['ip4addr'].apply(this) ||
2503 validation.types['ip6addr'].apply(this))
2506 validation.i18n('Must be a valid IP address');
2510 'ip4addr': function()
2512 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2514 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2515 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2516 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2517 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2518 ((RegExp.$6.indexOf('.') < 0)
2519 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2520 : (validation.types['ip4addr'].apply(RegExp.$6))))
2524 validation.i18n('Must be a valid IPv4 address');
2528 'ip6addr': function()
2530 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2532 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2534 var addr = RegExp.$1;
2541 if (addr.indexOf('.') > 0)
2543 var off = addr.lastIndexOf(':');
2545 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2547 validation.i18n('Must be a valid IPv6 address');
2551 addr = addr.substr(0, off) + ':0:0';
2554 if (addr.indexOf('::') >= 0)
2559 for (var i = 1; i < (addr.length-1); i++)
2560 if (addr.charAt(i) == ':')
2565 validation.i18n('Must be a valid IPv6 address');
2569 for (var i = 0; i < (7 - colons); i++)
2572 if (addr.match(/^(.*?)::(.*?)$/))
2573 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2574 (RegExp.$2 ? ':' + RegExp.$2 : '');
2577 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2580 validation.i18n('Must be a valid IPv6 address');
2590 if (validation.types['integer'].apply(this) &&
2591 (this >= 0) && (this <= 65535))
2594 validation.i18n('Must be a valid port number');
2598 'portrange': function()
2600 if (this.match(/^(\d+)-(\d+)$/))
2605 if (validation.types['port'].apply(p1) &&
2606 validation.types['port'].apply(p2) &&
2607 (parseInt(p1) <= parseInt(p2)))
2610 else if (validation.types['port'].apply(this))
2615 validation.i18n('Must be a valid port range');
2619 'macaddr': function()
2621 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2624 validation.i18n('Must be a valid MAC address');
2630 if (validation.types['hostname'].apply(this) ||
2631 validation.types['ipaddr'].apply(this))
2634 validation.i18n('Must be a valid hostname or IP address');
2638 'hostname': function()
2640 if ((this.length <= 253) &&
2641 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2642 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2643 this.match(/[^0-9.]/)))))
2646 validation.i18n('Must be a valid host name');
2650 'network': function()
2652 if (validation.types['uciname'].apply(this) ||
2653 validation.types['host'].apply(this))
2656 validation.i18n('Must be a valid network name');
2660 'wpakey': function()
2664 if ((v.length == 64)
2665 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
2666 : ((v.length >= 8) && (v.length <= 63)))
2669 validation.i18n('Must be a valid WPA key');
2673 'wepkey': function()
2677 if (v.substr(0,2) == 's:')
2680 if (((v.length == 10) || (v.length == 26))
2681 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
2682 : ((v.length == 5) || (v.length == 13)))
2685 validation.i18n('Must be a valid WEP key');
2689 'uciname': function()
2691 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2694 validation.i18n('Must be a valid UCI identifier');
2698 'range': function(min, max)
2700 var val = parseFloat(this);
2702 if (validation.types['integer'].apply(this) &&
2703 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
2706 validation.i18n('Must be a number between %d and %d');
2710 'min': function(min)
2712 var val = parseFloat(this);
2714 if (validation.types['integer'].apply(this) &&
2715 !isNaN(min) && !isNaN(val) && (val >= min))
2718 validation.i18n('Must be a number greater or equal to %d');
2722 'max': function(max)
2724 var val = parseFloat(this);
2726 if (validation.types['integer'].apply(this) &&
2727 !isNaN(max) && !isNaN(val) && (val <= max))
2730 validation.i18n('Must be a number lower or equal to %d');
2734 'rangelength': function(min, max)
2736 var val = '' + this;
2738 if (!isNaN(min) && !isNaN(max) &&
2739 (val.length >= min) && (val.length <= max))
2742 validation.i18n('Must be between %d and %d characters');
2746 'minlength': function(min)
2748 var val = '' + this;
2750 if (!isNaN(min) && (val.length >= min))
2753 validation.i18n('Must be at least %d characters');
2757 'maxlength': function(max)
2759 var val = '' + this;
2761 if (!isNaN(max) && (val.length <= max))
2764 validation.i18n('Must be at most %d characters');
2772 for (var i = 0; i < arguments.length; i += 2)
2774 delete validation.message;
2776 if (typeof(arguments[i]) != 'function')
2778 if (arguments[i] == this)
2782 else if (arguments[i].apply(this, arguments[i+1]))
2787 if (validation.message)
2788 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2791 validation.message = msgs.join( _luci2.tr(' - or - '));
2799 for (var i = 0; i < arguments.length; i += 2)
2801 delete validation.message;
2803 if (typeof arguments[i] != 'function')
2805 if (arguments[i] != this)
2809 else if (!arguments[i].apply(this, arguments[i+1]))
2814 if (validation.message)
2815 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2818 validation.message = msgs.join(', ');
2824 return validation.types['or'].apply(
2825 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
2828 'list': function(subvalidator, subargs)
2830 if (typeof subvalidator != 'function')
2833 var tokens = this.match(/[^ \t]+/g);
2834 for (var i = 0; i < tokens.length; i++)
2835 if (!subvalidator.apply(tokens[i], subargs))
2841 'phonedigit': function()
2843 if (this.match(/^[0-9\*#!\.]+$/) != null)
2846 validation.i18n('Must be a valid phone number digit');
2850 'string': function()
2857 var AbstractValue = AbstractWidget.extend({
2858 init: function(name, options)
2861 this.instance = { };
2862 this.dependencies = [ ];
2863 this.rdependency = { };
2865 this.options = _luci2.defaults(options, {
2875 return this.section.id('field', sid || '__unknown__', this.name);
2878 render: function(sid)
2880 var i = this.instance[sid] = { };
2882 i.top = $('<div />').addClass('cbi-value');
2884 if (typeof(this.options.caption) == 'string')
2886 .addClass('cbi-value-title')
2887 .attr('for', this.id(sid))
2888 .text(this.options.caption)
2891 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
2892 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
2894 if (typeof(this.options.description) == 'string')
2896 .addClass('cbi-value-description')
2897 .text(this.options.description)
2903 ucipath: function(sid)
2906 config: (this.options.uci_package || this.map.uci_package),
2907 section: (this.options.uci_section || sid),
2908 option: (this.options.uci_option || this.name)
2912 ucivalue: function(sid)
2914 var uci = this.ucipath(sid);
2915 var val = this.map.get(uci.config, uci.section, uci.option);
2917 if (typeof(val) == 'undefined')
2918 return this.options.initial;
2923 formvalue: function(sid)
2925 var v = $('#' + this.id(sid)).val();
2926 return (v === '') ? undefined : v;
2929 textvalue: function(sid)
2931 var v = this.formvalue(sid);
2933 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
2934 v = this.ucivalue(sid);
2936 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
2937 v = this.options.placeholder;
2939 if (typeof(v) == 'undefined' || v === '')
2942 if (typeof(v) == 'string' && $.isArray(this.choices))
2944 for (var i = 0; i < this.choices.length; i++)
2945 if (v === this.choices[i][0])