2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String.prototype.format = function()
15 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27 var a = b = [], numSubstitutions = 0, numMatches = 0;
29 while ((a = re.exec(str)) != null)
32 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33 var pPrecision = a[6], pType = a[7];
43 if (numSubstitutions < arguments.length)
45 var param = arguments[numSubstitutions++];
48 if (pPad && pPad.substr(0,1) == "'")
49 pad = leftpart.substr(1,1);
53 var justifyRight = true;
54 if (pJustify && pJustify === "-")
59 minLength = parseInt(pMinLength);
62 if (pPrecision && pType == 'f')
63 precision = parseInt(pPrecision.substring(1));
70 subst = (parseInt(param) || 0).toString(2);
74 subst = String.fromCharCode(parseInt(param) || 0);
78 subst = (parseInt(param) || 0);
82 subst = Math.abs(parseInt(param) || 0);
86 subst = (precision > -1)
87 ? ((parseFloat(param) || 0.0)).toFixed(precision)
88 : (parseFloat(param) || 0.0);
92 subst = (parseInt(param) || 0).toString(8);
100 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
104 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
108 subst = esc(param, html_esc);
112 subst = esc(param, quot_esc);
116 subst = String.serialize(param);
123 var ts = (param || 0);
126 tm = Math.floor(ts / 60);
131 th = Math.floor(tm / 60);
136 td = Math.floor(th / 24);
141 ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142 : '%dh %dm %ds'.format(th, tm, ts);
147 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
151 var val = parseFloat(param || 0);
152 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i = 0; (i < units.length) && (val > mf); i++)
157 subst = val.toFixed(pr) + ' ' + units[i];
161 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
163 if (minLength > 0 && pad.length > 0)
164 for (var i = 0; i < (minLength - subst.length); i++)
165 subst = justifyRight ? (pad + subst) : (subst + pad);
169 out += leftpart + subst;
170 str = str.substr(m.length);
180 var Class = function() { };
182 Class.extend = function(properties)
184 Class.initializing = true;
186 var prototype = new this();
187 var superprot = this.prototype;
189 Class.initializing = false;
191 $.extend(prototype, properties, {
192 callSuper: function() {
194 var meth = arguments[0];
196 if (typeof(superprot[meth]) != 'function')
199 for (var i = 1; i < arguments.length; i++)
200 args.push(arguments[i]);
202 return superprot[meth].apply(this, args);
208 this.options = arguments[0] || { };
210 if (!Class.initializing && typeof(this.init) == 'function')
211 this.init.apply(this, arguments);
214 _class.prototype = prototype;
215 _class.prototype.constructor = _class;
217 _class.extend = Class.extend;
222 this.defaults = function(obj, def)
225 if (typeof(obj[key]) == 'undefined')
231 this.isDeferred = function(x)
233 return (typeof(x) == 'object' &&
234 typeof(x.then) == 'function' &&
235 typeof(x.promise) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments[0]))
243 var d = $.Deferred();
244 d.resolve.apply(d, arguments);
253 plural: function(n) { return 0 + (n != 1) },
256 if (_luci2.i18n.loaded)
259 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
262 for (var i = 0; i < langs.length; i++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
267 success: function(data) {
268 $.extend(_luci2.i18n.catalog, data);
270 var pe = _luci2.i18n.catalog[''];
273 delete _luci2.i18n.catalog[''];
275 var pf = new Function('n', 'return 0 + (' + pe + ')');
276 _luci2.i18n.plural = pf;
282 _luci2.i18n.loaded = true;
287 this.tr = function(msgid)
291 var msgstr = _luci2.i18n.catalog[msgid];
293 if (typeof(msgstr) == 'undefined')
295 else if (typeof(msgstr) == 'string')
301 this.trp = function(msgid, msgid_plural, count)
305 var msgstr = _luci2.i18n.catalog[msgid];
307 if (typeof(msgstr) == 'undefined')
308 return (count == 1) ? msgid : msgid_plural;
309 else if (typeof(msgstr) == 'string')
312 return msgstr[_luci2.i18n.plural(count)];
315 this.trc = function(msgctx, msgid)
319 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
321 if (typeof(msgstr) == 'undefined')
323 else if (typeof(msgstr) == 'string')
329 this.trcp = function(msgctx, msgid, msgid_plural, count)
333 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
335 if (typeof(msgstr) == 'undefined')
336 return (count == 1) ? msgid : msgid_plural;
337 else if (typeof(msgstr) == 'string')
340 return msgstr[_luci2.i18n.plural(count)];
343 this.setHash = function(key, value)
346 var data = this.getHash(undefined);
348 if (typeof(value) == 'undefined')
359 for (var i = 0; i < keys.length; i++)
364 h += keys[i] + ':' + data[keys[i]];
368 location.hash = '#' + h;
373 this.getHash = function(key)
376 var tuples = (location.hash || '#').substring(1).split(/,/);
378 for (var i = 0; i < tuples.length; i++)
380 var tuple = tuples[i].split(/:/);
381 if (tuple.length == 2)
382 data[tuple[0]] = tuple[1];
385 if (typeof(key) != 'undefined')
391 this.toArray = function(x)
401 var l = x.split(/\s+/);
402 for (var i = 0; i < l.length; i++)
411 for (var i = 0; i < x.length; i++)
415 else if ($.isPlainObject(x))
419 if (x.hasOwnProperty(k))
428 this.toObject = function(x)
438 var l = x.split(/\x+/);
439 for (var i = 0; i < l.length; i++)
448 for (var i = 0; i < x.length; i++)
452 else if ($.isPlainObject(x))
461 this.filterArray = function(array, item)
463 if (!$.isArray(array))
466 for (var i = 0; i < array.length; i++)
467 if (array[i] === item)
468 array.splice(i--, 1);
473 this.toClassName = function(str, suffix)
476 var l = str.split(/[\/.]/);
478 for (var i = 0; i < l.length; i++)
480 n += l[i].charAt(0).toUpperCase() + l[i].substr(1).toLowerCase();
482 if (typeof(suffix) == 'string')
491 sid: '00000000000000000000000000000000'
500 _call: function(req, cb)
502 return $.ajax('/ubus', {
504 contentType: 'application/json',
505 data: JSON.stringify(req),
508 timeout: _luci2.globals.timeout,
513 _list_cb: function(msg)
515 var list = msg.result;
517 /* verify message frame */
518 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id || !$.isArray(list))
521 return $.Deferred().resolveWith(this, [ list ]);
524 _call_cb: function(msg)
527 var type = Object.prototype.toString;
528 var reqs = this._rpc_req;
530 if (!$.isArray(reqs))
536 for (var i = 0; i < msg.length; i++)
538 /* fetch related request info */
539 var req = _luci2.rpc._requests[reqs[i].id];
540 if (typeof(req) != 'object')
541 throw 'No related request for JSON response';
543 /* fetch response attribute and verify returned type */
546 /* verify message frame */
547 if (typeof(msg[i]) == 'object' && msg[i].jsonrpc == '2.0')
548 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
549 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
553 for (var key in req.expect)
555 if (typeof(ret) != 'undefined' && key != '')
558 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
559 ret = req.expect[key];
566 if (typeof(req.filter) == 'function')
569 req.priv[1] = req.params;
570 ret = req.filter.apply(_luci2.rpc, req.priv);
573 /* store response data */
574 if (typeof(req.index) == 'number')
575 data[req.index] = ret;
579 /* delete request object */
580 delete _luci2.rpc._requests[reqs[i].id];
583 return $.Deferred().resolveWith(this, [ data ]);
589 for (var i = 0; i < arguments.length; i++)
590 params[i] = arguments[i];
596 params: (params.length > 0) ? params : undefined
599 return this._call(msg, this._list_cb);
604 if (!$.isArray(this._batch))
610 if (!$.isArray(this._batch))
611 return _luci2.deferrable([ ]);
613 var req = this._batch;
617 return this._call(req, this._call_cb);
620 declare: function(options)
625 /* build parameter object */
628 if ($.isArray(options.params))
629 for (p_off = 0; p_off < options.params.length; p_off++)
630 params[options.params[p_off]] = arguments[p_off];
632 /* all remaining arguments are private args */
633 var priv = [ undefined, undefined ];
634 for (; p_off < arguments.length; p_off++)
635 priv.push(arguments[p_off]);
637 /* store request info */
638 var req = _rpc._requests[_rpc._id] = {
639 expect: options.expect,
640 filter: options.filter,
645 /* build message object */
658 /* when a batch is in progress then store index in request data
659 * and push message object onto the stack */
660 if ($.isArray(_rpc._batch))
662 req.index = _rpc._batch.push(msg) - 1;
663 return _luci2.deferrable(msg);
667 return _rpc._call(msg, _rpc._call_cb);
672 this.UCIContext = Class.extend({
686 _load: _luci2.rpc.declare({
689 params: [ 'config' ],
690 expect: { values: { } }
693 _order: _luci2.rpc.declare({
696 params: [ 'config', 'sections' ]
699 _add: _luci2.rpc.declare({
702 params: [ 'config', 'type', 'name', 'values' ],
703 expect: { section: '' }
706 _set: _luci2.rpc.declare({
709 params: [ 'config', 'section', 'values' ]
712 _delete: _luci2.rpc.declare({
715 params: [ 'config', 'section', 'options' ]
718 load: function(packages)
724 if (!$.isArray(packages))
725 packages = [ packages ];
729 for (var i = 0; i < packages.length; i++)
730 if (!seen[packages[i]])
732 pkgs.push(packages[i]);
733 seen[packages[i]] = true;
734 self._load(packages[i]);
737 return _luci2.rpc.flush().then(function(responses) {
738 for (var i = 0; i < responses.length; i++)
739 self.state.values[pkgs[i]] = responses[i];
745 unload: function(packages)
747 if (!$.isArray(packages))
748 packages = [ packages ];
750 for (var i = 0; i < packages.length; i++)
752 delete this.state.values[packages[i]];
753 delete this.state.creates[packages[i]];
754 delete this.state.changes[packages[i]];
755 delete this.state.deletes[packages[i]];
759 add: function(conf, type, name)
761 var c = this.state.creates;
762 var s = '.new.%d'.format(this.state.newid++);
772 '.index': 1000 + this.state.newid
778 remove: function(conf, sid)
780 var n = this.state.creates;
781 var c = this.state.changes;
782 var d = this.state.deletes;
784 /* requested deletion of a just created section */
785 if (sid.indexOf('.new.') == 0)
802 sections: function(conf, type, cb)
805 var v = this.state.values[conf];
806 var n = this.state.creates[conf];
807 var c = this.state.changes[conf];
808 var d = this.state.deletes[conf];
814 if (!d || d[s] !== true)
815 if (!type || v[s]['.type'] == type)
816 sa.push($.extend({ }, v[s], c ? c[s] : undefined));
820 if (!type || n[s]['.type'] == type)
823 sa.sort(function(a, b) {
824 return a['.index'] - b['.index'];
827 for (var i = 0; i < sa.length; i++)
830 if (typeof(cb) == 'function')
831 for (var i = 0; i < sa.length; i++)
832 cb.call(this, sa[i], sa[i]['.name']);
837 get: function(conf, sid, opt)
839 var v = this.state.values;
840 var n = this.state.creates;
841 var c = this.state.changes;
842 var d = this.state.deletes;
844 if (typeof(sid) == 'undefined')
847 /* requested option in a just created section */
848 if (sid.indexOf('.new.') == 0)
853 if (typeof(opt) == 'undefined')
856 return n[conf][sid][opt];
859 /* requested an option value */
860 if (typeof(opt) != 'undefined')
862 /* check whether option was deleted */
863 if (d[conf] && d[conf][sid])
865 if (d[conf][sid] === true)
868 for (var i = 0; i < d[conf][sid].length; i++)
869 if (d[conf][sid][i] == opt)
873 /* check whether option was changed */
874 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
875 return c[conf][sid][opt];
877 /* return base value */
878 if (v[conf] && v[conf][sid])
879 return v[conf][sid][opt];
884 /* requested an entire section */
891 set: function(conf, sid, opt, val)
893 var n = this.state.creates;
894 var c = this.state.changes;
895 var d = this.state.deletes;
897 if (typeof(sid) == 'undefined' ||
898 typeof(opt) == 'undefined' ||
899 opt.charAt(0) == '.')
902 if (sid.indexOf('.new.') == 0)
904 if (n[conf] && n[conf][sid])
906 if (typeof(val) != 'undefined')
907 n[conf][sid][opt] = val;
909 delete n[conf][sid][opt];
912 else if (typeof(val) != 'undefined')
914 /* do not set within deleted section */
915 if (d[conf] && d[conf][sid] === true)
924 /* undelete option */
925 if (d[conf] && d[conf][sid])
926 d[conf][sid] = _luci2.filterArray(d[conf][sid], opt);
928 c[conf][sid][opt] = val;
938 if (d[conf][sid] !== true)
939 d[conf][sid].push(opt);
943 unset: function(conf, sid, opt)
945 return this.set(conf, sid, opt, undefined);
952 for (var pkg in this.state.values)
957 return this.load(pkgs);
962 var v = this.state.values;
963 var n = this.state.creates;
964 var r = this.state.reorder;
966 if ($.isEmptyObject(r))
967 return _luci2.deferrable();
972 gather all created and existing sections, sort them according
973 to their index value and issue an uci order call
988 o.sort(function(a, b) {
989 return (a['.index'] - b['.index']);
994 for (var i = 0; i < o.length; i++)
995 sids.push(o[i]['.name']);
997 this._order(c, sids);
1001 this.state.reorder = { };
1002 return _luci2.rpc.flush();
1005 swap: function(conf, sid1, sid2)
1007 var s1 = this.get(conf, sid1);
1008 var s2 = this.get(conf, sid2);
1009 var n1 = s1 ? s1['.index'] : NaN;
1010 var n2 = s2 ? s2['.index'] : NaN;
1012 if (isNaN(n1) || isNaN(n2))
1018 this.state.reorder[conf] = true;
1030 if (self.state.creates)
1031 for (var c in self.state.creates)
1032 for (var s in self.state.creates[c])
1039 for (var k in self.state.creates[c][s])
1042 r.type = self.state.creates[c][s][k];
1043 else if (k == '.create')
1044 r.name = self.state.creates[c][s][k];
1045 else if (k.charAt(0) != '.')
1046 r.values[k] = self.state.creates[c][s][k];
1049 snew.push(self.state.creates[c][s]);
1051 self._add(r.config, r.type, r.name, r.values);
1054 if (self.state.changes)
1055 for (var c in self.state.changes)
1056 for (var s in self.state.changes[c])
1057 self._set(c, s, self.state.changes[c][s]);
1059 if (self.state.deletes)
1060 for (var c in self.state.deletes)
1061 for (var s in self.state.deletes[c])
1063 var o = self.state.deletes[c][s];
1064 self._delete(c, s, (o === true) ? undefined : o);
1067 return _luci2.rpc.flush().then(function(responses) {
1069 array "snew" holds references to the created uci sections,
1070 use it to assign the returned names of the new sections
1072 for (var i = 0; i < snew.length; i++)
1073 snew[i]['.name'] = responses[i];
1075 return self._reorder();
1079 _apply: _luci2.rpc.declare({
1082 params: [ 'timeout', 'rollback' ]
1085 _confirm: _luci2.rpc.declare({
1090 apply: function(timeout)
1093 var date = new Date();
1094 var deferred = $.Deferred();
1096 if (typeof(timeout) != 'number' || timeout < 1)
1099 self._apply(timeout, true).then(function(rv) {
1102 deferred.rejectWith(self, [ rv ]);
1106 var try_deadline = date.getTime() + 1000 * timeout;
1107 var try_confirm = function()
1109 return self._confirm().then(function(rv) {
1112 if (date.getTime() < try_deadline)
1113 window.setTimeout(try_confirm, 250);
1115 deferred.rejectWith(self, [ rv ]);
1120 deferred.resolveWith(self, [ rv ]);
1124 window.setTimeout(try_confirm, 1000);
1130 changes: _luci2.rpc.declare({
1133 expect: { changes: { } }
1136 readable: function(conf)
1138 return _luci2.session.hasACL('uci', conf, 'read');
1141 writable: function(conf)
1143 return _luci2.session.hasACL('uci', conf, 'write');
1149 writable: function()
1151 return _luci2.session.access('ubus', 'uci', 'commit');
1154 add: _luci2.rpc.declare({
1157 params: [ 'config', 'type', 'name', 'values' ],
1158 expect: { section: '' }
1166 configs: _luci2.rpc.declare({
1169 expect: { configs: [ ] }
1172 _changes: _luci2.rpc.declare({
1175 params: [ 'config' ],
1176 expect: { changes: [ ] }
1179 changes: function(config)
1181 if (typeof(config) == 'string')
1182 return this._changes(config);
1185 return this.configs().then(function(configs) {
1187 configlist = configs;
1189 for (var i = 0; i < configs.length; i++)
1190 _luci2.uci._changes(configs[i]);
1192 return _luci2.rpc.flush();
1193 }).then(function(changes) {
1196 for (var i = 0; i < configlist.length; i++)
1197 if (changes[i].length)
1198 rv[configlist[i]] = changes[i];
1204 commit: _luci2.rpc.declare({
1207 params: [ 'config' ]
1210 _delete_one: _luci2.rpc.declare({
1213 params: [ 'config', 'section', 'option' ]
1216 _delete_multiple: _luci2.rpc.declare({
1219 params: [ 'config', 'section', 'options' ]
1222 'delete': function(config, section, option)
1224 if ($.isArray(option))
1225 return this._delete_multiple(config, section, option);
1227 return this._delete_one(config, section, option);
1230 delete_all: _luci2.rpc.declare({
1233 params: [ 'config', 'type', 'match' ]
1236 _foreach: _luci2.rpc.declare({
1239 params: [ 'config', 'type' ],
1240 expect: { values: { } }
1243 foreach: function(config, type, cb)
1245 return this._foreach(config, type).then(function(sections) {
1246 for (var s in sections)
1251 get: _luci2.rpc.declare({
1254 params: [ 'config', 'section', 'option' ],
1255 expect: { '': { } },
1256 filter: function(data, params) {
1257 if (typeof(params.option) == 'undefined')
1258 return data.values ? data.values['.type'] : undefined;
1264 get_all: _luci2.rpc.declare({
1267 params: [ 'config', 'section' ],
1268 expect: { values: { } },
1269 filter: function(data, params) {
1270 if (typeof(params.section) == 'string')
1271 data['.section'] = params.section;
1272 else if (typeof(params.config) == 'string')
1273 data['.package'] = params.config;
1278 get_first: function(config, type, option)
1280 return this._foreach(config, type).then(function(sections) {
1281 for (var s in sections)
1283 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
1285 if (typeof(val) != 'undefined')
1293 section: _luci2.rpc.declare({
1296 params: [ 'config', 'type', 'name', 'values' ],
1297 expect: { section: '' }
1300 _set: _luci2.rpc.declare({
1303 params: [ 'config', 'section', 'values' ]
1306 set: function(config, section, option, value)
1308 if (typeof(value) == 'undefined' && typeof(option) == 'string')
1309 return this.section(config, section, option); /* option -> type */
1310 else if ($.isPlainObject(option))
1311 return this._set(config, section, option); /* option -> values */
1314 values[option] = value;
1316 return this._set(config, section, values);
1319 order: _luci2.rpc.declare({
1322 params: [ 'config', 'sections' ]
1327 listNetworkNames: function() {
1328 return _luci2.rpc.list('network.interface.*').then(function(list) {
1330 for (var name in list)
1331 if (name != 'network.interface.loopback')
1332 names.push(name.substring(18));
1338 listDeviceNames: _luci2.rpc.declare({
1339 object: 'network.device',
1341 expect: { '': { } },
1342 filter: function(data) {
1344 for (var name in data)
1352 getNetworkStatus: function()
1357 return this.listNetworkNames().then(function(names) {
1360 for (var i = 0; i < names.length; i++)
1361 _luci2.network.getInterfaceStatus(names[i]);
1363 return _luci2.rpc.flush();
1364 }).then(function(networks) {
1365 for (var i = 0; i < networks.length; i++)
1367 var net = nets[i] = networks[i];
1368 var dev = net.l3_device || net.l2_device;
1370 net.device = devs[dev] || (devs[dev] = { });
1375 for (var dev in devs)
1376 _luci2.network.getDeviceStatus(dev);
1378 return _luci2.rpc.flush();
1379 }).then(function(devices) {
1382 for (var i = 0; i < devices.length; i++)
1384 var brm = devices[i]['bridge-members'];
1385 delete devices[i]['bridge-members'];
1387 $.extend(devs[devices[i]['device']], devices[i]);
1392 devs[devices[i]['device']].subdevices = [ ];
1394 for (var j = 0; j < brm.length; j++)
1399 _luci2.network.getDeviceStatus(brm[j]);
1402 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
1406 return _luci2.rpc.flush();
1407 }).then(function(subdevices) {
1408 for (var i = 0; i < subdevices.length; i++)
1409 $.extend(devs[subdevices[i]['device']], subdevices[i]);
1413 for (var dev in devs)
1414 _luci2.wireless.getDeviceStatus(dev);
1416 return _luci2.rpc.flush();
1417 }).then(function(wifidevices) {
1418 for (var i = 0; i < wifidevices.length; i++)
1420 devs[wifidevices[i]['device']].wireless = wifidevices[i];
1422 nets.sort(function(a, b) {
1423 if (a['interface'] < b['interface'])
1425 else if (a['interface'] > b['interface'])
1435 findWanInterfaces: function(cb)
1437 return this.listNetworkNames().then(function(names) {
1440 for (var i = 0; i < names.length; i++)
1441 _luci2.network.getInterfaceStatus(names[i]);
1443 return _luci2.rpc.flush();
1444 }).then(function(interfaces) {
1445 var rv = [ undefined, undefined ];
1447 for (var i = 0; i < interfaces.length; i++)
1449 if (!interfaces[i].route)
1452 for (var j = 0; j < interfaces[i].route.length; j++)
1454 var rt = interfaces[i].route[j];
1456 if (typeof(rt.table) != 'undefined')
1459 if (rt.target == '0.0.0.0' && rt.mask == 0)
1460 rv[0] = interfaces[i];
1461 else if (rt.target == '::' && rt.mask == 0)
1462 rv[1] = interfaces[i];
1470 getDHCPLeases: _luci2.rpc.declare({
1471 object: 'luci2.network',
1472 method: 'dhcp_leases',
1473 expect: { leases: [ ] }
1476 getDHCPv6Leases: _luci2.rpc.declare({
1477 object: 'luci2.network',
1478 method: 'dhcp6_leases',
1479 expect: { leases: [ ] }
1482 getRoutes: _luci2.rpc.declare({
1483 object: 'luci2.network',
1485 expect: { routes: [ ] }
1488 getIPv6Routes: _luci2.rpc.declare({
1489 object: 'luci2.network',
1491 expect: { routes: [ ] }
1494 getARPTable: _luci2.rpc.declare({
1495 object: 'luci2.network',
1496 method: 'arp_table',
1497 expect: { entries: [ ] }
1500 getInterfaceStatus: _luci2.rpc.declare({
1501 object: 'network.interface',
1503 params: [ 'interface' ],
1504 expect: { '': { } },
1505 filter: function(data, params) {
1506 data['interface'] = params['interface'];
1507 data['l2_device'] = data['device'];
1508 delete data['device'];
1513 getDeviceStatus: _luci2.rpc.declare({
1514 object: 'network.device',
1517 expect: { '': { } },
1518 filter: function(data, params) {
1519 data['device'] = params['name'];
1524 getConntrackCount: _luci2.rpc.declare({
1525 object: 'luci2.network',
1526 method: 'conntrack_count',
1527 expect: { '': { count: 0, limit: 0 } }
1530 listSwitchNames: _luci2.rpc.declare({
1531 object: 'luci2.network',
1532 method: 'switch_list',
1533 expect: { switches: [ ] }
1536 getSwitchInfo: _luci2.rpc.declare({
1537 object: 'luci2.network',
1538 method: 'switch_info',
1539 params: [ 'switch' ],
1540 expect: { info: { } },
1541 filter: function(data, params) {
1542 data['attrs'] = data['switch'];
1543 data['vlan_attrs'] = data['vlan'];
1544 data['port_attrs'] = data['port'];
1545 data['switch'] = params['switch'];
1554 getSwitchStatus: _luci2.rpc.declare({
1555 object: 'luci2.network',
1556 method: 'switch_status',
1557 params: [ 'switch' ],
1558 expect: { ports: [ ] }
1562 runPing: _luci2.rpc.declare({
1563 object: 'luci2.network',
1566 expect: { '': { code: -1 } }
1569 runPing6: _luci2.rpc.declare({
1570 object: 'luci2.network',
1573 expect: { '': { code: -1 } }
1576 runTraceroute: _luci2.rpc.declare({
1577 object: 'luci2.network',
1578 method: 'traceroute',
1580 expect: { '': { code: -1 } }
1583 runTraceroute6: _luci2.rpc.declare({
1584 object: 'luci2.network',
1585 method: 'traceroute6',
1587 expect: { '': { code: -1 } }
1590 runNslookup: _luci2.rpc.declare({
1591 object: 'luci2.network',
1594 expect: { '': { code: -1 } }
1598 setUp: _luci2.rpc.declare({
1599 object: 'luci2.network',
1602 expect: { '': { code: -1 } }
1605 setDown: _luci2.rpc.declare({
1606 object: 'luci2.network',
1609 expect: { '': { code: -1 } }
1614 listDeviceNames: _luci2.rpc.declare({
1617 expect: { 'devices': [ ] },
1618 filter: function(data) {
1624 getDeviceStatus: _luci2.rpc.declare({
1627 params: [ 'device' ],
1628 expect: { '': { } },
1629 filter: function(data, params) {
1630 if (!$.isEmptyObject(data))
1632 data['device'] = params['device'];
1639 getAssocList: _luci2.rpc.declare({
1641 method: 'assoclist',
1642 params: [ 'device' ],
1643 expect: { results: [ ] },
1644 filter: function(data, params) {
1645 for (var i = 0; i < data.length; i++)
1646 data[i]['device'] = params['device'];
1648 data.sort(function(a, b) {
1649 if (a.bssid < b.bssid)
1651 else if (a.bssid > b.bssid)
1661 getWirelessStatus: function() {
1662 return this.listDeviceNames().then(function(names) {
1665 for (var i = 0; i < names.length; i++)
1666 _luci2.wireless.getDeviceStatus(names[i]);
1668 return _luci2.rpc.flush();
1669 }).then(function(networks) {
1673 'country', 'channel', 'frequency', 'frequency_offset',
1674 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1678 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1679 'signal', 'noise', 'bitrate', 'encryption'
1682 for (var i = 0; i < networks.length; i++)
1684 var phy = rv[networks[i].phy] || (
1685 rv[networks[i].phy] = { networks: [ ] }
1689 device: networks[i].device
1692 for (var j = 0; j < phy_attrs.length; j++)
1693 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1695 for (var j = 0; j < net_attrs.length; j++)
1696 net[net_attrs[j]] = networks[i][net_attrs[j]];
1698 phy.networks.push(net);
1705 getAssocLists: function()
1707 return this.listDeviceNames().then(function(names) {
1710 for (var i = 0; i < names.length; i++)
1711 _luci2.wireless.getAssocList(names[i]);
1713 return _luci2.rpc.flush();
1714 }).then(function(assoclists) {
1717 for (var i = 0; i < assoclists.length; i++)
1718 for (var j = 0; j < assoclists[i].length; j++)
1719 rv.push(assoclists[i][j]);
1725 formatEncryption: function(enc)
1727 var format_list = function(l, s)
1730 for (var i = 0; i < l.length; i++)
1731 rv.push(l[i].toUpperCase());
1732 return rv.join(s ? s : ', ');
1735 if (!enc || !enc.enabled)
1736 return _luci2.tr('None');
1740 if (enc.wep.length == 2)
1741 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1742 else if (enc.wep[0] == 'shared')
1743 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1745 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1749 if (enc.wpa.length == 2)
1750 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1751 format_list(enc.authentication, '/'),
1752 format_list(enc.ciphers, ', ')
1754 else if (enc.wpa[0] == 2)
1755 return 'WPA2 %s (%s)'.format(
1756 format_list(enc.authentication, '/'),
1757 format_list(enc.ciphers, ', ')
1760 return 'WPA %s (%s)'.format(
1761 format_list(enc.authentication, '/'),
1762 format_list(enc.ciphers, ', ')
1766 return _luci2.tr('Unknown');
1771 getZoneColor: function(zone)
1773 if ($.isPlainObject(zone))
1778 else if (zone == 'wan')
1781 for (var i = 0, hash = 0;
1783 hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1785 for (var i = 0, color = '#';
1787 color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1792 findZoneByNetwork: function(network)
1795 var zone = undefined;
1797 return _luci2.uci.foreach('firewall', 'zone', function(z) {
1798 if (!z.name || !z.network)
1801 if (!$.isArray(z.network))
1802 z.network = z.network.split(/\s+/);
1804 for (var i = 0; i < z.network.length; i++)
1806 if (z.network[i] == network)
1812 }).then(function() {
1814 zone.color = self.getZoneColor(zone);
1822 getSystemInfo: _luci2.rpc.declare({
1828 getBoardInfo: _luci2.rpc.declare({
1834 getDiskInfo: _luci2.rpc.declare({
1835 object: 'luci2.system',
1840 getInfo: function(cb)
1844 this.getSystemInfo();
1845 this.getBoardInfo();
1848 return _luci2.rpc.flush().then(function(info) {
1851 $.extend(rv, info[0]);
1852 $.extend(rv, info[1]);
1853 $.extend(rv, info[2]);
1859 getProcessList: _luci2.rpc.declare({
1860 object: 'luci2.system',
1861 method: 'process_list',
1862 expect: { processes: [ ] },
1863 filter: function(data) {
1864 data.sort(function(a, b) { return a.pid - b.pid });
1869 getSystemLog: _luci2.rpc.declare({
1870 object: 'luci2.system',
1875 getKernelLog: _luci2.rpc.declare({
1876 object: 'luci2.system',
1881 getZoneInfo: function(cb)
1883 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1886 sendSignal: _luci2.rpc.declare({
1887 object: 'luci2.system',
1888 method: 'process_signal',
1889 params: [ 'pid', 'signal' ],
1890 filter: function(data) {
1895 initList: _luci2.rpc.declare({
1896 object: 'luci2.system',
1897 method: 'init_list',
1898 expect: { initscripts: [ ] },
1899 filter: function(data) {
1900 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1905 initEnabled: function(init, cb)
1907 return this.initList().then(function(list) {
1908 for (var i = 0; i < list.length; i++)
1909 if (list[i].name == init)
1910 return !!list[i].enabled;
1916 initRun: _luci2.rpc.declare({
1917 object: 'luci2.system',
1918 method: 'init_action',
1919 params: [ 'name', 'action' ],
1920 filter: function(data) {
1925 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1926 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1927 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1928 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1929 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1930 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1933 getRcLocal: _luci2.rpc.declare({
1934 object: 'luci2.system',
1935 method: 'rclocal_get',
1936 expect: { data: '' }
1939 setRcLocal: _luci2.rpc.declare({
1940 object: 'luci2.system',
1941 method: 'rclocal_set',
1946 getCrontab: _luci2.rpc.declare({
1947 object: 'luci2.system',
1948 method: 'crontab_get',
1949 expect: { data: '' }
1952 setCrontab: _luci2.rpc.declare({
1953 object: 'luci2.system',
1954 method: 'crontab_set',
1959 getSSHKeys: _luci2.rpc.declare({
1960 object: 'luci2.system',
1961 method: 'sshkeys_get',
1962 expect: { keys: [ ] }
1965 setSSHKeys: _luci2.rpc.declare({
1966 object: 'luci2.system',
1967 method: 'sshkeys_set',
1972 setPassword: _luci2.rpc.declare({
1973 object: 'luci2.system',
1974 method: 'password_set',
1975 params: [ 'user', 'password' ]
1979 listLEDs: _luci2.rpc.declare({
1980 object: 'luci2.system',
1982 expect: { leds: [ ] }
1985 listUSBDevices: _luci2.rpc.declare({
1986 object: 'luci2.system',
1988 expect: { devices: [ ] }
1992 testUpgrade: _luci2.rpc.declare({
1993 object: 'luci2.system',
1994 method: 'upgrade_test',
1998 startUpgrade: _luci2.rpc.declare({
1999 object: 'luci2.system',
2000 method: 'upgrade_start',
2004 cleanUpgrade: _luci2.rpc.declare({
2005 object: 'luci2.system',
2006 method: 'upgrade_clean'
2010 restoreBackup: _luci2.rpc.declare({
2011 object: 'luci2.system',
2012 method: 'backup_restore'
2015 cleanBackup: _luci2.rpc.declare({
2016 object: 'luci2.system',
2017 method: 'backup_clean'
2021 getBackupConfig: _luci2.rpc.declare({
2022 object: 'luci2.system',
2023 method: 'backup_config_get',
2024 expect: { config: '' }
2027 setBackupConfig: _luci2.rpc.declare({
2028 object: 'luci2.system',
2029 method: 'backup_config_set',
2034 listBackup: _luci2.rpc.declare({
2035 object: 'luci2.system',
2036 method: 'backup_list',
2037 expect: { files: [ ] }
2041 testReset: _luci2.rpc.declare({
2042 object: 'luci2.system',
2043 method: 'reset_test',
2044 expect: { supported: false }
2047 startReset: _luci2.rpc.declare({
2048 object: 'luci2.system',
2049 method: 'reset_start'
2053 performReboot: _luci2.rpc.declare({
2054 object: 'luci2.system',
2060 updateLists: _luci2.rpc.declare({
2061 object: 'luci2.opkg',
2066 _allPackages: _luci2.rpc.declare({
2067 object: 'luci2.opkg',
2069 params: [ 'offset', 'limit', 'pattern' ],
2073 _installedPackages: _luci2.rpc.declare({
2074 object: 'luci2.opkg',
2075 method: 'list_installed',
2076 params: [ 'offset', 'limit', 'pattern' ],
2080 _findPackages: _luci2.rpc.declare({
2081 object: 'luci2.opkg',
2083 params: [ 'offset', 'limit', 'pattern' ],
2087 _fetchPackages: function(action, offset, limit, pattern)
2091 return action(offset, limit, pattern).then(function(list) {
2092 if (!list.total || !list.packages)
2093 return { length: 0, total: 0 };
2095 packages.push.apply(packages, list.packages);
2096 packages.total = list.total;
2101 if (packages.length >= limit)
2106 for (var i = offset + packages.length; i < limit; i += 100)
2107 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
2109 return _luci2.rpc.flush();
2110 }).then(function(lists) {
2111 for (var i = 0; i < lists.length; i++)
2113 if (!lists[i].total || !lists[i].packages)
2116 packages.push.apply(packages, lists[i].packages);
2117 packages.total = lists[i].total;
2124 listPackages: function(offset, limit, pattern)
2126 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
2129 installedPackages: function(offset, limit, pattern)
2131 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
2134 findPackages: function(offset, limit, pattern)
2136 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
2139 installPackage: _luci2.rpc.declare({
2140 object: 'luci2.opkg',
2142 params: [ 'package' ],
2146 removePackage: _luci2.rpc.declare({
2147 object: 'luci2.opkg',
2149 params: [ 'package' ],
2153 getConfig: _luci2.rpc.declare({
2154 object: 'luci2.opkg',
2155 method: 'config_get',
2156 expect: { config: '' }
2159 setConfig: _luci2.rpc.declare({
2160 object: 'luci2.opkg',
2161 method: 'config_set',
2168 login: _luci2.rpc.declare({
2171 params: [ 'username', 'password' ],
2175 access: _luci2.rpc.declare({
2178 params: [ 'scope', 'object', 'function' ],
2179 expect: { access: false }
2184 return _luci2.session.access('ubus', 'session', 'access');
2187 startHeartbeat: function()
2189 this._hearbeatInterval = window.setInterval(function() {
2190 _luci2.session.isAlive().then(function(alive) {
2193 _luci2.session.stopHeartbeat();
2194 _luci2.ui.login(true);
2198 }, _luci2.globals.timeout * 2);
2201 stopHeartbeat: function()
2203 if (typeof(this._hearbeatInterval) != 'undefined')
2205 window.clearInterval(this._hearbeatInterval);
2206 delete this._hearbeatInterval;
2213 saveScrollTop: function()
2215 this._scroll_top = $(document).scrollTop();
2218 restoreScrollTop: function()
2220 if (typeof(this._scroll_top) == 'undefined')
2223 $(document).scrollTop(this._scroll_top);
2225 delete this._scroll_top;
2228 loading: function(enable)
2230 var win = $(window);
2231 var body = $('body');
2233 var state = _luci2.ui._loading || (_luci2.ui._loading = {
2235 .addClass('modal fade')
2236 .append($('<div />')
2237 .addClass('modal-dialog')
2238 .append($('<div />')
2239 .addClass('modal-content luci2-modal-loader')
2240 .append($('<div />')
2241 .addClass('modal-body')
2242 .text(_luci2.tr('Loading data…')))))
2250 state.modal.modal(enable ? 'show' : 'hide');
2253 dialog: function(title, content, options)
2255 var win = $(window);
2256 var body = $('body');
2258 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
2259 dialog: $('<div />')
2260 .addClass('modal fade')
2261 .append($('<div />')
2262 .addClass('modal-dialog')
2263 .append($('<div />')
2264 .addClass('modal-content')
2265 .append($('<div />')
2266 .addClass('modal-header')
2268 .addClass('modal-title'))
2269 .append($('<div />')
2270 .addClass('modal-body'))
2271 .append($('<div />')
2272 .addClass('modal-footer')
2273 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2275 $(this).parents('div.modal').modal('hide');
2280 if (typeof(options) != 'object')
2283 if (title === false)
2285 state.dialog.modal('hide');
2290 var cnt = state.dialog.children().children().children('div.modal-body');
2291 var ftr = state.dialog.children().children().children('div.modal-footer');
2295 if (options.style == 'confirm')
2297 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
2298 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
2300 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
2301 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
2303 else if (options.style == 'close')
2305 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2306 .click(options.close || function() { _luci2.ui.dialog(false) }));
2308 else if (options.style == 'wait')
2310 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2311 .attr('disabled', true));
2314 state.dialog.find('h4:first').text(title);
2315 state.dialog.modal('show');
2317 cnt.empty().append(content);
2320 upload: function(title, content, options)
2322 var state = _luci2.ui._upload || (_luci2.ui._upload = {
2324 .attr('method', 'post')
2325 .attr('action', '/cgi-bin/luci-upload')
2326 .attr('enctype', 'multipart/form-data')
2327 .attr('target', 'cbi-fileupload-frame')
2329 .append($('<input />')
2330 .attr('type', 'hidden')
2331 .attr('name', 'sessionid'))
2332 .append($('<input />')
2333 .attr('type', 'hidden')
2334 .attr('name', 'filename'))
2335 .append($('<input />')
2336 .attr('type', 'file')
2337 .attr('name', 'filedata')
2338 .addClass('cbi-input-file'))
2339 .append($('<div />')
2340 .css('width', '100%')
2341 .addClass('progress progress-striped active')
2342 .append($('<div />')
2343 .addClass('progress-bar')
2344 .css('width', '100%')))
2345 .append($('<iframe />')
2346 .addClass('pull-right')
2347 .attr('name', 'cbi-fileupload-frame')
2348 .css('width', '1px')
2349 .css('height', '1px')
2350 .css('visibility', 'hidden')),
2352 finish_cb: function(ev) {
2353 $(this).off('load');
2355 var body = (this.contentDocument || this.contentWindow.document).body;
2356 if (body.firstChild.tagName.toLowerCase() == 'pre')
2357 body = body.firstChild;
2361 json = $.parseJSON(body.innerHTML);
2364 message: _luci2.tr('Invalid server response received'),
2365 error: [ -1, _luci2.tr('Invalid data') ]
2371 L.ui.dialog(L.tr('File upload'), [
2372 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
2373 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
2374 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
2375 ], { style: 'close' });
2377 else if (typeof(state.success_cb) == 'function')
2379 state.success_cb(json);
2383 confirm_cb: function() {
2384 var f = state.form.find('.cbi-input-file');
2385 var b = state.form.find('.progress');
2386 var p = state.form.find('p');
2391 state.form.find('iframe').on('load', state.finish_cb);
2392 state.form.submit();
2396 p.text(_luci2.tr('File upload in progress …'));
2398 state.form.parent().parent().find('button').prop('disabled', true);
2402 state.form.find('.progress').hide();
2403 state.form.find('.cbi-input-file').val('').show();
2404 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
2406 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
2407 state.form.find('[name=filename]').val(options.filename);
2409 state.success_cb = options.success;
2411 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
2413 confirm: state.confirm_cb
2417 reconnect: function()
2419 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
2420 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
2421 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
2423 var interval, timeout;
2426 _luci2.tr('Waiting for device'), [
2427 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
2429 .css('width', '100%')
2430 .addClass('progressbar')
2431 .addClass('intermediate')
2432 .append($('<div />')
2433 .css('width', '100%'))
2434 ], { style: 'wait' }
2437 for (var i = 0; i < protocols.length; i++)
2438 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
2440 //_luci2.network.getNetworkStatus(function(s) {
2441 // for (var i = 0; i < protocols.length; i++)
2443 // for (var j = 0; j < s.length; j++)
2445 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
2446 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
2448 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
2449 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
2452 //}).then(function() {
2453 images.on('load', function() {
2454 var url = this.getAttribute('url');
2455 _luci2.session.isAlive().then(function(access) {
2458 window.clearTimeout(timeout);
2459 window.clearInterval(interval);
2460 _luci2.ui.dialog(false);
2465 location.href = url;
2470 interval = window.setInterval(function() {
2471 images.each(function() {
2472 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
2476 timeout = window.setTimeout(function() {
2477 window.clearInterval(interval);
2481 _luci2.tr('Device not responding'),
2482 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2489 login: function(invalid)
2491 var state = _luci2.ui._login || (_luci2.ui._login = {
2494 .attr('method', 'post')
2496 .addClass('alert-message')
2497 .text(_luci2.tr('Wrong username or password given!')))
2499 .append($('<label />')
2500 .text(_luci2.tr('Username'))
2501 .append($('<br />'))
2502 .append($('<input />')
2503 .attr('type', 'text')
2504 .attr('name', 'username')
2505 .attr('value', 'root')
2506 .addClass('form-control')
2507 .keypress(function(ev) {
2508 if (ev.which == 10 || ev.which == 13)
2512 .append($('<label />')
2513 .text(_luci2.tr('Password'))
2514 .append($('<br />'))
2515 .append($('<input />')
2516 .attr('type', 'password')
2517 .attr('name', 'password')
2518 .addClass('form-control')
2519 .keypress(function(ev) {
2520 if (ev.which == 10 || ev.which == 13)
2524 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
2526 response_cb: function(response) {
2527 if (!response.ubus_rpc_session)
2529 _luci2.ui.login(true);
2533 _luci2.globals.sid = response.ubus_rpc_session;
2534 _luci2.setHash('id', _luci2.globals.sid);
2535 _luci2.session.startHeartbeat();
2536 _luci2.ui.dialog(false);
2537 state.deferred.resolve();
2541 confirm_cb: function() {
2542 var u = state.form.find('[name=username]').val();
2543 var p = state.form.find('[name=password]').val();
2549 _luci2.tr('Logging in'), [
2550 $('<p />').text(_luci2.tr('Log in in progress …')),
2552 .css('width', '100%')
2553 .addClass('progressbar')
2554 .addClass('intermediate')
2555 .append($('<div />')
2556 .css('width', '100%'))
2557 ], { style: 'wait' }
2560 _luci2.globals.sid = '00000000000000000000000000000000';
2561 _luci2.session.login(u, p).then(state.response_cb);
2565 if (!state.deferred || state.deferred.state() != 'pending')
2566 state.deferred = $.Deferred();
2568 /* try to find sid from hash */
2569 var sid = _luci2.getHash('id');
2570 if (sid && sid.match(/^[a-f0-9]{32}$/))
2572 _luci2.globals.sid = sid;
2573 _luci2.session.isAlive().then(function(access) {
2576 _luci2.session.startHeartbeat();
2577 state.deferred.resolve();
2581 _luci2.setHash('id', undefined);
2586 return state.deferred;
2590 state.form.find('.alert-message').show();
2592 state.form.find('.alert-message').hide();
2594 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2596 confirm: state.confirm_cb
2599 state.form.find('[name=password]').focus();
2601 return state.deferred;
2604 cryptPassword: _luci2.rpc.declare({
2608 expect: { crypt: '' }
2612 _acl_merge_scope: function(acl_scope, scope)
2614 if ($.isArray(scope))
2616 for (var i = 0; i < scope.length; i++)
2617 acl_scope[scope[i]] = true;
2619 else if ($.isPlainObject(scope))
2621 for (var object_name in scope)
2623 if (!$.isArray(scope[object_name]))
2626 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2628 for (var i = 0; i < scope[object_name].length; i++)
2629 acl_object[scope[object_name][i]] = true;
2634 _acl_merge_permission: function(acl_perm, perm)
2636 if ($.isPlainObject(perm))
2638 for (var scope_name in perm)
2640 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2641 this._acl_merge_scope(acl_scope, perm[scope_name]);
2646 _acl_merge_group: function(acl_group, group)
2648 if ($.isPlainObject(group))
2650 if (!acl_group.description)
2651 acl_group.description = group.description;
2655 var acl_perm = acl_group.read || (acl_group.read = { });
2656 this._acl_merge_permission(acl_perm, group.read);
2661 var acl_perm = acl_group.write || (acl_group.write = { });
2662 this._acl_merge_permission(acl_perm, group.write);
2667 _acl_merge_tree: function(acl_tree, tree)
2669 if ($.isPlainObject(tree))
2671 for (var group_name in tree)
2673 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2674 this._acl_merge_group(acl_group, tree[group_name]);
2679 listAvailableACLs: _luci2.rpc.declare({
2682 expect: { acls: [ ] },
2683 filter: function(trees) {
2685 for (var i = 0; i < trees.length; i++)
2686 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2691 renderMainMenu: _luci2.rpc.declare({
2694 expect: { menu: { } },
2695 filter: function(entries) {
2696 _luci2.globals.mainMenu = new _luci2.ui.menu();
2697 _luci2.globals.mainMenu.entries(entries);
2701 .append(_luci2.globals.mainMenu.render(0, 1));
2705 renderViewMenu: function()
2709 .append(_luci2.globals.mainMenu.render(2, 900));
2712 renderView: function()
2714 var node = arguments[0];
2715 var name = node.view.split(/\//).join('.');
2718 for (var i = 1; i < arguments.length; i++)
2719 args.push(arguments[i]);
2721 if (_luci2.globals.currentView)
2722 _luci2.globals.currentView.finish();
2724 _luci2.ui.renderViewMenu();
2727 _luci2._views = { };
2729 _luci2.setHash('view', node.view);
2731 if (_luci2._views[name] instanceof _luci2.ui.view)
2733 _luci2.globals.currentView = _luci2._views[name];
2734 return _luci2._views[name].render.apply(_luci2._views[name], args);
2737 var url = _luci2.globals.resource + '/view/' + name + '.js';
2739 return $.ajax(url, {
2743 }).then(function(data) {
2745 var viewConstructorSource = (
2746 '(function(L, $) { ' +
2748 '})(_luci2, $);\n\n' +
2750 ).format(data, url);
2752 var viewConstructor = eval(viewConstructorSource);
2754 _luci2._views[name] = new viewConstructor({
2756 acls: node.write || { }
2759 _luci2.globals.currentView = _luci2._views[name];
2760 return _luci2._views[name].render.apply(_luci2._views[name], args);
2763 alert('Unable to instantiate view "%s": %s'.format(url, e));
2766 return $.Deferred().resolve();
2770 updateHostname: function()
2772 return _luci2.system.getBoardInfo().then(function(info) {
2774 $('#hostname').text(info.hostname);
2778 updateChanges: function()
2780 return _luci2.uci.changes().then(function(changes) {
2784 for (var config in changes)
2788 for (var i = 0; i < changes[config].length; i++)
2790 var c = changes[config][i];
2799 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2801 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2806 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2808 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2812 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2816 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2820 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2825 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2827 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2832 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2833 n += changes[config].length;
2844 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2845 .click(function(ev) {
2846 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2847 ev.preventDefault();
2857 _luci2.ui.loading(true);
2860 _luci2.ui.updateHostname(),
2861 _luci2.ui.updateChanges(),
2862 _luci2.ui.renderMainMenu()
2864 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2865 _luci2.ui.loading(false);
2870 button: function(label, style, title)
2872 style = style || 'default';
2874 return $('<button />')
2875 .attr('type', 'button')
2876 .attr('title', title ? title : '')
2877 .addClass('btn btn-' + style)
2882 this.ui.AbstractWidget = Class.extend({
2883 i18n: function(text) {
2888 var key = arguments[0];
2891 for (var i = 1; i < arguments.length; i++)
2892 args.push(arguments[i]);
2894 switch (typeof(this.options[key]))
2900 return this.options[key].apply(this, args);
2903 return ''.format.apply('' + this.options[key], args);
2907 toString: function() {
2908 return $('<div />').append(this.render()).html();
2911 insertInto: function(id) {
2912 return $(id).empty().append(this.render());
2915 appendTo: function(id) {
2916 return $(id).append(this.render());
2920 this.ui.view = this.ui.AbstractWidget.extend({
2921 _fetch_template: function()
2923 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2927 success: function(data) {
2928 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2929 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2936 return _luci2.tr(p2);
2939 return _luci2.globals[p2] || '';
2942 return '(?' + match + ')';
2946 $('#maincontent').append(data);
2953 throw "Not implemented";
2958 var container = $('#maincontent');
2963 container.append($('<h2 />').append(this.title));
2965 if (this.description)
2966 container.append($('<p />').append(this.description));
2971 for (var i = 0; i < arguments.length; i++)
2972 args.push(arguments[i]);
2974 return this._fetch_template().then(function() {
2975 return _luci2.deferrable(self.execute.apply(self, args));
2979 repeat: function(func, interval)
2983 if (!self._timeouts)
2984 self._timeouts = [ ];
2986 var index = self._timeouts.length;
2988 if (typeof(interval) != 'number')
2991 var setTimer, runTimer;
2993 setTimer = function() {
2995 self._timeouts[index] = window.setTimeout(runTimer, interval);
2998 runTimer = function() {
2999 _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
3007 if ($.isArray(this._timeouts))
3009 for (var i = 0; i < this._timeouts.length; i++)
3010 window.clearTimeout(this._timeouts[i]);
3012 delete this._timeouts;
3017 this.ui.menu = this.ui.AbstractWidget.extend({
3022 entries: function(entries)
3024 for (var entry in entries)
3026 var path = entry.split(/\//);
3027 var node = this._nodes;
3029 for (i = 0; i < path.length; i++)
3034 if (!node.childs[path[i]])
3035 node.childs[path[i]] = { };
3037 node = node.childs[path[i]];
3040 $.extend(node, entries[entry]);
3044 _indexcmp: function(a, b)
3046 var x = a.index || 0;
3047 var y = b.index || 0;
3051 firstChildView: function(node)
3057 for (var child in (node.childs || { }))
3058 nodes.push(node.childs[child]);
3060 nodes.sort(this._indexcmp);
3062 for (var i = 0; i < nodes.length; i++)
3064 var child = this.firstChildView(nodes[i]);
3067 for (var key in child)
3068 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
3069 node[key] = child[key];
3078 _onclick: function(ev)
3080 _luci2.ui.loading(true);
3081 _luci2.ui.renderView(ev.data).then(function() {
3082 _luci2.ui.loading(false);
3085 ev.preventDefault();
3089 _render: function(childs, level, min, max)
3092 for (var node in childs)
3094 var child = this.firstChildView(childs[node]);
3096 nodes.push(childs[node]);
3099 nodes.sort(this._indexcmp);
3101 var list = $('<ul />');
3104 list.addClass('nav').addClass('navbar-nav');
3105 else if (level == 1)
3106 list.addClass('dropdown-menu').addClass('navbar-inverse');
3108 for (var i = 0; i < nodes.length; i++)
3110 if (!_luci2.globals.defaultNode)
3112 var v = _luci2.getHash('view');
3113 if (!v || v == nodes[i].view)
3114 _luci2.globals.defaultNode = nodes[i];
3117 var item = $('<li />')
3120 .text(_luci2.tr(nodes[i].title)))
3123 if (nodes[i].childs && level < max)
3125 item.addClass('dropdown');
3128 .addClass('dropdown-toggle')
3129 .attr('data-toggle', 'dropdown')
3130 .append('<b class="caret"></b>');
3132 item.append(this._render(nodes[i].childs, level + 1));
3136 item.find('a').click(nodes[i], this._onclick);
3143 render: function(min, max)
3145 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
3146 return this._render(top.childs, 0, min, max);
3149 getNode: function(path, max)
3151 var p = path.split(/\//);
3152 var n = this._nodes;
3154 if (typeof(max) == 'undefined')
3157 for (var i = 0; i < max; i++)
3159 if (!n.childs[p[i]])
3169 this.ui.table = this.ui.AbstractWidget.extend({
3175 row: function(values)
3177 if ($.isArray(values))
3179 this._rows.push(values);
3181 else if ($.isPlainObject(values))
3184 for (var i = 0; i < this.options.columns.length; i++)
3186 var col = this.options.columns[i];
3188 if (typeof col.key == 'string')
3189 v.push(values[col.key]);
3197 rows: function(rows)
3199 for (var i = 0; i < rows.length; i++)
3203 render: function(id)
3205 var fieldset = document.createElement('fieldset');
3206 fieldset.className = 'cbi-section';
3208 if (this.options.caption)
3210 var legend = document.createElement('legend');
3211 $(legend).append(this.options.caption);
3212 fieldset.appendChild(legend);
3215 var table = document.createElement('table');
3216 table.className = 'table table-condensed table-hover';
3218 var has_caption = false;
3219 var has_description = false;
3221 for (var i = 0; i < this.options.columns.length; i++)
3222 if (this.options.columns[i].caption)
3227 else if (this.options.columns[i].description)
3229 has_description = true;
3235 var tr = table.insertRow(-1);
3236 tr.className = 'cbi-section-table-titles';
3238 for (var i = 0; i < this.options.columns.length; i++)
3240 var col = this.options.columns[i];
3241 var th = document.createElement('th');
3242 th.className = 'cbi-section-table-cell';
3247 th.style.width = col.width;
3250 th.style.textAlign = col.align;
3253 $(th).append(col.caption);
3257 if (has_description)
3259 var tr = table.insertRow(-1);
3260 tr.className = 'cbi-section-table-descr';
3262 for (var i = 0; i < this.options.columns.length; i++)
3264 var col = this.options.columns[i];
3265 var th = document.createElement('th');
3266 th.className = 'cbi-section-table-cell';
3271 th.style.width = col.width;
3274 th.style.textAlign = col.align;
3276 if (col.description)
3277 $(th).append(col.description);
3281 if (this._rows.length == 0)
3283 if (this.options.placeholder)
3285 var tr = table.insertRow(-1);
3286 var td = tr.insertCell(-1);
3287 td.className = 'cbi-section-table-cell';
3289 td.colSpan = this.options.columns.length;
3290 $(td).append(this.options.placeholder);
3295 for (var i = 0; i < this._rows.length; i++)
3297 var tr = table.insertRow(-1);
3299 for (var j = 0; j < this.options.columns.length; j++)
3301 var col = this.options.columns[j];
3302 var td = tr.insertCell(-1);
3304 var val = this._rows[i][j];
3306 if (typeof(val) == 'undefined')
3307 val = col.placeholder;
3309 if (typeof(val) == 'undefined')
3313 td.style.width = col.width;
3316 td.style.textAlign = col.align;
3318 if (typeof col.format == 'string')
3319 $(td).append(col.format.format(val));
3320 else if (typeof col.format == 'function')
3321 $(td).append(col.format(val, i));
3329 fieldset.appendChild(table);
3335 this.ui.progress = this.ui.AbstractWidget.extend({
3338 var vn = parseInt(this.options.value) || 0;
3339 var mn = parseInt(this.options.max) || 100;
3340 var pc = Math.floor((100 / mn) * vn);
3344 if (typeof(this.options.format) == 'string')
3345 text = this.options.format.format(this.options.value, this.options.max, pc);
3346 else if (typeof(this.options.format) == 'function')
3347 text = this.options.format(pc);
3349 text = '%.2f%%'.format(pc);
3352 .addClass('progress')
3353 .append($('<div />')
3354 .addClass('progress-bar')
3355 .addClass('progress-bar-info')
3356 .css('width', pc + '%'))
3357 .append($('<small />')
3362 this.ui.devicebadge = this.ui.AbstractWidget.extend({
3365 var l2dev = this.options.l2_device || this.options.device;
3366 var l3dev = this.options.l3_device;
3367 var dev = l3dev || l2dev || '?';
3369 var span = document.createElement('span');
3370 span.className = 'badge';
3372 if (typeof(this.options.signal) == 'number' ||
3373 typeof(this.options.noise) == 'number')
3376 if (typeof(this.options.signal) != 'undefined' &&
3377 typeof(this.options.noise) != 'undefined')
3379 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
3392 span.appendChild(document.createElement('img'));
3393 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
3396 span.title = _luci2.tr('No signal');
3398 span.title = '%s: %d %s / %s: %d %s'.format(
3399 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
3400 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
3405 var type = 'ethernet';
3406 var desc = _luci2.tr('Ethernet device');
3411 desc = _luci2.tr('Tunnel interface');
3413 else if (dev.indexOf('br-') == 0)
3416 desc = _luci2.tr('Bridge');
3418 else if (dev.indexOf('.') > 0)
3421 desc = _luci2.tr('VLAN interface');
3423 else if (dev.indexOf('wlan') == 0 ||
3424 dev.indexOf('ath') == 0 ||
3425 dev.indexOf('wl') == 0)
3428 desc = _luci2.tr('Wireless Network');
3431 span.appendChild(document.createElement('img'));
3432 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
3436 $(span).append(' ');
3437 $(span).append(dev);
3443 var type = function(f, l)
3453 _luci2.cbi.validation.message = _luci2.tr(msg);
3456 compile: function(code)
3461 var types = _luci2.cbi.validation.types;
3466 for (var i = 0; i < code.length; i++)
3474 switch (code.charCodeAt(i))
3486 var label = code.substring(pos, i);
3487 label = label.replace(/\\(.)/g, '$1');
3488 label = label.replace(/^[ \t]+/g, '');
3489 label = label.replace(/[ \t]+$/g, '');
3491 if (label && !isNaN(label))
3493 stack.push(parseFloat(label));
3495 else if (label.match(/^(['"]).*\1$/))
3497 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
3499 else if (typeof types[label] == 'function')
3501 stack.push(types[label]);
3506 throw "Syntax error, unhandled token '"+label+"'";
3511 depth += (code.charCodeAt(i) == 40);
3517 if (typeof stack[stack.length-2] != 'function')
3518 throw "Syntax error, argument list follows non-function";
3520 stack[stack.length-1] =
3521 _luci2.cbi.validation.compile(code.substring(pos, i));
3534 var validation = this.cbi.validation;
3536 validation.types = {
3537 'integer': function()
3539 if (this.match(/^-?[0-9]+$/) != null)
3542 validation.i18n('Must be a valid integer');
3546 'uinteger': function()
3548 if (validation.types['integer'].apply(this) && (this >= 0))
3551 validation.i18n('Must be a positive integer');
3557 if (!isNaN(parseFloat(this)))
3560 validation.i18n('Must be a valid number');
3564 'ufloat': function()
3566 if (validation.types['float'].apply(this) && (this >= 0))
3569 validation.i18n('Must be a positive number');
3573 'ipaddr': function()
3575 if (validation.types['ip4addr'].apply(this) ||
3576 validation.types['ip6addr'].apply(this))
3579 validation.i18n('Must be a valid IP address');
3583 'ip4addr': function()
3585 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
3587 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
3588 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
3589 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
3590 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
3591 ((RegExp.$6.indexOf('.') < 0)
3592 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
3593 : (validation.types['ip4addr'].apply(RegExp.$6))))
3597 validation.i18n('Must be a valid IPv4 address');
3601 'ip6addr': function()
3603 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
3605 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
3607 var addr = RegExp.$1;
3614 if (addr.indexOf('.') > 0)
3616 var off = addr.lastIndexOf(':');
3618 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
3620 validation.i18n('Must be a valid IPv6 address');
3624 addr = addr.substr(0, off) + ':0:0';
3627 if (addr.indexOf('::') >= 0)
3632 for (var i = 1; i < (addr.length-1); i++)
3633 if (addr.charAt(i) == ':')
3638 validation.i18n('Must be a valid IPv6 address');
3642 for (var i = 0; i < (7 - colons); i++)
3645 if (addr.match(/^(.*?)::(.*?)$/))
3646 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
3647 (RegExp.$2 ? ':' + RegExp.$2 : '');
3650 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
3653 validation.i18n('Must be a valid IPv6 address');
3658 validation.i18n('Must be a valid IPv6 address');
3664 if (validation.types['integer'].apply(this) &&
3665 (this >= 0) && (this <= 65535))
3668 validation.i18n('Must be a valid port number');
3672 'portrange': function()
3674 if (this.match(/^(\d+)-(\d+)$/))
3679 if (validation.types['port'].apply(p1) &&
3680 validation.types['port'].apply(p2) &&
3681 (parseInt(p1) <= parseInt(p2)))
3684 else if (validation.types['port'].apply(this))
3689 validation.i18n('Must be a valid port range');
3693 'macaddr': function()
3695 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
3698 validation.i18n('Must be a valid MAC address');
3704 if (validation.types['hostname'].apply(this) ||
3705 validation.types['ipaddr'].apply(this))
3708 validation.i18n('Must be a valid hostname or IP address');
3712 'hostname': function()
3714 if ((this.length <= 253) &&
3715 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3716 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3717 this.match(/[^0-9.]/)))))
3720 validation.i18n('Must be a valid host name');
3724 'network': function()
3726 if (validation.types['uciname'].apply(this) ||
3727 validation.types['host'].apply(this))
3730 validation.i18n('Must be a valid network name');
3734 'wpakey': function()
3738 if ((v.length == 64)
3739 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
3740 : ((v.length >= 8) && (v.length <= 63)))
3743 validation.i18n('Must be a valid WPA key');
3747 'wepkey': function()
3751 if (v.substr(0,2) == 's:')
3754 if (((v.length == 10) || (v.length == 26))
3755 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
3756 : ((v.length == 5) || (v.length == 13)))
3759 validation.i18n('Must be a valid WEP key');
3763 'uciname': function()
3765 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3768 validation.i18n('Must be a valid UCI identifier');
3772 'range': function(min, max)
3774 var val = parseFloat(this);
3776 if (validation.types['integer'].apply(this) &&
3777 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
3780 validation.i18n('Must be a number between %d and %d');
3784 'min': function(min)
3786 var val = parseFloat(this);
3788 if (validation.types['integer'].apply(this) &&
3789 !isNaN(min) && !isNaN(val) && (val >= min))
3792 validation.i18n('Must be a number greater or equal to %d');
3796 'max': function(max)
3798 var val = parseFloat(this);
3800 if (validation.types['integer'].apply(this) &&
3801 !isNaN(max) && !isNaN(val) && (val <= max))
3804 validation.i18n('Must be a number lower or equal to %d');
3808 'rangelength': function(min, max)
3810 var val = '' + this;
3812 if (!isNaN(min) && !isNaN(max) &&
3813 (val.length >= min) && (val.length <= max))
3816 validation.i18n('Must be between %d and %d characters');
3820 'minlength': function(min)
3822 var val = '' + this;
3824 if (!isNaN(min) && (val.length >= min))
3827 validation.i18n('Must be at least %d characters');
3831 'maxlength': function(max)
3833 var val = '' + this;
3835 if (!isNaN(max) && (val.length <= max))
3838 validation.i18n('Must be at most %d characters');
3846 for (var i = 0; i < arguments.length; i += 2)
3848 delete validation.message;
3850 if (typeof(arguments[i]) != 'function')
3852 if (arguments[i] == this)
3856 else if (arguments[i].apply(this, arguments[i+1]))
3861 if (validation.message)
3862 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3865 validation.message = msgs.join( _luci2.tr(' - or - '));
3873 for (var i = 0; i < arguments.length; i += 2)
3875 delete validation.message;
3877 if (typeof arguments[i] != 'function')
3879 if (arguments[i] != this)
3883 else if (!arguments[i].apply(this, arguments[i+1]))
3888 if (validation.message)
3889 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3892 validation.message = msgs.join(', ');
3898 return validation.types['or'].apply(
3899 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
3902 'list': function(subvalidator, subargs)
3904 if (typeof subvalidator != 'function')
3907 var tokens = this.match(/[^ \t]+/g);
3908 for (var i = 0; i < tokens.length; i++)
3909 if (!subvalidator.apply(tokens[i], subargs))
3915 'phonedigit': function()
3917 if (this.match(/^[0-9\*#!\.]+$/) != null)
3920 validation.i18n('Must be a valid phone number digit');
3924 'string': function()
3931 this.cbi.AbstractValue = this.ui.AbstractWidget.extend({
3932 init: function(name, options)
3935 this.instance = { };
3936 this.dependencies = [ ];
3937 this.rdependency = { };
3939 this.options = _luci2.defaults(options, {
3949 return this.section.id('field', sid || '__unknown__', this.name);
3952 render: function(sid, condensed)
3954 var i = this.instance[sid] = { };
3956 i.top = $('<div />');
3960 i.top.addClass('form-group');
3962 if (typeof(this.options.caption) == 'string')
3964 .addClass('col-lg-2 control-label')
3965 .attr('for', this.id(sid))
3966 .text(this.options.caption)
3970 i.error = $('<div />')
3972 .addClass('label label-danger');
3974 i.widget = $('<div />')
3976 .append(this.widget(sid))
3982 i.widget.addClass('col-lg-5');
3985 .addClass('col-lg-5')
3986 .text((typeof(this.options.description) == 'string') ? this.options.description : '')
3993 ucipath: function(sid)
3996 config: (this.options.uci_package || this.map.uci_package),
3997 section: (this.options.uci_section || sid),
3998 option: (this.options.uci_option || this.name)
4002 ucivalue: function(sid)
4004 var uci = this.ucipath(sid);
4005 var val = this.map.get(uci.config, uci.section, uci.option);
4007 if (typeof(val) == 'undefined')
4008 return this.options.initial;
4013 formvalue: function(sid)
4015 var v = $('#' + this.id(sid)).val();
4016 return (v === '') ? undefined : v;
4019 textvalue: function(sid)
4021 var v = this.formvalue(sid);
4023 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
4024 v = this.ucivalue(sid);
4026 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
4027 v = this.options.placeholder;
4029 if (typeof(v) == 'undefined' || v === '')
4032 if (typeof(v) == 'string' && $.isArray(this.choices))
4034 for (var i = 0; i < this.choices.length; i++)
4035 if (v === this.choices[i][0])
4036 return this.choices[i][1];
4038 else if (v === true)
4039 return _luci2.tr('yes');
4040 else if (v === false)
4041 return _luci2.tr('no');
4042 else if ($.isArray(v))
4043 return v.join(', ');
4048 changed: function(sid)
4050 var a = this.ucivalue(sid);
4051 var b = this.formvalue(sid);
4053 if (typeof(a) != typeof(b))
4056 if (typeof(a) == 'object')
4058 if (a.length != b.length)
4061 for (var i = 0; i < a.length; i++)
4073 var uci = this.ucipath(sid);
4075 if (this.instance[sid].disabled)
4077 if (!this.options.keep)
4078 return this.map.set(uci.config, uci.section, uci.option, undefined);
4083 var chg = this.changed(sid);
4084 var val = this.formvalue(sid);
4087 this.map.set(uci.config, uci.section, uci.option, val);
4092 _ev_validate: function(ev)
4096 var val = d.elem.val();
4097 var vstack = d.vstack;
4099 if (vstack && typeof(vstack[0]) == 'function')
4101 delete validation.message;
4103 if ((val.length == 0 && !d.opt))
4105 d.elem.parents('div.form-group, td').first().addClass('luci2-form-error');
4106 d.elem.parents('div.input-group, div.form-group, td').first().addClass('has-error');
4108 d.inst.error.text(_luci2.tr('Field must not be empty')).show();
4111 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
4113 d.elem.parents('div.form-group, td').first().addClass('luci2-form-error');
4114 d.elem.parents('div.input-group, div.form-group, td').first().addClass('has-error');
4116 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1])).show();
4121 d.elem.parents('div.form-group, td').first().removeClass('luci2-form-error');
4122 d.elem.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
4124 if (d.multi && d.inst.widget && d.inst.widget.find('input.error, select.error').length > 0)
4127 d.inst.error.text('').hide();
4132 for (var field in d.self.rdependency)
4133 d.self.rdependency[field].toggle(d.sid);
4138 validator: function(sid, elem, multi)
4140 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
4144 if (typeof(this.options.datatype) == 'string')
4147 vstack = _luci2.cbi.validation.compile(this.options.datatype);
4150 else if (typeof(this.options.datatype) == 'function')
4152 var vfunc = this.options.datatype;
4153 vstack = [ function(elem) {
4154 var rv = vfunc(this, elem);
4156 validation.message = rv;
4157 return (rv === true);
4167 inst: this.instance[sid],
4168 opt: this.options.optional
4171 if (elem.prop('tagName') == 'SELECT')
4173 elem.change(evdata, this._ev_validate);
4175 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
4177 elem.click(evdata, this._ev_validate);
4178 elem.blur(evdata, this._ev_validate);
4182 elem.keyup(evdata, this._ev_validate);
4183 elem.blur(evdata, this._ev_validate);
4186 elem.attr('cbi-validate', true).on('validate', evdata, this._ev_validate);
4191 validate: function(sid)
4193 var i = this.instance[sid];
4195 i.widget.find('[cbi-validate]').trigger('validate');
4197 return (i.disabled || i.error.text() == '');
4200 depends: function(d, v)
4207 for (var i = 0; i < d.length; i++)
4209 if (typeof(d[i]) == 'string')
4211 else if (d[i] instanceof _luci2.cbi.AbstractValue)
4212 dep[d[i].name] = true;
4215 else if (d instanceof _luci2.cbi.AbstractValue)
4218 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
4220 else if (typeof(d) == 'object')
4224 else if (typeof(d) == 'string')
4227 dep[d] = (typeof(v) == 'undefined') ? true : v;
4230 if (!dep || $.isEmptyObject(dep))
4233 for (var field in dep)
4235 var f = this.section.fields[field];
4237 f.rdependency[this.name] = this;
4242 if ($.isEmptyObject(dep))
4245 this.dependencies.push(dep);
4250 toggle: function(sid)
4252 var d = this.dependencies;
4253 var i = this.instance[sid];
4258 for (var n = 0; n < d.length; n++)
4262 for (var field in d[n])
4264 var val = this.section.fields[field].formvalue(sid);
4265 var cmp = d[n][field];
4267 if (typeof(cmp) == 'boolean')
4269 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
4275 else if (typeof(cmp) == 'string')
4283 else if (typeof(cmp) == 'function')
4291 else if (cmp instanceof RegExp)
4316 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
4323 this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
4324 widget: function(sid)
4326 var o = this.options;
4328 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
4329 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
4331 var i = $('<input />')
4332 .attr('id', this.id(sid))
4333 .attr('type', 'checkbox')
4334 .prop('checked', this.ucivalue(sid));
4337 .addClass('checkbox')
4338 .append(this.validator(sid, i));
4341 ucivalue: function(sid)
4343 var v = this.callSuper('ucivalue', sid);
4345 if (typeof(v) == 'boolean')
4348 return (v == this.options.enabled);
4351 formvalue: function(sid)
4353 var v = $('#' + this.id(sid)).prop('checked');
4355 if (typeof(v) == 'undefined')
4356 return !!this.options.initial;
4363 var uci = this.ucipath(sid);
4365 if (this.instance[sid].disabled)
4367 if (!this.options.keep)
4368 return this.map.set(uci.config, uci.section, uci.option, undefined);
4373 var chg = this.changed(sid);
4374 var val = this.formvalue(sid);
4378 if (this.options.optional && val == this.options.initial)
4379 this.map.set(uci.config, uci.section, uci.option, undefined);
4381 this.map.set(uci.config, uci.section, uci.option, val ? this.options.enabled : this.options.disabled);
4388 this.cbi.InputValue = this.cbi.AbstractValue.extend({
4389 widget: function(sid)
4391 var i = $('<input />')
4392 .addClass('form-control')
4393 .attr('id', this.id(sid))
4394 .attr('type', 'text')
4395 .attr('placeholder', this.options.placeholder)
4396 .val(this.ucivalue(sid));
4398 return this.validator(sid, i);
4402 this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
4403 widget: function(sid)
4405 var i = $('<input />')
4406 .addClass('form-control')
4407 .attr('id', this.id(sid))
4408 .attr('type', 'password')
4409 .attr('placeholder', this.options.placeholder)
4410 .val(this.ucivalue(sid));
4412 var t = $('<span />')
4413 .addClass('input-group-btn')
4414 .append(_luci2.ui.button(_luci2.tr('Reveal'), 'default')
4415 .click(function(ev) {
4417 var i = b.parent().prev();
4418 var t = i.attr('type');
4419 b.text(t == 'password' ? _luci2.tr('Hide') : _luci2.tr('Reveal'));
4420 i.attr('type', (t == 'password') ? 'text' : 'password');
4424 this.validator(sid, i);
4427 .addClass('input-group')
4433 this.cbi.ListValue = this.cbi.AbstractValue.extend({
4434 widget: function(sid)
4436 var s = $('<select />')
4437 .addClass('form-control');
4439 if (this.options.optional)
4442 .text(_luci2.tr('-- Please choose --'))
4446 for (var i = 0; i < this.choices.length; i++)
4448 .attr('value', this.choices[i][0])
4449 .text(this.choices[i][1])
4452 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
4454 return this.validator(sid, s);
4457 value: function(k, v)
4462 this.choices.push([k, v || k]);
4467 this.cbi.MultiValue = this.cbi.ListValue.extend({
4468 widget: function(sid)
4470 var v = this.ucivalue(sid);
4471 var t = $('<div />').attr('id', this.id(sid));
4474 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4477 for (var i = 0; i < v.length; i++)
4481 for (var i = 0; i < this.choices.length; i++)
4484 .addClass('checkbox')
4485 .append($('<input />')
4486 .attr('type', 'checkbox')
4487 .attr('value', this.choices[i][0])
4488 .prop('checked', s[this.choices[i][0]]))
4489 .append(this.choices[i][1])
4496 formvalue: function(sid)
4499 var fields = $('#' + this.id(sid) + ' > label > input');
4501 for (var i = 0; i < fields.length; i++)
4502 if (fields[i].checked)
4503 rv.push(fields[i].getAttribute('value'));
4508 textvalue: function(sid)
4510 var v = this.formvalue(sid);
4514 for (var i = 0; i < this.choices.length; i++)
4515 c[this.choices[i][0]] = this.choices[i][1];
4519 for (var i = 0; i < v.length; i++)
4520 t.push(c[v[i]] || v[i]);
4522 return t.join(', ');
4526 this.cbi.ComboBox = this.cbi.AbstractValue.extend({
4527 _change: function(ev)
4530 var self = ev.data.self;
4532 if (s.selectedIndex == (s.options.length - 1))
4534 ev.data.select.hide();
4535 ev.data.input.show().focus();
4537 var v = ev.data.input.val();
4538 ev.data.input.val(' ');
4539 ev.data.input.val(v);
4541 else if (self.options.optional && s.selectedIndex == 0)
4543 ev.data.input.val('');
4547 ev.data.input.val(ev.data.select.val());
4554 var val = this.value;
4555 var self = ev.data.self;
4557 ev.data.select.empty();
4559 if (self.options.optional)
4562 .text(_luci2.tr('-- please choose --'))
4563 .appendTo(ev.data.select);
4566 for (var i = 0; i < self.choices.length; i++)
4568 if (self.choices[i][0] == val)
4572 .attr('value', self.choices[i][0])
4573 .text(self.choices[i][1])
4574 .appendTo(ev.data.select);
4577 if (!seen && val != '')
4581 .appendTo(ev.data.select);
4585 .text(_luci2.tr('-- custom --'))
4586 .appendTo(ev.data.select);
4588 ev.data.input.hide();
4589 ev.data.select.val(val).show().focus();
4592 _enter: function(ev)
4597 ev.preventDefault();
4598 ev.data.self._blur(ev);
4602 widget: function(sid)
4604 var d = $('<div />')
4605 .attr('id', this.id(sid));
4607 var t = $('<input />')
4608 .attr('type', 'text')
4612 var s = $('<select />')
4617 input: this.validator(sid, t),
4618 select: this.validator(sid, s)
4621 s.change(evdata, this._change);
4622 t.blur(evdata, this._blur);
4623 t.keydown(evdata, this._enter);
4625 t.val(this.ucivalue(sid));
4631 value: function(k, v)
4636 this.choices.push([k, v || k]);
4640 formvalue: function(sid)
4642 var v = $('#' + this.id(sid)).children('input').val();
4643 return (v == '') ? undefined : v;
4647 this.cbi.DynamicList = this.cbi.ComboBox.extend({
4648 _redraw: function(focus, add, del, s)
4650 var v = s.values || [ ];
4653 $(s.parent).children('div.input-group').children('input').each(function(i) {
4655 v.push(this.value || '');
4658 $(s.parent).empty();
4663 v.splice(focus, 0, '');
4665 else if (v.length == 0)
4671 for (var i = 0; i < v.length; i++)
4678 remove: ((i+1) < v.length)
4683 btn = _luci2.ui.button('–', 'danger').click(evdata, this._btnclick);
4685 btn = _luci2.ui.button('+', 'success').click(evdata, this._btnclick);
4689 var txt = $('<input />')
4690 .addClass('form-control')
4691 .attr('type', 'text')
4694 var sel = $('<select />')
4695 .addClass('form-control');
4698 .addClass('input-group')
4701 .append($('<span />')
4702 .addClass('input-group-btn')
4704 .appendTo(s.parent);
4706 evdata.input = this.validator(s.sid, txt, true);
4707 evdata.select = this.validator(s.sid, sel, true);
4709 sel.change(evdata, this._change);
4710 txt.blur(evdata, this._blur);
4711 txt.keydown(evdata, this._keydown);
4716 if (i == focus || -(i+1) == focus)
4723 var f = $('<input />')
4724 .attr('type', 'text')
4726 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
4727 .addClass('form-control')
4728 .keydown(evdata, this._keydown)
4729 .keypress(evdata, this._keypress)
4733 .addClass('input-group')
4735 .append($('<span />')
4736 .addClass('input-group-btn')
4738 .appendTo(s.parent);
4744 else if (-(i+1) == focus)
4748 /* force cursor to end */
4754 evdata.input = this.validator(s.sid, f, true);
4765 _keypress: function(ev)
4769 /* backspace, delete */
4772 if (ev.data.input.val() == '')
4774 ev.preventDefault();
4780 /* enter, arrow up, arrow down */
4784 ev.preventDefault();
4791 _keydown: function(ev)
4793 var input = ev.data.input;
4797 /* backspace, delete */
4800 if (input.val().length == 0)
4802 ev.preventDefault();
4804 var index = ev.data.index;
4810 ev.data.self._redraw(focus, -1, index, ev.data);
4818 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4823 var prev = input.parent().prevAll('div.input-group:first').children('input');
4824 if (prev.is(':visible'))
4827 prev.next('select').focus();
4832 var next = input.parent().nextAll('div.input-group:first').children('input');
4833 if (next.is(':visible'))
4836 next.next('select').focus();
4843 _btnclick: function(ev)
4845 if (!this.getAttribute('disabled'))
4849 var index = ev.data.index;
4850 ev.data.self._redraw(-index, -1, index, ev.data);
4854 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4861 widget: function(sid)
4863 this.options.optional = true;
4865 var v = this.ucivalue(sid);
4868 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4870 var d = $('<div />')
4871 .attr('id', this.id(sid))
4872 .addClass('cbi-input-dynlist');
4874 this._redraw(NaN, -1, -1, {
4884 ucivalue: function(sid)
4886 var v = this.callSuper('ucivalue', sid);
4889 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4894 formvalue: function(sid)
4897 var fields = $('#' + this.id(sid) + ' > input');
4899 for (var i = 0; i < fields.length; i++)
4900 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
4901 rv.push(fields[i].value);
4907 this.cbi.DummyValue = this.cbi.AbstractValue.extend({
4908 widget: function(sid)
4911 .addClass('form-control-static')
4912 .attr('id', this.id(sid))
4913 .html(this.ucivalue(sid));
4916 formvalue: function(sid)
4918 return this.ucivalue(sid);
4922 this.cbi.NetworkList = this.cbi.AbstractValue.extend({
4927 if (!self.interfaces)
4929 self.interfaces = [ ];
4930 return _luci2.network.getNetworkStatus().then(function(ifaces) {
4931 self.interfaces = ifaces;
4939 _device_icon: function(dev)
4941 var type = 'ethernet';
4942 var desc = _luci2.tr('Ethernet device');
4944 if (dev.type == 'IP tunnel')
4947 desc = _luci2.tr('Tunnel interface');
4949 else if (dev['bridge-members'])
4952 desc = _luci2.tr('Bridge');
4954 else if (dev.wireless)
4957 desc = _luci2.tr('Wireless Network');
4959 else if (dev.device.indexOf('.') > 0)
4962 desc = _luci2.tr('VLAN interface');
4966 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
4967 .attr('title', '%s (%s)'.format(desc, dev.device));
4970 widget: function(sid)
4972 var id = this.id(sid);
4973 var ul = $('<ul />')
4975 .addClass('list-unstyled');
4977 var itype = this.options.multiple ? 'checkbox' : 'radio';
4978 var value = this.ucivalue(sid);
4981 if (!this.options.multiple)
4982 check[value] = true;
4984 for (var i = 0; i < value.length; i++)
4985 check[value[i]] = true;
4987 if (this.interfaces)
4989 for (var i = 0; i < this.interfaces.length; i++)
4991 var iface = this.interfaces[i];
4992 var badge = $('<span />')
4994 .text('%s: '.format(iface['interface']));
4996 if (iface.device && iface.device.subdevices)
4997 for (var j = 0; j < iface.device.subdevices.length; j++)
4998 badge.append(this._device_icon(iface.device.subdevices[j]));
4999 else if (iface.device)
5000 badge.append(this._device_icon(iface.device));
5002 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
5005 .append($('<label />')
5006 .addClass(itype + ' inline')
5007 .append($('<input />')
5008 .attr('name', itype + id)
5009 .attr('type', itype)
5010 .attr('value', iface['interface'])
5011 .prop('checked', !!check[iface['interface']]))
5017 if (!this.options.multiple)
5020 .append($('<label />')
5021 .addClass(itype + ' inline text-muted')
5022 .append($('<input />')
5023 .attr('name', itype + id)
5024 .attr('type', itype)
5026 .prop('checked', !value))
5027 .append(_luci2.tr('unspecified')))
5034 ucivalue: function(sid)
5036 var v = this.callSuper('ucivalue', sid);
5038 if (!this.options.multiple)
5044 else if (typeof(v) == 'string')
5047 return v ? v[0] : undefined;
5054 if (typeof(v) == 'string')
5055 v = v.match(/\S+/g);
5061 formvalue: function(sid)
5063 var inputs = $('#' + this.id(sid) + ' input');
5065 if (!this.options.multiple)
5067 for (var i = 0; i < inputs.length; i++)
5068 if (inputs[i].checked && inputs[i].value !== '')
5069 return inputs[i].value;
5076 for (var i = 0; i < inputs.length; i++)
5077 if (inputs[i].checked)
5078 rv.push(inputs[i].value);
5080 return rv.length ? rv : undefined;
5085 this.cbi.AbstractSection = this.ui.AbstractWidget.extend({
5088 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
5090 for (var i = 1; i < arguments.length; i++)
5091 s.push(arguments[i].replace(/\./g, '_'));
5096 option: function(widget, name, options)
5098 if (this.tabs.length == 0)
5099 this.tab({ id: '__default__', selected: true });
5101 return this.taboption('__default__', widget, name, options);
5104 tab: function(options)
5106 if (options.selected)
5107 this.tabs.selected = this.tabs.length;
5111 caption: options.caption,
5112 description: options.description,
5118 taboption: function(tabid, widget, name, options)
5121 for (var i = 0; i < this.tabs.length; i++)
5123 if (this.tabs[i].id == tabid)
5131 throw 'Cannot append to unknown tab ' + tabid;
5133 var w = widget ? new widget(name, options) : null;
5135 if (!(w instanceof _luci2.cbi.AbstractValue))
5136 throw 'Widget must be an instance of AbstractValue';
5141 this.fields[name] = w;
5147 ucipackages: function(pkg)
5149 for (var i = 0; i < this.tabs.length; i++)
5150 for (var j = 0; j < this.tabs[i].fields.length; j++)
5151 if (this.tabs[i].fields[j].options.uci_package)
5152 pkg[this.tabs[i].fields[j].options.uci_package] = true;
5155 formvalue: function()
5159 this.sections(function(s) {
5160 var sid = s['.name'];
5161 var sv = rv[sid] || (rv[sid] = { });
5163 for (var i = 0; i < this.tabs.length; i++)
5164 for (var j = 0; j < this.tabs[i].fields.length; j++)
5166 var val = this.tabs[i].fields[j].formvalue(sid);
5167 sv[this.tabs[i].fields[j].name] = val;
5174 validate_section: function(sid)
5176 var inst = this.instance[sid];
5179 var badge = $('#' + this.id('teaser', sid)).children('span:first');
5181 for (var i = 0; i < this.tabs.length; i++)
5184 var stbadge = $('#' + this.id('nodetab', sid, this.tabs[i].id)).children('span:first');
5186 for (var j = 0; j < this.tabs[i].fields.length; j++)
5187 if (!this.tabs[i].fields[j].validate(sid))
5193 .attr('title', _luci2.trp('1 Error', '%d Errors', inval).format(inval));
5203 .attr('title', _luci2.trp('1 Error', '%d Errors', invals).format(invals));
5210 validate: function()
5212 this.error_count = 0;
5214 var as = this.sections();
5216 for (var i = 0; i < as.length; i++)
5218 var invals = this.validate_section(as[i]['.name']);
5221 this.error_count += invals;
5224 var badge = $('#' + this.id('sectiontab')).children('span:first');
5226 if (this.error_count > 0)
5228 .text(this.error_count)
5229 .attr('title', _luci2.trp('1 Error', '%d Errors', this.error_count).format(this.error_count));
5233 return (this.error_count == 0);
5237 this.cbi.TypedSection = this.cbi.AbstractSection.extend({
5238 init: function(uci_type, options)
5240 this.uci_type = uci_type;
5241 this.options = options;
5244 this.error_count = 0;
5245 this.active_panel = 0;
5246 this.active_tab = { };
5249 filter: function(section)
5254 sections: function(cb)
5256 var s1 = this.map.ucisections(this.map.uci_package);
5259 for (var i = 0; i < s1.length; i++)
5260 if (s1[i]['.type'] == this.uci_type)
5261 if (this.filter(s1[i]))
5264 if (typeof(cb) == 'function')
5265 for (var i = 0; i < s2.length; i++)
5266 cb.apply(this, [ s2[i] ]);
5273 this.map.add(this.map.uci_package, this.uci_type, name);
5276 remove: function(sid)
5278 this.map.remove(this.map.uci_package, sid);
5281 _ev_add: function(ev)
5284 var name = undefined;
5285 var self = ev.data.self;
5287 if (addb.prev().prop('nodeName') == 'INPUT')
5288 name = addb.prev().val();
5290 if (addb.prop('disabled') || name === '')
5293 _luci2.ui.saveScrollTop();
5295 self.active_panel = -1;
5300 _luci2.ui.restoreScrollTop();
5303 _ev_remove: function(ev)
5305 var self = ev.data.self;
5306 var sid = ev.data.sid;
5308 _luci2.ui.saveScrollTop();
5314 _luci2.ui.restoreScrollTop();
5316 ev.stopPropagation();
5319 _ev_sid: function(ev)
5321 var self = ev.data.self;
5323 var addb = text.next();
5324 var errt = addb.next();
5325 var name = text.val();
5328 if (!/^[a-zA-Z0-9_]*$/.test(name))
5330 errt.text(_luci2.tr('Invalid section name')).show();
5331 text.addClass('error');
5332 addb.prop('disabled', true);
5336 for (var sid in self.map.uci.values[self.map.uci_package])
5343 for (var sid in self.map.uci.creates[self.map.uci_package])
5352 errt.text(_luci2.tr('Name already used')).show();
5353 text.addClass('error');
5354 addb.prop('disabled', true);
5358 errt.text('').hide();
5359 text.removeClass('error');
5360 addb.prop('disabled', false);
5364 _ev_tab: function(ev)
5366 var self = ev.data.self;
5367 var sid = ev.data.sid;
5370 self.active_tab[sid] = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
5373 _ev_panel_collapse: function(ev)
5375 var self = ev.data.self;
5377 var this_panel = $(ev.target);
5378 var this_toggle = this_panel.prevAll('[data-toggle="collapse"]:first');
5380 var prev_toggle = $($(ev.delegateTarget).find('[data-toggle="collapse"]:eq(%d)'.format(self.active_panel)));
5381 var prev_panel = $(prev_toggle.attr('data-target'));
5385 .addClass('collapse');
5387 prev_toggle.find('.luci2-section-teaser')
5389 .children('span:last')
5391 .append(self.teaser(prev_panel.attr('data-luci2-sid')));
5393 this_toggle.find('.luci2-section-teaser')
5396 self.active_panel = parseInt(this_panel.attr('data-luci2-panel-index'));
5400 _ev_panel_open: function(ev)
5402 var self = ev.data.self;
5403 var panel = $($(this).attr('data-target'));
5404 var index = parseInt(panel.attr('data-luci2-panel-index'));
5406 if (index == self.active_panel)
5407 ev.stopPropagation();
5410 _ev_sort: function(ev)
5412 var self = ev.data.self;
5413 var cur_idx = ev.data.index;
5414 var new_idx = cur_idx + (ev.data.up ? -1 : 1);
5415 var s = self.sections();
5417 if (new_idx >= 0 && new_idx < s.length)
5419 var tmp = s[cur_idx]['.index'];
5421 s[cur_idx]['.index'] = s[new_idx]['.index'];
5422 s[new_idx]['.index'] = tmp;
5424 if (self.active_panel == cur_idx)
5425 self.active_panel = new_idx;
5426 else if (self.active_panel == new_idx)
5427 self.active_panel = cur_idx;
5429 self.map.uci.reorder = true;
5435 ev.stopPropagation();
5438 teaser: function(sid)
5440 var tf = this.teaser_fields;
5444 tf = this.teaser_fields = [ ];
5446 if ($.isArray(this.options.teasers))
5448 for (var i = 0; i < this.options.teasers.length; i++)
5450 var f = this.options.teasers[i];
5451 if (f instanceof _luci2.cbi.AbstractValue)
5453 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
5454 tf.push(this.fields[f]);
5459 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
5460 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
5461 tf.push(this.tabs[i].fields[j]);
5467 for (var i = 0; i < tf.length; i++)
5469 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
5472 var n = tf[i].options.caption || tf[i].name;
5473 var v = tf[i].textvalue(sid);
5475 if (typeof(v) == 'undefined')
5478 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
5484 _render_add: function()
5486 if (!this.options.addremove)
5489 var text = _luci2.tr('Add section');
5490 var ttip = _luci2.tr('Create new section...');
5492 if ($.isArray(this.options.add_caption))
5493 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
5494 else if (typeof(this.options.add_caption) == 'string')
5495 text = this.options.add_caption, ttip = '';
5497 var add = $('<div />');
5499 if (this.options.anonymous === false)
5502 .addClass('cbi-input-text')
5503 .attr('type', 'text')
5504 .attr('placeholder', ttip)
5505 .blur({ self: this }, this._ev_sid)
5506 .keyup({ self: this }, this._ev_sid)
5510 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
5511 .attr('title', text)
5512 .addClass('cbi-button')
5513 .click({ self: this }, this._ev_add)
5517 .addClass('cbi-value-error')
5523 _luci2.ui.button(text, 'success', ttip)
5524 .click({ self: this }, this._ev_add)
5531 _render_remove: function(sid, index)
5533 if (!this.options.addremove)
5536 var text = _luci2.tr('Remove');
5537 var ttip = _luci2.tr('Remove this section');
5539 if ($.isArray(this.options.remove_caption))
5540 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
5541 else if (typeof(this.options.remove_caption) == 'string')
5542 text = this.options.remove_caption, ttip = '';
5544 return _luci2.ui.button(text, 'danger', ttip)
5545 .click({ self: this, sid: sid, index: index }, this._ev_remove);
5548 _render_sort: function(sid, index)
5550 if (!this.options.sortable)
5553 var b1 = _luci2.ui.button('↑', 'info', _luci2.tr('Move up'))
5554 .click({ self: this, index: index, up: true }, this._ev_sort);
5556 var b2 = _luci2.ui.button('↓', 'info', _luci2.tr('Move down'))
5557 .click({ self: this, index: index, up: false }, this._ev_sort);
5562 _render_caption: function()
5565 .addClass('panel-title')
5566 .append(this.label('caption') || this.uci_type);
5569 _render_description: function()
5571 var text = this.label('description');
5575 .addClass('luci2-section-description')
5581 _render_teaser: function(sid, index)
5583 if (this.options.collabsible || this.map.options.collabsible)
5586 .attr('id', this.id('teaser', sid))
5587 .addClass('luci2-section-teaser well well-sm')
5588 .append($('<span />')
5590 .append($('<span />'));
5596 _render_head: function(condensed)
5602 .addClass('panel-heading')
5603 .append(this._render_caption())
5604 .append(this._render_description());
5607 _render_tab_description: function(sid, index, tab_index)
5609 var tab = this.tabs[tab_index];
5611 if (typeof(tab.description) == 'string')
5614 .addClass('cbi-tab-descr')
5615 .text(tab.description);
5621 _render_tab_head: function(sid, index, tab_index)
5623 var tab = this.tabs[tab_index];
5624 var cur = this.active_tab[sid] || 0;
5626 var tabh = $('<li />')
5628 .attr('id', this.id('nodetab', sid, tab.id))
5629 .attr('href', '#' + this.id('node', sid, tab.id))
5630 .attr('data-toggle', 'tab')
5631 .attr('data-luci2-tab-index', tab_index)
5632 .text((tab.caption ? tab.caption.format(tab.id) : tab.id) + ' ')
5633 .append($('<span />')
5635 .on('shown.bs.tab', { self: this, sid: sid }, this._ev_tab));
5637 if (cur == tab_index)
5638 tabh.addClass('active');
5643 _render_tab_body: function(sid, index, tab_index)
5645 var tab = this.tabs[tab_index];
5646 var cur = this.active_tab[sid] || 0;
5648 var tabb = $('<div />')
5649 .addClass('tab-pane')
5650 .attr('id', this.id('node', sid, tab.id))
5651 .attr('data-luci2-tab-index', tab_index)
5652 .append(this._render_tab_description(sid, index, tab_index));
5654 if (cur == tab_index)
5655 tabb.addClass('active');
5657 for (var i = 0; i < tab.fields.length; i++)
5658 tabb.append(tab.fields[i].render(sid));
5663 _render_section_head: function(sid, index)
5665 var head = $('<div />')
5666 .addClass('luci2-section-header')
5667 .append(this._render_teaser(sid, index))
5668 .append($('<div />')
5669 .addClass('btn-group')
5670 .append(this._render_sort(sid, index))
5671 .append(this._render_remove(sid, index)));
5673 if (this.options.collabsible)
5675 head.attr('data-toggle', 'collapse')
5676 .attr('data-parent', this.id('sectiongroup'))
5677 .attr('data-target', '#' + this.id('panel', sid))
5678 .on('click', { self: this }, this._ev_panel_open);
5684 _render_section_body: function(sid, index)
5686 var body = $('<div />')
5687 .attr('id', this.id('panel', sid))
5688 .attr('data-luci2-panel-index', index)
5689 .attr('data-luci2-sid', sid);
5691 if (this.options.collabsible || this.map.options.collabsible)
5693 body.addClass('panel-collapse collapse');
5695 if (index == this.active_panel)
5696 body.addClass('in');
5699 var tab_heads = $('<ul />')
5700 .addClass('nav nav-tabs');
5702 var tab_bodies = $('<div />')
5703 .addClass('form-horizontal tab-content')
5706 for (var j = 0; j < this.tabs.length; j++)
5708 tab_heads.append(this._render_tab_head(sid, index, j));
5709 tab_bodies.append(this._render_tab_body(sid, index, j));
5712 body.append(tab_bodies);
5714 if (this.tabs.length <= 1)
5720 _render_body: function(condensed)
5722 var s = this.sections();
5724 if (this.active_panel < 0)
5725 this.active_panel += s.length;
5726 else if (this.active_panel >= s.length)
5727 this.active_panel = s.length - 1;
5729 var body = $('<ul />')
5730 .addClass('list-group');
5732 if (this.options.collabsible)
5734 body.attr('id', this.id('sectiongroup'))
5735 .on('show.bs.collapse', { self: this }, this._ev_panel_collapse);
5740 body.append($('<li />')
5741 .addClass('list-group-item text-muted')
5742 .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.')))
5745 for (var i = 0; i < s.length; i++)
5747 var sid = s[i]['.name'];
5748 var inst = this.instance[sid] = { tabs: [ ] };
5750 body.append($('<li />')
5751 .addClass('list-group-item')
5752 .append(this._render_section_head(sid, i))
5753 .append(this._render_section_body(sid, i)));
5759 render: function(condensed)
5761 this.instance = { };
5763 var panel = $('<div />')
5764 .addClass('panel panel-default')
5765 .append(this._render_head(condensed))
5766 .append(this._render_body(condensed));
5768 if (this.options.addremove)
5769 panel.append($('<div />')
5770 .addClass('panel-footer')
5771 .append(this._render_add()));
5778 var s = this.sections();
5780 for (var i = 0; i < s.length; i++)
5782 var sid = s[i]['.name'];
5784 this.validate_section(sid);
5786 if (i != this.active_panel)
5787 $('#' + this.id('teaser', sid)).children('span:last')
5788 .append(this.teaser(sid));
5790 $('#' + this.id('teaser', sid))
5796 this.cbi.TableSection = this.cbi.TypedSection.extend({
5797 _render_table_head: function()
5799 var thead = $('<thead />')
5801 .addClass('cbi-section-table-titles'));
5803 for (var j = 0; j < this.tabs[0].fields.length; j++)
5804 thead.children().append($('<th />')
5805 .addClass('cbi-section-table-cell')
5806 .css('width', this.tabs[0].fields[j].options.width || '')
5807 .append(this.tabs[0].fields[j].label('caption')));
5809 if (this.options.addremove !== false || this.options.sortable)
5810 thead.children().append($('<th />')
5811 .addClass('cbi-section-table-cell')
5817 _render_table_row: function(sid, index)
5819 var row = $('<tr />')
5820 .attr('data-luci2-sid', sid);
5822 for (var j = 0; j < this.tabs[0].fields.length; j++)
5824 row.append($('<td />')
5825 .css('width', this.tabs[0].fields[j].options.width || '')
5826 .append(this.tabs[0].fields[j].render(sid, true)));
5829 if (this.options.addremove !== false || this.options.sortable)
5831 row.append($('<td />')
5832 .addClass('text-right')
5833 .append($('<div />')
5834 .addClass('btn-group')
5835 .append(this._render_sort(sid, index))
5836 .append(this._render_remove(sid, index))));
5842 _render_table_body: function()
5844 var s = this.sections();
5846 var tbody = $('<tbody />');
5850 var cols = this.tabs[0].fields.length;
5852 if (this.options.addremove !== false || this.options.sortable)
5855 tbody.append($('<tr />')
5857 .addClass('text-muted')
5858 .attr('colspan', cols)
5859 .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.'))));
5862 for (var i = 0; i < s.length; i++)
5864 var sid = s[i]['.name'];
5865 var inst = this.instance[sid] = { tabs: [ ] };
5867 tbody.append(this._render_table_row(sid, i));
5873 _render_body: function(condensed)
5875 return $('<table />')
5876 .addClass('table table-condensed table-hover')
5877 .append(this._render_table_head())
5878 .append(this._render_table_body());
5882 this.cbi.NamedSection = this.cbi.TypedSection.extend({
5883 sections: function(cb)
5886 var pkg = this.map.uci.values[this.map.uci_package];
5889 if (pkg[s]['.name'] == this.uci_type)
5895 if (typeof(cb) == 'function' && sa.length > 0)
5896 cb.apply(this, [ sa[0] ]);
5902 this.cbi.DummySection = this.cbi.TypedSection.extend({
5903 sections: function(cb)
5905 if (typeof(cb) == 'function')
5906 cb.apply(this, [ { '.name': this.uci_type } ]);
5908 return [ { '.name': this.uci_type } ];
5912 this.cbi.Map = this.ui.AbstractWidget.extend({
5913 init: function(uci_package, options)
5917 this.uci_package = uci_package;
5918 this.sections = [ ];
5919 this.options = _luci2.defaults(options, {
5920 save: function() { },
5921 prepare: function() {
5922 return _luci2.uci.writable(function(writable) {
5923 self.options.readonly = !writable;
5929 _load_cb: function(packages)
5931 for (var i = 0; i < packages.length; i++)
5933 this.uci.values[packages[i]['.package']] = packages[i];
5934 delete packages[i]['.package'];
5937 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
5939 for (var i = 0; i < this.sections.length; i++)
5941 for (var f in this.sections[i].fields)
5943 if (typeof(this.sections[i].fields[f].load) != 'function')
5946 var s = this.sections[i].sections();
5947 for (var j = 0; j < s.length; j++)
5949 var rv = this.sections[i].fields[f].load(s[j]['.name']);
5950 if (_luci2.isDeferred(rv))
5956 return $.when.apply($, deferreds);
5974 for (var i = 0; i < this.sections.length; i++)
5975 this.sections[i].ucipackages(packages);
5977 packages[this.uci_package] = true;
5981 for (var pkg in packages)
5982 _luci2.uci.get_all(pkg);
5984 return _luci2.rpc.flush().then(function(packages) {
5985 return self._load_cb(packages);
5989 _ev_tab: function(ev)
5991 var self = ev.data.self;
5994 self.active_tab = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
5997 _render_tab_head: function(tab_index)
5999 var section = this.sections[tab_index];
6000 var cur = this.active_tab || 0;
6002 var tabh = $('<li />')
6004 .attr('id', section.id('sectiontab'))
6005 .attr('href', '#' + section.id('section'))
6006 .attr('data-toggle', 'tab')
6007 .attr('data-luci2-tab-index', tab_index)
6008 .text(section.label('caption') + ' ')
6009 .append($('<span />')
6011 .on('shown.bs.tab', { self: this }, this._ev_tab));
6013 if (cur == tab_index)
6014 tabh.addClass('active');
6019 _render_tab_body: function(tab_index)
6021 var section = this.sections[tab_index];
6022 var desc = section.label('description');
6023 var cur = this.active_tab || 0;
6025 var tabb = $('<div />')
6026 .addClass('tab-pane')
6027 .attr('id', section.id('section'))
6028 .attr('data-luci2-tab-index', tab_index);
6030 if (cur == tab_index)
6031 tabb.addClass('active');
6034 tabb.append($('<p />')
6037 var s = section.render(this.options.tabbed);
6039 if (this.options.readonly || section.options.readonly)
6040 s.find('input, select, button, img.cbi-button').attr('disabled', true);
6047 _render_body: function()
6049 var tabs = $('<ul />')
6050 .addClass('nav nav-tabs');
6052 var body = $('<div />')
6055 for (var i = 0; i < this.sections.length; i++)
6057 tabs.append(this._render_tab_head(i));
6058 body.append(this._render_tab_body(i));
6061 if (this.options.tabbed)
6062 body.addClass('tab-content');
6071 var map = $('<form />');
6073 if (typeof(this.options.caption) == 'string')
6074 map.append($('<h2 />')
6075 .text(this.options.caption));
6077 if (typeof(this.options.description) == 'string')
6078 map.append($('<p />')
6079 .text(this.options.description));
6081 map.append(this._render_body());
6083 if (this.options.pageaction !== false)
6085 map.append($('<div />')
6086 .addClass('panel panel-default panel-body text-right')
6087 .append($('<div />')
6088 .addClass('btn-group')
6089 .append(_luci2.ui.button(_luci2.tr('Save & Apply'), 'primary')
6090 .click({ self: this }, function(ev) { }))
6091 .append(_luci2.ui.button(_luci2.tr('Save'), 'default')
6092 .click({ self: this }, function(ev) { ev.data.self.send(); }))
6093 .append(_luci2.ui.button(_luci2.tr('Reset'), 'default')
6094 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); }))));
6102 for (var i = 0; i < this.sections.length; i++)
6103 this.sections[i].finish();
6110 this.target.hide().empty().append(this.render());
6115 section: function(widget, uci_type, options)
6117 var w = widget ? new widget(uci_type, options) : null;
6119 if (!(w instanceof _luci2.cbi.AbstractSection))
6120 throw 'Widget must be an instance of AbstractSection';
6123 w.index = this.sections.length;
6125 this.sections.push(w);
6129 formvalue: function()
6133 for (var i = 0; i < this.sections.length; i++)
6135 var sids = this.sections[i].formvalue();
6136 for (var sid in sids)
6138 var s = rv[sid] || (rv[sid] = { });
6139 $.extend(s, sids[sid]);
6146 add: function(conf, type, name)
6148 var c = this.uci.creates;
6149 var s = '.new.%d'.format(this.uci.newid++);
6158 '.anonymous': !name,
6159 '.index': 1000 + this.uci.newid
6165 remove: function(conf, sid)
6167 var n = this.uci.creates;
6168 var c = this.uci.changes;
6169 var d = this.uci.deletes;
6171 /* requested deletion of a just created section */
6172 if (sid.indexOf('.new.') == 0)
6175 delete n[conf][sid];
6180 delete c[conf][sid];
6185 d[conf][sid] = true;
6189 ucisections: function(conf, cb)
6192 var pkg = this.uci.values[conf];
6193 var crt = this.uci.creates[conf];
6194 var del = this.uci.deletes[conf];
6200 if (!del || del[s] !== true)
6207 sa.sort(function(a, b) {
6208 return a['.index'] - b['.index'];
6211 for (var i = 0; i < sa.length; i++)
6212 sa[i]['.index'] = i;
6214 if (typeof(cb) == 'function')
6215 for (var i = 0; i < sa.length; i++)
6216 cb.apply(this, [ sa[i] ]);
6221 get: function(conf, sid, opt)
6223 var v = this.uci.values;
6224 var n = this.uci.creates;
6225 var c = this.uci.changes;
6226 var d = this.uci.deletes;
6228 /* requested option in a just created section */
6229 if (sid.indexOf('.new.') == 0)
6234 if (typeof(opt) == 'undefined')
6235 return (n[conf][sid] || { });
6237 return n[conf][sid][opt];
6240 /* requested an option value */
6241 if (typeof(opt) != 'undefined')
6243 /* check whether option was deleted */
6244 if (d[conf] && d[conf][sid])
6246 if (d[conf][sid] === true)
6249 for (var i = 0; i < d[conf][sid].length; i++)
6250 if (d[conf][sid][i] == opt)
6254 /* check whether option was changed */
6255 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
6256 return c[conf][sid][opt];
6258 /* return base value */
6259 if (v[conf] && v[conf][sid])
6260 return v[conf][sid][opt];
6265 /* requested an entire section */
6267 return (v[conf][sid] || { });
6272 set: function(conf, sid, opt, val)
6274 var n = this.uci.creates;
6275 var c = this.uci.changes;
6276 var d = this.uci.deletes;
6278 if (sid.indexOf('.new.') == 0)
6280 if (n[conf] && n[conf][sid])
6282 if (typeof(val) != 'undefined')
6283 n[conf][sid][opt] = val;
6285 delete n[conf][sid][opt];
6288 else if (typeof(val) != 'undefined')
6296 c[conf][sid][opt] = val;
6306 d[conf][sid].push(opt);
6310 validate: function()
6314 for (var i = 0; i < this.sections.length; i++)
6316 if (!this.sections[i].validate())
6325 if (this.options.readonly)
6326 return _luci2.deferrable();
6328 var deferreds = [ _luci2.deferrable(this.options.save()) ];
6330 for (var i = 0; i < this.sections.length; i++)
6332 if (this.sections[i].options.readonly)
6335 for (var f in this.sections[i].fields)
6337 if (typeof(this.sections[i].fields[f].save) != 'function')
6340 var s = this.sections[i].sections();
6341 for (var j = 0; j < s.length; j++)
6343 var rv = this.sections[i].fields[f].save(s[j]['.name']);
6344 if (_luci2.isDeferred(rv))
6350 return $.when.apply($, deferreds);
6353 _send_uci_reorder: function()
6355 if (!this.uci.reorder)
6356 return _luci2.deferrable();
6361 gather all created and existing sections, sort them according
6362 to their index value and issue an uci order call
6364 for (var c in this.uci.values)
6368 if (this.uci.creates && this.uci.creates[c])
6369 for (var s in this.uci.creates[c])
6370 o.push(this.uci.creates[c][s]);
6372 for (var s in this.uci.values[c])
6373 o.push(this.uci.values[c][s]);
6377 o.sort(function(a, b) {
6378 return (a['.index'] - b['.index']);
6383 for (var i = 0; i < o.length; i++)
6384 sids.push(o[i]['.name']);
6386 _luci2.uci.order(c, sids);
6390 return _luci2.rpc.flush();
6393 _send_uci: function()
6400 if (this.uci.creates)
6401 for (var c in this.uci.creates)
6402 for (var s in this.uci.creates[c])
6409 for (var k in this.uci.creates[c][s])
6412 r.type = this.uci.creates[c][s][k];
6413 else if (k == '.create')
6414 r.name = this.uci.creates[c][s][k];
6415 else if (k.charAt(0) != '.')
6416 r.values[k] = this.uci.creates[c][s][k];
6419 snew.push(this.uci.creates[c][s]);
6421 _luci2.uci.add(r.config, r.type, r.name, r.values);
6424 if (this.uci.changes)
6425 for (var c in this.uci.changes)
6426 for (var s in this.uci.changes[c])
6427 _luci2.uci.set(c, s, this.uci.changes[c][s]);
6429 if (this.uci.deletes)
6430 for (var c in this.uci.deletes)
6431 for (var s in this.uci.deletes[c])
6433 var o = this.uci.deletes[c][s];
6434 _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
6437 return _luci2.rpc.flush().then(function(responses) {
6439 array "snew" holds references to the created uci sections,
6440 use it to assign the returned names of the new sections
6442 for (var i = 0; i < snew.length; i++)
6443 snew[i]['.name'] = responses[i];
6445 return self._send_uci_reorder();
6451 if (!this.validate())
6452 return _luci2.deferrable();
6456 _luci2.ui.saveScrollTop();
6457 _luci2.ui.loading(true);
6459 return this.save().then(function() {
6460 return self._send_uci();
6461 }).then(function() {
6462 return _luci2.ui.updateChanges();
6463 }).then(function() {
6465 }).then(function() {
6469 _luci2.ui.loading(false);
6470 _luci2.ui.restoreScrollTop();
6474 insertInto: function(id)
6477 self.target = $(id);
6479 _luci2.ui.loading(true);
6482 return self.load().then(function() {
6483 self.target.empty().append(self.render());
6487 _luci2.ui.loading(false);