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')
443 _wrap_msg: function(method, object, func, args)
445 if (typeof(args) != 'object')
449 id: _luci2.rpc._msg_id++,
452 params: (method == 'call') ? [ _luci2.globals.sid, object, func, args ] : object
456 _parse_response: function(keys, priv)
458 return function(data) {
461 obj = $.parseJSON(data);
464 if (typeof(obj) != 'object')
467 /* is a batched response */
471 for (var i = 0; i < obj.length; i++)
473 var p = (typeof(priv) != 'undefined') ? priv[i] : undefined;
475 if ($.isArray(obj[i].result) && typeof(priv) != 'undefined')
476 obj[i].result[2] = p;
478 if (obj[i].jsonrpc != '2.0' || obj[i].error || !obj[i].result)
479 rv[keys[i]] = [ 4 /* UBUS_STATUS_NO_DATA */, undefined, p ];
481 rv[keys[i]] = obj[i].result;
486 if (obj.jsonrpc != '2.0' || obj.error || !obj.result)
487 return [ 4 /* UBUS_STATUS_NO_DATA */, undefined, priv ];
489 if ($.isArray(obj.result) && typeof(priv) != 'undefined')
490 obj.result[2] = priv;
496 _post_msg: function(message, cb, keys, priv)
498 return $.ajax('/ubus', {
500 contentType: 'application/json',
501 data: JSON.stringify(message),
502 dataFilter: _luci2.rpc._parse_response(keys, priv),
509 _post_single: function(object, method, args, cb, priv)
511 var msg = _luci2.rpc._wrap_msg('call', object, method, args, priv);
512 return _luci2.rpc._post_msg(msg, cb, undefined, priv);
515 _post_batch: function(methods, cb)
517 if (typeof(methods) != 'object')
524 for (var k in methods)
526 if (typeof(methods[k]) != 'object' || methods[k].length < 2)
530 priv.push(methods[k][3]);
531 msgs.push(_luci2.rpc._wrap_msg('call', methods[k][0], methods[k][1], methods[k][2]));
535 return _luci2.rpc._post_msg(msgs, cb, keys, priv);
537 return _luci2.deferrable([ ]);
543 if (typeof a[0] == 'string')
544 return _luci2.rpc._post_single(a[0], a[1], a[2], a[3], a[4]);
546 return _luci2.rpc._post_batch(a[0], a[1]);
549 list: function(objects)
551 var msg = _luci2.rpc._wrap_msg('list', objects);
552 return _luci2.rpc._post_msg(msg);
555 access: function(scope, object, method, cb)
557 return _luci2.rpc._post_single('session', 'access', {
558 'sid': _luci2.globals.sid,
563 return retcb(cb, (rv[0] == 0 && rv[1] && rv[1].access == true));
570 writable: function(cb)
572 return _luci2.rpc.access('ubus', 'uci', 'commit', cb);
575 add: function(config, type, cb)
577 return rcall('uci', 'add', { config: config, type: type }, 'section', '', cb);
585 changes: function(config)
587 return rcall('uci', 'changes', { config: config }, 'changes', [ ], cb);
590 commit: function(config)
592 return rcall('uci', 'commit', { config: config }, undefined, undefined, cb);
595 'delete': function(config, section, option)
597 var req = { config: config, section: section };
599 if (isa(option, 'Array'))
600 req.options = option;
604 return rcall('uci', 'delete', req, undefined, undefined, cb);
607 delete_all: function(config, type, matches)
609 return rcall('uci', 'delete', { config: config, type: type, match: matches }, undefined, undefined, cb);
612 foreach: function(config, type, cb)
614 return rcall('uci', 'get', { config: config, type: type }, 'values', { }, function(sections) {
615 for (var s in sections)
620 get: function(config, section, option, cb)
622 return rcall('uci', 'get', { config: config, section: section, option: option }, undefined, { }, function(res) {
623 if (typeof(option) == 'undefined')
624 return retcb(cb, (res.values && res.values['.type']) ? res.values['.type'] : undefined);
626 return retcb(cb, res.value);
630 get_all: function(config, section, cb)
632 return rcall('uci', 'get', { config: config, section: section }, 'values', { }, cb);
635 get_first: function(config, type, option, cb)
637 return rcall('uci', 'get', { config: config, type: type }, 'values', { }, function(sections) {
638 for (var s in sections)
640 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
642 if (typeof(val) != 'undefined')
643 return retcb(cb, val);
646 return retcb(cb, undefined);
650 section: function(config, type, name, values, cb)
652 return rcall('uci', 'add', { config: config, type: type, name: name, values: values }, 'section', undefined, cb);
655 set: function(config, section, option, value, cb)
657 if (typeof(value) == 'undefined' && typeof(option) == 'string')
658 return rcall('uci', 'add', { config: config, section: section, type: option }, undefined, undefined, cb);
659 else if (isa(option, 'Object'))
660 return rcall('uci', 'set', { config: config, section: section, values: option }, undefined, undefined, cb);
664 values[option] = value;
666 return rcall('uci', 'set', { config: config, section: section, values: values }, undefined, undefined, cb);
669 order: function(config, sections, cb)
671 return rcall('uci', 'order', { config: config, sections: sections }, undefined, undefined, cb);
676 getNetworkStatus: function(cb)
679 var assign = function(target, key)
681 return function(value) {
682 if (typeof(value) != 'undefined' && !$.isEmptyObject(value))
687 return _luci2.rpc.list().then(function(data) {
690 for (var i = 0; i < data.length; i++)
692 if (data[i].indexOf('network.interface.') != 0)
695 var ifname = data[i].substring(18);
696 if (ifname == 'loopback')
699 var iface = { 'name': ifname };
702 requests.push(['network.interface', 'status', { 'interface': ifname }, iface]);
705 return _luci2.rpc.call(requests, function(responses) {
706 for (var key in responses)
707 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
708 $.extend(responses[key][2], responses[key][1]);
713 for (var i = 0; i < ifaces.length; i++)
715 var iface = ifaces[i];
717 var dev = iface.l3_device || iface.l2_device;
721 iface.device = { 'name': dev };
722 requests[dev] = ['network.device', 'status', { 'name': dev }, iface.device];
725 return _luci2.rpc.call(requests, function(responses) {
726 for (var key in responses)
727 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
728 $.extend(responses[key][2], responses[key][1]);
733 for (var i = 0; i < ifaces.length; i++)
735 var iface = ifaces[i];
739 var subdevs = iface.device['bridge-members'];
743 iface.subdevices = [ ];
744 for (var j = 0; j < subdevs.length; j++)
746 iface.subdevices[j] = { 'name': subdevs[j] };
747 requests.push(['network.device', 'status', { 'name': subdevs[j] }, iface.subdevices[j]]);
751 return _luci2.rpc.call(requests, function(responses) {
752 for (var key in responses)
753 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
754 $.extend(responses[key][2], responses[key][1]);
759 for (var i = 0; i < ifaces.length; i++)
761 var iface = ifaces[i];
764 requests.push(['iwinfo', 'info', { 'device': iface.device.name }, iface.device]);
766 if (iface.subdevices)
767 for (var j = 0; j < iface.subdevices.length; j++)
768 requests.push(['iwinfo', 'info', { 'device': iface.subdevices[j].name }, iface.subdevices[j]]);
771 return _luci2.rpc.call(requests, function(responses) {
772 for (var key in responses)
773 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
774 if (!$.isEmptyObject(responses[key][1]))
775 responses[key][2].wireless = responses[key][1];
778 ifaces.sort(function(a, b) {
779 if (a['interface'] < b['interface'])
781 else if (a['interface'] > b['interface'])
786 return retcb(cb, ifaces);
790 findWanInterfaces: function(cb)
792 return _luci2.rpc.list().then(function(data) {
794 for (var i = 0; i < data.length; i++)
796 if (data[i].indexOf('network.interface.') == 0)
798 var ifname = data[i].substring(18);
799 requests[ifname] = ['network.interface', 'status', { 'interface': ifname }];
802 return _luci2.rpc.call(requests);
803 }).then(function(responses) {
805 for (var ifname in responses)
807 var response = responses[ifname];
809 if (response[0] != 0 || !response[1] || !response[1].route)
812 for (var rn = 0, rt = response[1].route[rn];
813 rn < response[1].route.length;
814 rn++, rt = response[1].route[rn])
816 if (typeof(rt.table) != 'undefined')
819 if (rt.target == '0.0.0.0' && rt.mask == 0)
821 else if (rt.target == '::' && rt.mask == 0)
826 return retcb(cb, rv);
830 getDHCPLeases: function(cb)
832 return rcall('luci2.network', 'dhcp_leases', undefined, 'leases', [ ], cb);
835 getDHCPv6Leases: function(cb)
837 return rcall('luci2.network', 'dhcp6_leases', undefined, 'leases', [ ], cb);
840 getRoutes: function(cb)
842 return rcall('luci2.network', 'routes', undefined, 'routes', [ ], cb);
845 getIPv6Routes: function(cb)
847 return rcall('luci2.network', 'routes6', undefined, 'routes', [ ], cb);
850 getARPTable: function(cb)
852 return rcall('luci2.network', 'arp_table', undefined, 'entries', [ ], cb);
855 getInterfaceStatus: function(iface, cb)
857 return rcall('network.interface', 'status', { 'interface': iface }, undefined, { }, cb, function(rv) {
858 rv['interface'] = iface;
859 rv['l2_device'] = rv['device'];
864 getDeviceStatus: function(dev, cb)
866 return rcall('network.device', 'status', { name: dev }, undefined, { }, cb, function(rv) {
867 if (typeof(dev) == 'string')
873 getConntrackCount: function(cb)
875 return rcall('luci2.network', 'conntrack_count', undefined, undefined, {
883 getDevices: function(cb) {
884 return rcall('iwinfo', 'devices', undefined, 'devices', [ ], cb, function(rv) {
890 getInfo: function(dev, cb) {
891 var parse_info = function(device, info, rv)
898 var phy = rv[info.phy];
901 'country', 'channel', 'frequency', 'frequency_offset',
902 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
906 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
907 'signal', 'noise', 'bitrate', 'encryption'
910 for (var i = 0; i < phy_attrs.length; i++)
911 phy[phy_attrs[i]] = info[phy_attrs[i]];
917 for (var i = 0; i < net_attrs.length; i++)
918 net[net_attrs[i]] = info[net_attrs[i]];
920 phy.networks.push(net);
927 return _luci2.wireless.getDevices().then(function(devices) {
930 for (var i = 0; i < devices.length; i++)
932 if (devices[i].indexOf('.sta') >= 0)
935 requests[devices[i]] = [ 'iwinfo', 'info', { device: devices[i] } ];
938 return _luci2.rpc.call(requests);
939 }).then(function(responses) {
942 for (var device in responses)
944 var response = responses[device];
946 if (response[0] != 0 || !response[1])
949 parse_info(device, response[1], rv);
952 return retcb(cb, rv);
956 return _luci2.rpc.call('iwinfo', 'info', { device: dev }).then(function(response) {
957 if (response[0] != 0 || !response[1])
958 return retcb(cb, { });
960 return retcb(cb, parse_info(dev, response[1], { }));
964 getAssocList: function(dev, cb)
968 return _luci2.wireless.getDevices().then(function(devices) {
971 for (var i = 0; i < devices.length; i++)
973 if (devices[i].indexOf('.sta') >= 0)
976 requests[devices[i]] = [ 'iwinfo', 'assoclist', { device: devices[i] } ];
979 return _luci2.rpc.call(requests);
980 }).then(function(responses) {
983 for (var device in responses)
985 var response = responses[device];
987 if (response[0] != 0 || !response[1] || !response[1].results)
990 for (var i = 0; i < response[1].results.length; i++)
992 var station = response[1].results[i];
994 station.device = device;
999 rv.sort(function(a, b) {
1000 return (a.device == b.device)
1001 ? (a.bssid < b.bssid)
1002 : (a.device > b.device)
1006 return retcb(cb, rv);
1010 return _luci2.rpc.call('iwinfo', 'assoclist', { device: dev }).then(function(response) {
1013 if (response[0] != 0 || !response[1] || !response[1].results)
1014 return retcb(cb, rv);
1016 for (var i = 0; i < response[1].results.length; i++)
1018 var station = response[1].results[i];
1020 station.device = dev;
1024 rv.sort(function(a, b) {
1025 return (a.bssid < b.bssid);
1028 return retcb(cb, rv);
1032 formatEncryption: function(enc)
1034 var format_list = function(l, s)
1037 for (var i = 0; i < l.length; i++)
1038 rv.push(l[i].toUpperCase());
1039 return rv.join(s ? s : ', ');
1042 if (!enc || !enc.enabled)
1043 return _luci2.tr('None');
1047 if (enc.wep.length == 2)
1048 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1049 else if (enc.wep[0] == 'shared')
1050 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1052 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1056 if (enc.wpa.length == 2)
1057 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1058 format_list(enc.authentication, '/'),
1059 format_list(enc.ciphers, ', ')
1061 else if (enc.wpa[0] == 2)
1062 return 'WPA2 %s (%s)'.format(
1063 format_list(enc.authentication, '/'),
1064 format_list(enc.ciphers, ', ')
1067 return 'WPA %s (%s)'.format(
1068 format_list(enc.authentication, '/'),
1069 format_list(enc.ciphers, ', ')
1073 return _luci2.tr('Unknown');
1078 getInfo: function(cb)
1080 return _luci2.rpc.call({
1081 info: [ 'system', 'info', { } ],
1082 board: [ 'system', 'board', { } ],
1083 disk: [ 'luci2.system', 'diskfree', { } ]
1084 }).then(function(responses) {
1087 if (responses.info[0] == 0)
1088 $.extend(rv, responses.info[1]);
1090 if (responses.board[0] == 0)
1091 $.extend(rv, responses.board[1]);
1093 if (responses.disk[0] == 0)
1094 $.extend(rv, responses.disk[1]);
1096 return retcb(cb, rv);
1100 getProcessList: function(cb)
1102 return rcall('luci2.system', 'process_list', undefined, 'processes', [ ], cb, function(rv) {
1103 rv.sort(function(a, b) { return a.pid - b.pid });
1108 getSystemLog: function(cb)
1110 return rcall('luci2.system', 'syslog', undefined, 'log', '', cb);
1113 getKernelLog: function(cb)
1115 return rcall('luci2.system', 'dmesg', undefined, 'log', '', cb);
1118 getZoneInfo: function(cb)
1120 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1123 canSendSignal: function(cb)
1125 return _luci2.rpc.access('ubus', 'luci2.system', 'process_signal', cb);
1128 sendSignal: function(pid, sig, cb)
1130 return _luci2.rpc.call('luci2.system', 'process_signal', { pid: pid, signal: sig }).then(function(response) {
1131 return retcb(cb, response[0] == 0);
1135 initList: function(cb)
1137 return rcall('luci2.system', 'init_list', undefined, 'initscripts', [ ], cb, function(rv) {
1138 rv.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1143 initEnabled: function(init, cb)
1145 return this.initList(function(list) {
1146 for (var i = 0; i < list.length; i++)
1147 if (list[i].name == init)
1148 return retcb(cb, !!list[i].enabled);
1150 return retcb(cb, false);
1154 initRun: function(init, action, cb)
1156 return _luci2.rpc.call('luci2.system', 'init_action', { name: init, action: action }).then(function(response) {
1157 return retcb(cb, response[0] == 0);
1161 canInitRun: function(cb)
1163 return _luci2.rpc.access('ubus', 'luci2.system', 'init_action', cb);
1166 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1167 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1168 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1169 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1170 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1171 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1174 getRcLocal: function(cb)
1176 return rcall('luci2.system', 'rclocal_get', undefined, 'data', '', cb);
1179 setRcLocal: function(data, cb)
1181 return rcall('luci2.system', 'rclocal_set', { data: data }, undefined, undefined, cb);
1184 canSetRcLocal: function(cb)
1186 return _luci2.rpc.access('ubus', 'luci2.system', 'rclocal_set', cb);
1190 getCrontab: function(cb)
1192 return rcall('luci2.system', 'crontab_get', undefined, 'data', '', cb);
1195 setCrontab: function(data, cb)
1197 return rcall('luci2.system', 'crontab_set', { data: data }, undefined, undefined, cb);
1200 canSetCrontab: function(cb)
1202 return _luci2.rpc.access('ubus', 'luci2.system', 'crontab_set', cb);
1206 getSSHKeys: function(cb)
1208 return rcall('luci2.system', 'sshkeys_get', undefined, 'keys', [ ], cb);
1211 setSSHKeys: function(keys, cb)
1213 return rcall('luci2.system', 'sshkeys_set', { keys: keys }, undefined, undefined, cb);
1216 canSetSSHKeys: function(cb)
1218 return _luci2.rpc.access('ubus', 'luci2.system', 'sshkeys_set', cb);
1222 setPassword: function(user, pass, cb)
1224 return rcall('luci2.system', 'password_set', { user: user, password: pass }, undefined, undefined, cb);
1227 canSetPassword: function(cb)
1229 return _luci2.rpc.access('ubus', 'luci2.system', 'password_set', cb);
1233 listLEDs: function(cb)
1235 return rcall('luci2.system', 'led_list', undefined, 'leds', [ ], cb);
1238 listUSBDevices: function(cb)
1240 return rcall('luci2.system', 'usb_list', undefined, 'devices', [ ], cb);
1244 testUpgrade: function(cb)
1246 return rcall('luci2.system', 'upgrade_test', undefined, undefined, { }, cb);
1249 startUpgrade: function(keep, cb)
1251 return rcall('luci2.system', 'upgrade_start', { keep: !!keep }, undefined, undefined, cb);
1254 cleanUpgrade: function(cb)
1256 return rcall('luci2.system', 'upgrade_clean', undefined, undefined, undefined, cb);
1259 canUpgrade: function(cb)
1261 return _luci2.rpc.access('ubus', 'luci2.system', 'upgrade_start', cb);
1265 restoreBackup: function(cb)
1267 return rcall('luci2.system', 'backup_restore', undefined, undefined, undefined, cb);
1270 cleanBackup: function(cb)
1272 return rcall('luci2.system', 'backup_clean', undefined, undefined, undefined, cb);
1275 canRestoreBackup: function(cb)
1277 return _luci2.rpc.access('ubus', 'luci2.system', 'backup_restore', cb);
1281 getBackupConfig: function(cb)
1283 return rcall('luci2.system', 'backup_config_get', undefined, 'config', '', cb);
1286 setBackupConfig: function(data, cb)
1288 return rcall('luci2.system', 'backup_config_set', { data: data }, undefined, undefined, cb);
1291 canSetBackupConfig: function(cb)
1293 return _luci2.rpc.access('ubus', 'luci2.system', 'backup_config_set', cb);
1297 listBackup: function(cb)
1299 return rcall('luci2.system', 'backup_list', undefined, 'files', [ ], cb);
1303 performReboot: function(cb)
1305 return rcall('luci2.system', 'reboot', undefined, undefined, undefined, cb);
1308 canPerformReboot: function(cb)
1310 return _luci2.rpc.access('ubus', 'luci2.system', 'reboot', cb);
1315 updateLists: function(cb)
1317 return rcall('luci2.opkg', 'update', undefined, undefined, { }, cb);
1320 _fetchPackages: function(action, offset, limit, pattern, cb)
1323 var reqlimit = Math.min(limit, 100);
1328 return _luci2.rpc.call('luci2.opkg', action, { offset: offset, limit: reqlimit, pattern: pattern }).then(function(response) {
1329 if (response[0] != 0 || !response[1] || !response[1].total)
1330 return retcb(cb, { length: 0, total: 0 });
1332 packages.push.apply(packages, response[1].packages);
1333 packages.total = response[1].total;
1336 limit = response[1].total;
1338 if (packages.length >= limit)
1339 return retcb(cb, packages);
1342 for (var i = offset + packages.length; i < limit; i += 100)
1343 requests.push(['luci2.opkg', action, { offset: i, limit: (Math.min(i + 100, limit) % 100) || 100, pattern: pattern }]);
1345 return _luci2.rpc.call(requests);
1346 }).then(function(responses) {
1347 for (var key in responses)
1349 var response = responses[key];
1351 if (response[0] != 0 || !response[1] || !response[1].packages)
1354 packages.push.apply(packages, response[1].packages);
1355 packages.total = response[1].total;
1358 return retcb(cb, packages);
1362 listPackages: function(offset, limit, pattern, cb)
1364 return _luci2.opkg._fetchPackages('list', offset, limit, pattern, cb);
1367 installedPackages: function(offset, limit, pattern, cb)
1369 return _luci2.opkg._fetchPackages('list_installed', offset, limit, pattern, cb);
1372 findPackages: function(offset, limit, pattern, cb)
1374 return _luci2.opkg._fetchPackages('find', offset, limit, pattern, cb);
1377 installPackage: function(name, cb)
1379 return rcall('luci2.opkg', 'install', { 'package': name }, undefined, { }, cb);
1382 removePackage: function(name, cb)
1384 return rcall('luci2.opkg', 'remove', { 'package': name }, undefined, { }, cb);
1387 getConfig: function(cb)
1389 return rcall('luci2.opkg', 'config_get', undefined, 'config', '', cb);
1392 setConfig: function(data, cb)
1394 return rcall('luci2.opkg', 'config_set', { data: data }, undefined, undefined, cb);
1397 canInstallPackage: function(cb)
1399 return _luci2.rpc.access('ubus', 'luci2.opkg', 'install', cb);
1402 canRemovePackage: function(cb)
1404 return _luci2.rpc.access('ubus', 'luci2.opkg', 'remove', cb);
1407 canSetConfig: function(cb)
1409 return _luci2.rpc.access('ubus', 'luci2.opkg', 'config_set', cb);
1415 loading: function(enable)
1417 var win = $(window);
1418 var body = $('body');
1419 var div = _luci2._modal || (
1420 _luci2._modal = $('<div />')
1421 .addClass('cbi-modal-loader')
1422 .append($('<div />').text(_luci2.tr('Loading data...')))
1428 body.css('overflow', 'hidden');
1429 body.css('padding', 0);
1430 body.css('width', win.width());
1431 body.css('height', win.height());
1432 div.css('width', win.width());
1433 div.css('height', win.height());
1439 body.css('overflow', '');
1440 body.css('padding', '');
1441 body.css('width', '');
1442 body.css('height', '');
1446 dialog: function(title, content, options)
1448 var win = $(window);
1449 var body = $('body');
1450 var div = _luci2._dialog || (
1451 _luci2._dialog = $('<div />')
1452 .addClass('cbi-modal-dialog')
1453 .append($('<div />')
1454 .append($('<div />')
1455 .addClass('cbi-modal-dialog-header'))
1456 .append($('<div />')
1457 .addClass('cbi-modal-dialog-body'))
1458 .append($('<div />')
1459 .addClass('cbi-modal-dialog-footer')
1460 .append($('<button />')
1461 .addClass('cbi-button')
1462 .text(_luci2.tr('Close'))
1465 .css('overflow', '')
1470 $(this).parent().parent().parent().hide();
1475 if (typeof(options) != 'object')
1478 if (title === false)
1481 .css('overflow', '')
1486 _luci2._dialog.hide();
1491 var cnt = div.children().children('div.cbi-modal-dialog-body');
1492 var ftr = div.children().children('div.cbi-modal-dialog-footer');
1496 if (options.style == 'confirm')
1498 ftr.append($('<button />')
1499 .addClass('cbi-button')
1500 .text(_luci2.tr('Ok'))
1501 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1503 ftr.append($('<button />')
1504 .addClass('cbi-button')
1505 .text(_luci2.tr('Cancel'))
1506 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1508 else if (options.style == 'close')
1510 ftr.append($('<button />')
1511 .addClass('cbi-button')
1512 .text(_luci2.tr('Close'))
1513 .click(options.close || function() { _luci2.ui.dialog(false) }));
1515 else if (options.style == 'wait')
1517 ftr.append($('<button />')
1518 .addClass('cbi-button')
1519 .text(_luci2.tr('Close'))
1520 .attr('disabled', true));
1523 div.find('div.cbi-modal-dialog-header').text(title);
1527 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1532 .css('margin-top', -Math.floor(div.children().height() / 2) + 'px');
1534 body.css('overflow', 'hidden');
1535 body.css('padding', 0);
1536 body.css('width', win.width());
1537 body.css('height', win.height());
1538 div.css('width', win.width());
1539 div.css('height', win.height());
1542 upload: function(title, content, options)
1544 var form = _luci2._upload || (
1545 _luci2._upload = $('<form />')
1546 .attr('method', 'post')
1547 .attr('action', '/cgi-bin/luci-upload')
1548 .attr('enctype', 'multipart/form-data')
1549 .attr('target', 'cbi-fileupload-frame')
1551 .append($('<input />')
1552 .attr('type', 'hidden')
1553 .attr('name', 'sessionid')
1554 .attr('value', _luci2.globals.sid))
1555 .append($('<input />')
1556 .attr('type', 'hidden')
1557 .attr('name', 'filename')
1558 .attr('value', options.filename))
1559 .append($('<input />')
1560 .attr('type', 'file')
1561 .attr('name', 'filedata')
1562 .addClass('cbi-input-file'))
1563 .append($('<div />')
1564 .css('width', '100%')
1565 .addClass('progressbar')
1566 .addClass('intermediate')
1567 .append($('<div />')
1568 .css('width', '100%')))
1569 .append($('<iframe />')
1570 .attr('name', 'cbi-fileupload-frame')
1571 .css('width', '1px')
1572 .css('height', '1px')
1573 .css('visibility', 'hidden'))
1576 var finish = _luci2._upload_finish_cb || (
1577 _luci2._upload_finish_cb = function(ev) {
1578 $(this).off('load');
1580 var body = (this.contentDocument || this.contentWindow.document).body;
1581 if (body.firstChild.tagName.toLowerCase() == 'pre')
1582 body = body.firstChild;
1586 json = $.parseJSON(body.innerHTML);
1589 message: _luci2.tr('Invalid server response received'),
1590 error: [ -1, _luci2.tr('Invalid data') ]
1596 L.ui.dialog(L.tr('File upload'), [
1597 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1598 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1599 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1600 ], { style: 'close' });
1602 else if (typeof(ev.data.cb) == 'function')
1609 var confirm = _luci2._upload_confirm_cb || (
1610 _luci2._upload_confirm_cb = function() {
1611 var d = _luci2._upload;
1612 var f = d.find('.cbi-input-file');
1613 var b = d.find('.progressbar');
1614 var p = d.find('p');
1619 d.find('iframe').on('load', { cb: options.success }, finish);
1624 p.text(_luci2.tr('File upload in progress …'));
1626 _luci2._dialog.find('button').prop('disabled', true);
1630 _luci2._upload.find('.progressbar').hide();
1631 _luci2._upload.find('.cbi-input-file').val('').show();
1632 _luci2._upload.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1634 _luci2.ui.dialog(title || _luci2.tr('File upload'), _luci2._upload, {
1640 reconnect: function()
1642 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1643 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1644 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1646 var interval, timeout;
1649 _luci2.tr('Waiting for device'), [
1650 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1652 .css('width', '100%')
1653 .addClass('progressbar')
1654 .addClass('intermediate')
1655 .append($('<div />')
1656 .css('width', '100%'))
1657 ], { style: 'wait' }
1660 for (var i = 0; i < protocols.length; i++)
1661 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1663 //_luci2.network.getNetworkStatus(function(s) {
1664 // for (var i = 0; i < protocols.length; i++)
1666 // for (var j = 0; j < s.length; j++)
1668 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1669 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1671 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1672 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1675 //}).then(function() {
1676 images.on('load', function() {
1677 var url = this.getAttribute('url');
1678 _luci2.rpc.access('ubus', 'session', 'access').then(function(response) {
1679 if (response[0] == 0)
1681 window.clearTimeout(timeout);
1682 window.clearInterval(interval);
1683 _luci2.ui.dialog(false);
1688 location.href = url;
1693 interval = window.setInterval(function() {
1694 images.each(function() {
1695 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1699 timeout = window.setTimeout(function() {
1700 window.clearInterval(interval);
1704 _luci2.tr('Device not responding'),
1705 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1712 login: function(invalid)
1714 if (!_luci2._login_deferred || _luci2._login_deferred.state() != 'pending')
1715 _luci2._login_deferred = $.Deferred();
1717 /* try to find sid from hash */
1718 var sid = _luci2.getHash('id');
1719 if (sid && sid.match(/^[a-f0-9]{32}$/))
1721 _luci2.globals.sid = sid;
1722 _luci2.rpc.access('ubus', 'session', 'access').then(function(response) {
1723 if (response[0] == 0)
1725 _luci2._login_deferred.resolve();
1729 _luci2.setHash('id', undefined);
1734 return _luci2._login_deferred;
1737 var form = _luci2._login || (
1738 _luci2._login = $('<div />')
1740 .addClass('alert-message')
1741 .text(_luci2.tr('Wrong username or password given!')))
1743 .append($('<label />')
1744 .text(_luci2.tr('Username'))
1745 .append($('<br />'))
1746 .append($('<input />')
1747 .attr('type', 'text')
1748 .attr('name', 'username')
1749 .attr('value', 'root')
1750 .addClass('cbi-input-text'))))
1752 .append($('<label />')
1753 .text(_luci2.tr('Password'))
1754 .append($('<br />'))
1755 .append($('<input />')
1756 .attr('type', 'password')
1757 .attr('name', 'password')
1758 .addClass('cbi-input-password'))))
1760 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok'))))
1763 var response = _luci2._login_response_cb || (
1764 _luci2._login_response_cb = function(data) {
1765 if (typeof(data) == 'object' && typeof(data.sessionid) == 'string')
1767 _luci2.globals.sid = data.sessionid;
1768 _luci2.setHash('id', _luci2.globals.sid);
1770 _luci2.ui.dialog(false);
1771 _luci2._login_deferred.resolve();
1775 _luci2.ui.login(true);
1780 var confirm = _luci2._login_confirm_cb || (
1781 _luci2._login_confirm_cb = function() {
1782 var d = _luci2._login;
1783 var u = d.find('[name=username]').val();
1784 var p = d.find('[name=password]').val();
1790 _luci2.tr('Logging in'), [
1791 $('<p />').text(_luci2.tr('Log in in progress …')),
1793 .css('width', '100%')
1794 .addClass('progressbar')
1795 .addClass('intermediate')
1796 .append($('<div />')
1797 .css('width', '100%'))
1798 ], { style: 'wait' }
1801 $.ajax('/cgi-bin/luci-login', {
1804 data: { username: u, password: p },
1813 form.find('.alert-message').show();
1815 form.find('.alert-message').hide();
1817 _luci2.ui.dialog(_luci2.tr('Authorization Required'), form, {
1822 return _luci2._login_deferred;
1825 renderMainMenu: function()
1827 return rcall('luci2.ui', 'menu', undefined, 'menu', { }, function(entries) {
1828 _luci2.globals.mainMenu = new _luci2.ui.menu();
1829 _luci2.globals.mainMenu.entries(entries);
1833 .append(_luci2.globals.mainMenu.render(0, 1));
1837 renderViewMenu: function()
1841 .append(_luci2.globals.mainMenu.render(2, 900));
1844 renderView: function(node)
1846 var name = node.view.split(/\//).join('.');
1848 _luci2.ui.renderViewMenu();
1851 _luci2._views = { };
1853 _luci2.setHash('view', node.view);
1855 if (_luci2._views[name] instanceof _luci2.ui.view)
1856 return _luci2._views[name].render();
1858 return $.ajax(_luci2.globals.resource + '/view/' + name + '.js', {
1862 }).then(function(data) {
1864 var viewConstructor = (new Function(['L', '$'], 'return ' + data))(_luci2, $);
1866 _luci2._views[name] = new viewConstructor({
1868 acls: node.write || { }
1871 return _luci2._views[name].render();
1875 return $.Deferred().resolve();
1881 _luci2.ui.loading(true);
1884 _luci2.ui.renderMainMenu()
1886 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
1887 _luci2.ui.loading(false);
1893 var AbstractWidget = Class.extend({
1894 i18n: function(text) {
1898 toString: function() {
1899 var x = document.createElement('div');
1900 x.appendChild(this.render());
1905 insertInto: function(id) {
1906 return $(id).empty().append(this.render());
1910 this.ui.view = AbstractWidget.extend({
1911 _fetch_template: function()
1913 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
1917 success: function(data) {
1918 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
1919 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
1926 return _luci2.tr(p2);
1929 return _luci2.globals[p2] || '';
1932 return '(?' + match + ')';
1936 $('#maincontent').append(data);
1943 throw "Not implemented";
1948 var container = $('#maincontent');
1953 container.append($('<h2 />').append(this.title));
1955 if (this.description)
1956 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
1959 return this._fetch_template().then(function() {
1960 return _luci2.deferrable(self.execute());
1965 this.ui.menu = AbstractWidget.extend({
1970 entries: function(entries)
1972 for (var entry in entries)
1974 var path = entry.split(/\//);
1975 var node = this._nodes;
1977 for (i = 0; i < path.length; i++)
1982 if (!node.childs[path[i]])
1983 node.childs[path[i]] = { };
1985 node = node.childs[path[i]];
1988 $.extend(node, entries[entry]);
1992 _indexcmp: function(a, b)
1994 var x = a.index || 0;
1995 var y = b.index || 0;
1999 firstChildView: function(node)
2005 for (var child in (node.childs || { }))
2006 nodes.push(node.childs[child]);
2008 nodes.sort(this._indexcmp);
2010 for (var i = 0; i < nodes.length; i++)
2012 var child = this.firstChildView(nodes[i]);
2015 $.extend(node, child);
2023 _onclick: function(ev)
2025 _luci2.ui.loading(true);
2026 _luci2.ui.renderView(ev.data).then(function() {
2027 _luci2.ui.loading(false);
2030 ev.preventDefault();
2034 _render: function(childs, level, min, max)
2037 for (var node in childs)
2039 var child = this.firstChildView(childs[node]);
2041 nodes.push(childs[node]);
2044 nodes.sort(this._indexcmp);
2046 var list = $('<ul />');
2049 list.addClass('nav');
2050 else if (level == 1)
2051 list.addClass('dropdown-menu');
2053 for (var i = 0; i < nodes.length; i++)
2055 if (!_luci2.globals.defaultNode)
2057 var v = _luci2.getHash('view');
2058 if (!v || v == nodes[i].view)
2059 _luci2.globals.defaultNode = nodes[i];
2062 var item = $('<li />')
2065 .text(_luci2.tr(nodes[i].title))
2066 .click(nodes[i], this._onclick))
2069 if (nodes[i].childs && level < max)
2071 item.addClass('dropdown');
2072 item.find('a').addClass('menu');
2073 item.append(this._render(nodes[i].childs, level + 1));
2080 render: function(min, max)
2082 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2083 return this._render(top.childs, 0, min, max);
2086 getNode: function(path, max)
2088 var p = path.split(/\//);
2089 var n = this._nodes;
2091 if (typeof(max) == 'undefined')
2094 for (var i = 0; i < max; i++)
2096 if (!n.childs[p[i]])
2106 this.ui.table = AbstractWidget.extend({
2112 row: function(values)
2114 if (isa(values, 'Array'))
2116 this._rows.push(values);
2118 else if (isa(values, 'Object'))
2121 for (var i = 0; i < this.options.columns.length; i++)
2123 var col = this.options.columns[i];
2125 if (typeof col.key == 'string')
2126 v.push(values[col.key]);
2134 rows: function(rows)
2136 for (var i = 0; i < rows.length; i++)
2140 render: function(id)
2142 var fieldset = document.createElement('fieldset');
2143 fieldset.className = 'cbi-section';
2145 if (this.options.caption)
2147 var legend = document.createElement('legend');
2148 $(legend).append(this.options.caption);
2149 fieldset.appendChild(legend);
2152 var table = document.createElement('table');
2153 table.className = 'cbi-section-table';
2155 var has_caption = false;
2156 var has_description = false;
2158 for (var i = 0; i < this.options.columns.length; i++)
2159 if (this.options.columns[i].caption)
2164 else if (this.options.columns[i].description)
2166 has_description = true;
2172 var tr = table.insertRow(-1);
2173 tr.className = 'cbi-section-table-titles';
2175 for (var i = 0; i < this.options.columns.length; i++)
2177 var col = this.options.columns[i];
2178 var th = document.createElement('th');
2179 th.className = 'cbi-section-table-cell';
2184 th.style.width = col.width;
2187 th.style.textAlign = col.align;
2190 $(th).append(col.caption);
2194 if (has_description)
2196 var tr = table.insertRow(-1);
2197 tr.className = 'cbi-section-table-descr';
2199 for (var i = 0; i < this.options.columns.length; i++)
2201 var col = this.options.columns[i];
2202 var th = document.createElement('th');
2203 th.className = 'cbi-section-table-cell';
2208 th.style.width = col.width;
2211 th.style.textAlign = col.align;
2213 if (col.description)
2214 $(th).append(col.description);
2218 if (this._rows.length == 0)
2220 if (this.options.placeholder)
2222 var tr = table.insertRow(-1);
2223 var td = tr.insertCell(-1);
2224 td.className = 'cbi-section-table-cell';
2226 td.colSpan = this.options.columns.length;
2227 $(td).append(this.options.placeholder);
2232 for (var i = 0; i < this._rows.length; i++)
2234 var tr = table.insertRow(-1);
2236 for (var j = 0; j < this.options.columns.length; j++)
2238 var col = this.options.columns[j];
2239 var td = tr.insertCell(-1);
2241 var val = this._rows[i][j];
2243 if (typeof(val) == 'undefined')
2244 val = col.placeholder;
2246 if (typeof(val) == 'undefined')
2250 td.style.width = col.width;
2253 td.style.textAlign = col.align;
2255 if (typeof col.format == 'string')
2256 $(td).append(col.format.format(val));
2257 else if (typeof col.format == 'function')
2258 $(td).append(col.format(val, i));
2266 fieldset.appendChild(table);
2272 this.ui.progress = AbstractWidget.extend({
2275 var vn = parseInt(this.options.value) || 0;
2276 var mn = parseInt(this.options.max) || 100;
2277 var pc = Math.floor((100 / mn) * vn);
2279 var bar = document.createElement('div');
2280 bar.className = 'progressbar';
2282 bar.appendChild(document.createElement('div'));
2283 bar.lastChild.appendChild(document.createElement('div'));
2284 bar.lastChild.style.width = pc + '%';
2286 if (typeof(this.options.format) == 'string')
2287 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2288 else if (typeof(this.options.format) == 'function')
2289 $(bar.lastChild.lastChild).append(this.options.format(pc));
2291 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2297 this.ui.devicebadge = AbstractWidget.extend({
2300 var dev = this.options.l3_device || this.options.device || '?';
2302 var span = document.createElement('span');
2303 span.className = 'ifacebadge';
2305 if (typeof(this.options.signal) == 'number' ||
2306 typeof(this.options.noise) == 'number')
2309 if (typeof(this.options.signal) != 'undefined' &&
2310 typeof(this.options.noise) != 'undefined')
2312 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2325 span.appendChild(document.createElement('img'));
2326 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2329 span.title = _luci2.tr('No signal');
2331 span.title = '%s: %d %s / %s: %d %s'.format(
2332 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2333 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2338 var type = 'ethernet';
2339 var desc = _luci2.tr('Ethernet device');
2341 if (this.options.l3_device != this.options.device)
2344 desc = _luci2.tr('Tunnel interface');
2346 else if (dev.indexOf('br-') == 0)
2349 desc = _luci2.tr('Bridge');
2351 else if (dev.indexOf('.') > 0)
2354 desc = _luci2.tr('VLAN interface');
2356 else if (dev.indexOf('wlan') == 0 ||
2357 dev.indexOf('ath') == 0 ||
2358 dev.indexOf('wl') == 0)
2361 desc = _luci2.tr('Wireless Network');
2364 span.appendChild(document.createElement('img'));
2365 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2369 $(span).append(' ');
2370 $(span).append(dev);
2376 var type = function(f, l)
2386 _luci2.cbi.validation.message = _luci2.tr(msg);
2389 compile: function(code)
2394 var types = _luci2.cbi.validation.types;
2399 for (var i = 0; i < code.length; i++)
2407 switch (code.charCodeAt(i))
2419 var label = code.substring(pos, i);
2420 label = label.replace(/\\(.)/g, '$1');
2421 label = label.replace(/^[ \t]+/g, '');
2422 label = label.replace(/[ \t]+$/g, '');
2424 if (label && !isNaN(label))
2426 stack.push(parseFloat(label));
2428 else if (label.match(/^(['"]).*\1$/))
2430 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2432 else if (typeof types[label] == 'function')
2434 stack.push(types[label]);
2439 throw "Syntax error, unhandled token '"+label+"'";
2444 depth += (code.charCodeAt(i) == 40);
2450 if (typeof stack[stack.length-2] != 'function')
2451 throw "Syntax error, argument list follows non-function";
2453 stack[stack.length-1] =
2454 arguments.callee(code.substring(pos, i));
2467 var validation = this.cbi.validation;
2469 validation.types = {
2470 'integer': function()
2472 if (this.match(/^-?[0-9]+$/) != null)
2475 validation.i18n('Must be a valid integer');
2479 'uinteger': function()
2481 if (validation.types['integer'].apply(this) && (this >= 0))
2484 validation.i18n('Must be a positive integer');
2490 if (!isNaN(parseFloat(this)))
2493 validation.i18n('Must be a valid number');
2497 'ufloat': function()
2499 if (validation.types['float'].apply(this) && (this >= 0))
2502 validation.i18n('Must be a positive number');
2506 'ipaddr': function()
2508 if (validation.types['ip4addr'].apply(this) ||
2509 validation.types['ip6addr'].apply(this))
2512 validation.i18n('Must be a valid IP address');
2516 'ip4addr': function()
2518 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2520 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2521 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2522 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2523 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2524 ((RegExp.$6.indexOf('.') < 0)
2525 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2526 : (validation.types['ip4addr'].apply(RegExp.$6))))
2530 validation.i18n('Must be a valid IPv4 address');
2534 'ip6addr': function()
2536 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2538 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2540 var addr = RegExp.$1;
2547 if (addr.indexOf('.') > 0)
2549 var off = addr.lastIndexOf(':');
2551 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2553 validation.i18n('Must be a valid IPv6 address');
2557 addr = addr.substr(0, off) + ':0:0';
2560 if (addr.indexOf('::') >= 0)
2565 for (var i = 1; i < (addr.length-1); i++)
2566 if (addr.charAt(i) == ':')
2571 validation.i18n('Must be a valid IPv6 address');
2575 for (var i = 0; i < (7 - colons); i++)
2578 if (addr.match(/^(.*?)::(.*?)$/))
2579 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2580 (RegExp.$2 ? ':' + RegExp.$2 : '');
2583 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2586 validation.i18n('Must be a valid IPv6 address');
2596 if (validation.types['integer'].apply(this) &&
2597 (this >= 0) && (this <= 65535))
2600 validation.i18n('Must be a valid port number');
2604 'portrange': function()
2606 if (this.match(/^(\d+)-(\d+)$/))
2611 if (validation.types['port'].apply(p1) &&
2612 validation.types['port'].apply(p2) &&
2613 (parseInt(p1) <= parseInt(p2)))
2616 else if (validation.types['port'].apply(this))
2621 validation.i18n('Must be a valid port range');
2625 'macaddr': function()
2627 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2630 validation.i18n('Must be a valid MAC address');
2636 if (validation.types['hostname'].apply(this) ||
2637 validation.types['ipaddr'].apply(this))
2640 validation.i18n('Must be a valid hostname or IP address');
2644 'hostname': function()
2646 if ((this.length <= 253) &&
2647 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2648 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2649 this.match(/[^0-9.]/)))))
2652 validation.i18n('Must be a valid host name');
2656 'network': function()
2658 if (validation.types['uciname'].apply(this) ||
2659 validation.types['host'].apply(this))
2662 validation.i18n('Must be a valid network name');
2666 'wpakey': function()
2670 if ((v.length == 64)
2671 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
2672 : ((v.length >= 8) && (v.length <= 63)))
2675 validation.i18n('Must be a valid WPA key');
2679 'wepkey': function()
2683 if (v.substr(0,2) == 's:')
2686 if (((v.length == 10) || (v.length == 26))
2687 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
2688 : ((v.length == 5) || (v.length == 13)))
2691 validation.i18n('Must be a valid WEP key');
2695 'uciname': function()
2697 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2700 validation.i18n('Must be a valid UCI identifier');
2704 'range': function(min, max)
2706 var val = parseFloat(this);
2708 if (validation.types['integer'].apply(this) &&
2709 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
2712 validation.i18n('Must be a number between %d and %d');
2716 'min': function(min)
2718 var val = parseFloat(this);
2720 if (validation.types['integer'].apply(this) &&
2721 !isNaN(min) && !isNaN(val) && (val >= min))
2724 validation.i18n('Must be a number greater or equal to %d');
2728 'max': function(max)
2730 var val = parseFloat(this);
2732 if (validation.types['integer'].apply(this) &&
2733 !isNaN(max) && !isNaN(val) && (val <= max))
2736 validation.i18n('Must be a number lower or equal to %d');
2740 'rangelength': function(min, max)
2742 var val = '' + this;
2744 if (!isNaN(min) && !isNaN(max) &&
2745 (val.length >= min) && (val.length <= max))
2748 validation.i18n('Must be between %d and %d characters');
2752 'minlength': function(min)
2754 var val = '' + this;
2756 if (!isNaN(min) && (val.length >= min))
2759 validation.i18n('Must be at least %d characters');
2763 'maxlength': function(max)
2765 var val = '' + this;
2767 if (!isNaN(max) && (val.length <= max))
2770 validation.i18n('Must be at most %d characters');
2778 for (var i = 0; i < arguments.length; i += 2)
2780 delete validation.message;
2782 if (typeof(arguments[i]) != 'function')
2784 if (arguments[i] == this)
2788 else if (arguments[i].apply(this, arguments[i+1]))
2793 if (validation.message)
2794 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2797 validation.message = msgs.join( _luci2.tr(' - or - '));
2805 for (var i = 0; i < arguments.length; i += 2)
2807 delete validation.message;
2809 if (typeof arguments[i] != 'function')
2811 if (arguments[i] != this)
2815 else if (!arguments[i].apply(this, arguments[i+1]))
2820 if (validation.message)
2821 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2824 validation.message = msgs.join(', ');
2830 return validation.types['or'].apply(
2831 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
2834 'list': function(subvalidator, subargs)
2836 if (typeof subvalidator != 'function')
2839 var tokens = this.match(/[^ \t]+/g);
2840 for (var i = 0; i < tokens.length; i++)
2841 if (!subvalidator.apply(tokens[i], subargs))
2847 'phonedigit': function()
2849 if (this.match(/^[0-9\*#!\.]+$/) != null)
2852 validation.i18n('Must be a valid phone number digit');
2856 'string': function()
2863 var AbstractValue = AbstractWidget.extend({
2864 init: function(name, options)
2867 this.instance = { };
2868 this.dependencies = [ ];
2869 this.rdependency = { };
2871 this.options = _luci2.defaults(options, {
2881 return this.section.id('field', sid || '__unknown__', this.name);
2884 render: function(sid)
2886 var i = this.instance[sid] = { };
2888 i.top = $('<div />').addClass('cbi-value');
2890 if (typeof(this.options.caption) == 'string')
2892 .addClass('cbi-value-title')
2893 .attr('for', this.id(sid))
2894 .text(this.options.caption)
2897 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
2898 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
2900 if (typeof(this.options.description) == 'string')
2902 .addClass('cbi-value-description')
2903 .text(this.options.description)
2909 ucipath: function(sid)
2912 config: (this.options.uci_package || this.map.uci_package),
2913 section: (this.options.uci_section || sid),
2914 option: (this.options.uci_option || this.name)
2918 ucivalue: function(sid)
2920 var uci = this.ucipath(sid);
2921 var val = this.map.get(uci.config, uci.section, uci.option);
2923 if (typeof(val) == 'undefined')
2924 return this.options.initial;
2929 formvalue: function(sid)
2931 var v = $('#' + this.id(sid)).val();
2932 return (v === '') ? undefined : v;
2935 textvalue: function(sid)
2937 var v = this.formvalue(sid);
2939 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
2940 v = this.ucivalue(sid);
2942 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))