2 LuCI - Lua Configuration Interface
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008-2012 Jo-Philipp Wich <jow@openwrt.org>
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
11 http://www.apache.org/licenses/LICENSE-2.0
18 var cbi_validators = {
22 return (this.match(/^-?[0-9]+$/) != null);
25 'uinteger': function()
27 return (cbi_validators.integer.apply(this) && (this >= 0));
32 return !isNaN(parseFloat(this));
37 return (cbi_validators['float'].apply(this) && (this >= 0));
42 return cbi_validators.ip4addr.apply(this) ||
43 cbi_validators.ip6addr.apply(this);
48 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
50 return (RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
51 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
52 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
53 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
54 ((RegExp.$6.indexOf('.') < 0)
55 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
56 : (cbi_validators.ip4addr.apply(RegExp.$6)))
65 if( this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/) )
67 if( !RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)) )
76 if( addr.indexOf('.') > 0 )
78 var off = addr.lastIndexOf(':');
80 if( !(off && cbi_validators.ip4addr.apply(addr.substr(off+1))) )
83 addr = addr.substr(0, off) + ':0:0';
86 if( addr.indexOf('::') >= 0 )
91 for( var i = 1; i < (addr.length-1); i++ )
92 if( addr.charAt(i) == ':' )
98 for( var i = 0; i < (7 - colons); i++ )
101 if (addr.match(/^(.*?)::(.*?)$/))
102 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
103 (RegExp.$2 ? ':' + RegExp.$2 : '');
106 return (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null);
115 return cbi_validators.integer.apply(this) &&
116 (this >= 0) && (this <= 65535);
119 'portrange': function()
121 if (this.match(/^(\d+)-(\d+)$/))
126 return cbi_validators.port.apply(p1) &&
127 cbi_validators.port.apply(p2) &&
128 (parseInt(p1) <= parseInt(p2))
133 return cbi_validators.port.apply(this);
137 'macaddr': function()
139 return (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
144 return cbi_validators.hostname.apply(this) ||
145 cbi_validators.ipaddr.apply(this);
148 'hostname': function()
150 if (this.length <= 253)
151 return (this.match(/^[a-zA-Z0-9]+$/) != null ||
152 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
153 this.match(/[^0-9.]/)));
158 'network': function()
160 return cbi_validators.uciname.apply(this) ||
161 cbi_validators.host.apply(this);
164 'hostport': function()
166 var hp = this.split(/:/);
169 return (cbi_validators.host.apply(hp[0]) &&
170 cbi_validators.port.apply(hp[1]));
175 'ipaddrport': function()
177 var hp = this.split(/:/);
180 return (cbi_validators.ipaddr.apply(hp[0]) &&
181 cbi_validators.port.apply(hp[1]));
191 return (v.match(/^[a-fA-F0-9]{64}$/) != null);
193 return (v.length >= 8) && (v.length <= 63);
200 if ( v.substr(0,2) == 's:' )
203 if( (v.length == 10) || (v.length == 26) )
204 return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
206 return (v.length == 5) || (v.length == 13);
209 'uciname': function()
211 return (this.match(/^[a-zA-Z0-9_]+$/) != null);
214 'range': function(min, max)
216 var val = parseFloat(this);
217 if (!isNaN(min) && !isNaN(max) && !isNaN(val))
218 return ((val >= min) && (val <= max));
225 var val = parseFloat(this);
226 if (!isNaN(min) && !isNaN(val))
234 var val = parseFloat(this);
235 if (!isNaN(max) && !isNaN(val))
241 'rangelength': function(min, max)
244 if (!isNaN(min) && !isNaN(max))
245 return ((val.length >= min) && (val.length <= max));
250 'minlength': function(min)
254 return (val.length >= min);
259 'maxlength': function(max)
263 return (val.length <= max);
270 for (var i = 0; i < arguments.length; i += 2)
272 if (typeof arguments[i] != 'function')
274 if (arguments[i] == this)
278 else if (arguments[i].apply(this, arguments[i+1]))
288 for (var i = 0; i < arguments.length; i += 2)
290 if (typeof arguments[i] != 'function')
292 if (arguments[i] != this)
296 else if (!arguments[i].apply(this, arguments[i+1]))
306 return cbi_validators.or.apply(
307 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
310 'list': function(subvalidator, subargs)
312 if (typeof subvalidator != 'function')
315 var tokens = this.match(/[^ \t]+/g);
316 for (var i = 0; i < tokens.length; i++)
317 if (!subvalidator.apply(tokens[i], subargs))
322 'phonedigit': function()
324 return (this.match(/^[0-9\*#!\.]+$/) != null);
329 function cbi_d_add(field, dep, next) {
330 var obj = document.getElementById(field);
333 for (var i=0; i<cbi_d.length; i++) {
334 if (cbi_d[i].id == field) {
343 "parent": obj.parentNode.id,
347 cbi_d.unshift(entry);
353 function cbi_d_checkvalue(target, ref) {
354 var t = document.getElementById(target);
358 var tl = document.getElementsByName(target);
360 if( tl.length > 0 && (tl[0].type == 'radio' || tl[0].type == 'checkbox'))
361 for( var i = 0; i < tl.length; i++ )
362 if( tl[i].checked ) {
367 value = value ? value : "";
368 } else if (!t.value) {
373 if (t.type == "checkbox") {
374 value = t.checked ? value : "";
378 return (value == ref)
381 function cbi_d_check(deps) {
384 for (var i=0; i<deps.length; i++) {
387 for (var j in deps[i]) {
388 if (j == "!reverse") {
390 } else if (j == "!default") {
394 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
404 function cbi_d_update() {
406 for (var i=0; i<cbi_d.length; i++) {
407 var entry = cbi_d[i];
408 var next = document.getElementById(entry.next)
409 var node = document.getElementById(entry.id)
410 var parent = document.getElementById(entry.parent)
412 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
413 node.parentNode.removeChild(node);
416 cbi_c[entry.parent]--;
417 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
419 parent.appendChild(entry.node);
421 next.parentNode.insertBefore(entry.node, next);
425 cbi_c[entry.parent]++;
429 if (entry && entry.parent) {
431 cbi_tag_last(parent);
439 function cbi_bind(obj, type, callback, mode) {
440 if (!obj.addEventListener) {
441 obj.attachEvent('on' + type,
443 var e = window.event;
445 if (!e.target && e.srcElement)
446 e.target = e.srcElement;
448 return !!callback(e);
452 obj.addEventListener(type, callback, !!mode);
457 function cbi_combobox(id, values, def, man) {
458 var selid = "cbi.combobox." + id;
459 if (document.getElementById(selid)) {
463 var obj = document.getElementById(id)
464 var sel = document.createElement("select");
466 sel.className = obj.className.replace(/cbi-input-text/, 'cbi-input-select');
468 if (obj.nextSibling) {
469 obj.parentNode.insertBefore(sel, obj.nextSibling);
471 obj.parentNode.appendChild(sel);
474 var dt = obj.getAttribute('cbi_datatype');
475 var op = obj.getAttribute('cbi_optional');
478 cbi_validate_field(sel, op == 'true', dt);
480 if (!values[obj.value]) {
481 if (obj.value == "") {
482 var optdef = document.createElement("option");
484 optdef.appendChild(document.createTextNode(def));
485 sel.appendChild(optdef);
487 var opt = document.createElement("option");
488 opt.value = obj.value;
489 opt.selected = "selected";
490 opt.appendChild(document.createTextNode(obj.value));
491 sel.appendChild(opt);
495 for (var i in values) {
496 var opt = document.createElement("option");
499 if (obj.value == i) {
500 opt.selected = "selected";
503 opt.appendChild(document.createTextNode(values[i]));
504 sel.appendChild(opt);
507 var optman = document.createElement("option");
509 optman.appendChild(document.createTextNode(man));
510 sel.appendChild(optman);
512 obj.style.display = "none";
514 cbi_bind(sel, "change", function() {
515 if (sel.selectedIndex == sel.options.length - 1) {
516 obj.style.display = "inline";
517 sel.parentNode.removeChild(sel);
520 obj.value = sel.options[sel.selectedIndex].value;
530 // Retrigger validation in select
535 function cbi_combobox_init(id, values, def, man) {
536 var obj = document.getElementById(id);
537 cbi_bind(obj, "blur", function() {
538 cbi_combobox(id, values, def, man)
540 cbi_combobox(id, values, def, man);
543 function cbi_filebrowser(id, url, defpath) {
544 var field = document.getElementById(id);
545 var browser = window.open(
546 url + ( field.value || defpath || '' ) + '?field=' + id,
547 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
553 function cbi_browser_init(id, respath, url, defpath)
555 function cbi_browser_btnclick(e) {
556 cbi_filebrowser(id, url, defpath);
560 var field = document.getElementById(id);
562 var btn = document.createElement('img');
563 btn.className = 'cbi-image-button';
564 btn.src = respath + '/cbi/folder.gif';
565 field.parentNode.insertBefore(btn, field.nextSibling);
567 cbi_bind(btn, 'click', cbi_browser_btnclick);
570 function cbi_dynlist_init(name, respath, datatype, optional, url, defpath, choices)
572 var input0 = document.getElementsByName(name)[0];
573 var prefix = input0.name;
574 var parent = input0.parentNode;
575 var holder = input0.placeholder;
579 function cbi_dynlist_redraw(focus, add, del)
583 while (parent.firstChild)
585 var n = parent.firstChild;
586 var i = parseInt(n.index);
590 if (n.nodeName.toLowerCase() == 'input')
591 values.push(n.value || '');
592 else if (n.nodeName.toLowerCase() == 'select')
593 values[values.length-1] = n.options[n.selectedIndex].value;
596 parent.removeChild(n);
602 values.splice(focus, 0, '');
604 else if (values.length == 0)
610 for (var i = 0; i < values.length; i++)
612 var t = document.createElement('input');
613 t.id = prefix + '.' + (i+1);
618 t.className = 'cbi-input-text';
620 if (i == 0 && holder)
622 t.placeholder = holder;
625 var b = document.createElement('img');
626 b.src = respath + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
627 b.className = 'cbi-image-button';
629 parent.appendChild(t);
630 parent.appendChild(b);
631 if (datatype == 'file')
633 cbi_browser_init(t.id, respath, url, defpath);
636 parent.appendChild(document.createElement('br'));
640 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
645 cbi_combobox_init(t.id, choices[0], '', choices[1]);
648 cbi_bind(b, 'keydown', cbi_dynlist_keydown);
649 cbi_bind(b, 'keypress', cbi_dynlist_keypress);
651 if (i == focus || -i == focus)
656 cbi_bind(t, 'keydown', cbi_dynlist_keydown);
657 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
663 else if (-i == focus)
667 /* force cursor to end */
674 cbi_bind(b, 'click', cbi_dynlist_btnclick);
678 function cbi_dynlist_keypress(ev)
680 ev = ev ? ev : window.event;
682 var se = ev.target ? ev.target : ev.srcElement;
684 if (se.nodeType == 3)
689 /* backspace, delete */
692 if (se.value.length == 0)
694 if (ev.preventDefault)
702 /* enter, arrow up, arrow down */
706 if (ev.preventDefault)
715 function cbi_dynlist_keydown(ev)
717 ev = ev ? ev : window.event;
719 var se = ev.target ? ev.target : ev.srcElement;
721 if (se.nodeType == 3)
724 var prev = se.previousSibling;
725 while (prev && prev.name != name)
726 prev = prev.previousSibling;
728 var next = se.nextSibling;
729 while (next && next.name != name)
730 next = next.nextSibling;
732 /* advance one further in combobox case */
733 if (next && next.nextSibling.name == name)
734 next = next.nextSibling;
738 /* backspace, delete */
741 var del = (se.nodeName.toLowerCase() == 'select')
742 ? true : (se.value.length == 0);
746 if (ev.preventDefault)
749 var focus = se.index;
753 cbi_dynlist_redraw(focus, -1, se.index);
762 cbi_dynlist_redraw(-1, se.index, -1);
783 function cbi_dynlist_btnclick(ev)
785 ev = ev ? ev : window.event;
787 var se = ev.target ? ev.target : ev.srcElement;
788 var input = se.previousSibling;
789 while (input && input.name != name) {
790 input = input.previousSibling;
793 if (se.src.indexOf('remove') > -1)
797 cbi_dynlist_keydown({
804 cbi_dynlist_keydown({
813 cbi_dynlist_redraw(NaN, -1, -1);
816 //Hijacks the CBI form to send via XHR (requires Prototype)
817 function cbi_hijack_forms(layer, win, fail, load) {
818 var forms = layer.getElementsByTagName('form');
819 for (var i=0; i<forms.length; i++) {
820 $(forms[i]).observe('submit', function(event) {
821 // Prevent the form from also submitting the regular way
825 event.element().request({
838 function cbi_t_add(section, tab) {
839 var t = document.getElementById('tab.' + section + '.' + tab);
840 var c = document.getElementById('container.' + section + '.' + tab);
843 cbi_t[section] = (cbi_t[section] || [ ]);
844 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
848 function cbi_t_switch(section, tab) {
849 if( cbi_t[section] && cbi_t[section][tab] ) {
850 var o = cbi_t[section][tab];
851 var h = document.getElementById('tab.' + section);
852 for( var tid in cbi_t[section] ) {
853 var o2 = cbi_t[section][tid];
854 if( o.tab.id != o2.tab.id ) {
855 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
856 o2.container.style.display = 'none';
860 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
861 o2.container.style.display = 'block';
868 function cbi_t_update() {
872 for( var sid in cbi_t )
873 for( var tid in cbi_t[sid] )
875 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
876 cbi_t[sid][tid].tab.style.display = 'none';
878 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
879 cbi_t[sid][tid].tab.style.display = '';
881 var t = cbi_t[sid][tid].tab;
882 t.className += ' cbi-tab-highlighted';
886 cbi_tag_last(cbi_t[sid][tid].container);
890 if( hl_tabs.length > 0 )
891 window.setTimeout(function() {
892 for( var i = 0; i < hl_tabs.length; i++ )
893 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
900 function cbi_validate_form(form, errmsg)
902 /* if triggered by a section removal or addition, don't validate */
903 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
906 if( form.cbi_validators )
908 for( var i = 0; i < form.cbi_validators.length; i++ )
910 var validator = form.cbi_validators[i];
911 if( !validator() && errmsg )
922 function cbi_validate_reset(form)
925 function() { cbi_validate_form(form, null) }, 100
931 function cbi_validate_compile(code)
940 for (var i = 0; i < code.length; i++)
948 switch (code.charCodeAt(i))
960 var label = code.substring(pos, i);
961 label = label.replace(/\\(.)/g, '$1');
962 label = label.replace(/^[ \t]+/g, '');
963 label = label.replace(/[ \t]+$/g, '');
965 if (label && !isNaN(label))
967 stack.push(parseFloat(label));
969 else if (label.match(/^(['"]).*\1$/))
971 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
973 else if (typeof cbi_validators[label] == 'function')
975 stack.push(cbi_validators[label]);
980 throw "Syntax error, unhandled token '"+label+"'";
985 depth += (code.charCodeAt(i) == 40);
991 if (typeof stack[stack.length-2] != 'function')
992 throw "Syntax error, argument list follows non-function";
994 stack[stack.length-1] =
995 arguments.callee(code.substring(pos, i));
1006 function cbi_validate_field(cbid, optional, type)
1008 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
1009 var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
1011 if (field && vstack && typeof vstack[0] == "function")
1013 var validator = function()
1018 field.className = field.className.replace(/ cbi-input-invalid/g, '');
1021 var value = (field.options && field.options.selectedIndex > -1)
1022 ? field.options[field.options.selectedIndex].value : field.value;
1024 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
1027 field.className += ' cbi-input-invalid';
1035 if( ! field.form.cbi_validators )
1036 field.form.cbi_validators = [ ];
1038 field.form.cbi_validators.push(validator);
1040 cbi_bind(field, "blur", validator);
1041 cbi_bind(field, "keyup", validator);
1043 if (field.nodeName == 'SELECT')
1045 cbi_bind(field, "change", validator);
1046 cbi_bind(field, "click", validator);
1049 field.setAttribute("cbi_validate", validator);
1050 field.setAttribute("cbi_datatype", type);
1051 field.setAttribute("cbi_optional", (!!optional).toString());
1055 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1057 cbi_validate_field(fcbox, optional, type);
1061 function cbi_row_swap(elem, up, store)
1063 var tr = elem.parentNode;
1064 while (tr && tr.nodeName.toLowerCase() != 'tr')
1070 var table = tr.parentNode;
1071 while (table && table.nodeName.toLowerCase() != 'table')
1072 table = table.parentNode;
1078 var e = up ? table.rows.length : table.rows.length - 1;
1080 for (var idx = s; idx < e; idx++)
1082 if (table.rows[idx] == tr)
1085 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
1087 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
1094 for (idx = 2; idx < table.rows.length; idx++)
1096 table.rows[idx].className = table.rows[idx].className.replace(
1097 /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
1100 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
1101 ids.push(RegExp.$1);
1104 var input = document.getElementById(store);
1106 input.value = ids.join(' ');
1111 function cbi_tag_last(container)
1115 for (var i = 0; i < container.childNodes.length; i++)
1117 var c = container.childNodes[i];
1118 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1120 c.className = c.className.replace(/ cbi-value-last$/, '');
1127 last.className += ' cbi-value-last';
1131 String.prototype.serialize = function()
1148 for( var i = 0; i < o.length; i++ )
1149 s += (s ? ', ' : '') + String.serialize(o[i]);
1151 return '[ ' + s + ' ]';
1160 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1162 return '{ ' + s + ' }';
1169 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1170 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1174 return '"' + o + '"';
1179 return o.toString();
1183 String.prototype.format = function()
1188 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1189 var quot_esc = [/"/g, '"', /'/g, '''];
1191 function esc(s, r) {
1192 for( var i = 0; i < r.length; i += 2 )
1193 s = s.replace(r[i], r[i+1]);
1199 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1200 var a = b = [], numSubstitutions = 0, numMatches = 0;
1202 while( a = re.exec(str) )
1205 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1206 var pPrecision = a[6], pType = a[7];
1216 if (numSubstitutions < arguments.length)
1218 var param = arguments[numSubstitutions++];
1221 if (pPad && pPad.substr(0,1) == "'")
1222 pad = leftpart.substr(1,1);
1226 var justifyRight = true;
1227 if (pJustify && pJustify === "-")
1228 justifyRight = false;
1232 minLength = parseInt(pMinLength);
1235 if (pPrecision && pType == 'f')
1236 precision = parseInt(pPrecision.substring(1));
1243 subst = (parseInt(param) || 0).toString(2);
1247 subst = String.fromCharCode(parseInt(param) || 0);
1251 subst = (parseInt(param) || 0);
1255 subst = Math.abs(parseInt(param) || 0);
1259 subst = (precision > -1)
1260 ? ((parseFloat(param) || 0.0)).toFixed(precision)
1261 : (parseFloat(param) || 0.0);
1265 subst = (parseInt(param) || 0).toString(8);
1273 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1277 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1281 subst = esc(param, html_esc);
1285 subst = esc(param, quot_esc);
1289 subst = String.serialize(param);
1296 var ts = (param || 0);
1299 tm = Math.floor(ts / 60);
1304 th = Math.floor(tm / 60);
1309 td = Math.floor(th / 24);
1314 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1315 : String.format('%dh %dm %ds', th, tm, ts);
1320 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1321 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1324 var val = parseFloat(param || 0);
1325 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1327 for (i = 0; (i < units.length) && (val > mf); i++)
1330 subst = val.toFixed(pr) + ' ' + units[i];
1336 out += leftpart + subst;
1337 str = str.substr(m.length);
1343 String.prototype.nobr = function()
1345 return this.replace(/[\s\n]+/g, ' ');
1348 String.serialize = function()
1351 for (var i = 1; i < arguments.length; i++)
1352 a.push(arguments[i]);
1353 return ''.serialize.apply(arguments[0], a);
1356 String.format = function()
1359 for (var i = 1; i < arguments.length; i++)
1360 a.push(arguments[i]);
1361 return ''.format.apply(arguments[0], a);
1364 String.nobr = function()
1367 for (var i = 1; i < arguments.length; i++)
1368 a.push(arguments[i]);
1369 return ''.nobr.apply(arguments[0], a);