2 LuCI - Lua Configuration Interface
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008-2012 Jo-Philipp Wich <xm@subsignal.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-Z]+$/) != 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);
169 return (v.match(/^[a-fA-F0-9]{64}$/) != null);
171 return (v.length >= 8) && (v.length <= 63);
178 if ( v.substr(0,2) == 's:' )
181 if( (v.length == 10) || (v.length == 26) )
182 return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
184 return (v.length == 5) || (v.length == 13);
187 'uciname': function()
189 return (this.match(/^[a-zA-Z0-9_]+$/) != null);
192 'range': function(min, max)
194 var val = parseFloat(this);
195 if (!isNaN(min) && !isNaN(max) && !isNaN(val))
196 return ((val >= min) && (val <= max));
203 var val = parseFloat(this);
204 if (!isNaN(min) && !isNaN(val))
212 var val = parseFloat(this);
213 if (!isNaN(max) && !isNaN(val))
219 'rangelength': function(min, max)
222 if (!isNaN(min) && !isNaN(max))
223 return ((val.length >= min) && (val.length <= max));
228 'minlength': function(min)
232 return (val.length >= min);
237 'maxlength': function(max)
241 return (val.length <= max);
248 for (var i = 0; i < arguments.length; i += 2)
250 if (typeof arguments[i] != 'function')
252 if (arguments[i] == this)
256 else if (arguments[i].apply(this, arguments[i+1]))
266 for (var i = 0; i < arguments.length; i += 2)
268 if (typeof arguments[i] != 'function')
270 if (arguments[i] != this)
274 else if (!arguments[i].apply(this, arguments[i+1]))
284 return cbi_validators.or.apply(
285 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
288 'list': function(subvalidator, subargs)
290 if (typeof subvalidator != 'function')
293 var tokens = this.match(/[^ \t]+/g);
294 for (var i = 0; i < tokens.length; i++)
295 if (!subvalidator.apply(tokens[i], subargs))
300 'phonedigit': function()
302 return (this.match(/^[0-9\*#]+$/) != null);
307 function cbi_d_add(field, dep, next) {
308 var obj = document.getElementById(field);
311 for (var i=0; i<cbi_d.length; i++) {
312 if (cbi_d[i].id == field) {
321 "parent": obj.parentNode.id,
325 cbi_d.unshift(entry);
331 function cbi_d_checkvalue(target, ref) {
332 var t = document.getElementById(target);
336 var tl = document.getElementsByName(target);
338 if( tl.length > 0 && tl[0].type == 'radio' )
339 for( var i = 0; i < tl.length; i++ )
340 if( tl[i].checked ) {
345 value = value ? value : "";
346 } else if (!t.value) {
351 if (t.type == "checkbox") {
352 value = t.checked ? value : "";
356 return (value == ref)
359 function cbi_d_check(deps) {
362 for (var i=0; i<deps.length; i++) {
365 for (var j in deps[i]) {
366 if (j == "!reverse") {
368 } else if (j == "!default") {
372 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
382 function cbi_d_update() {
384 for (var i=0; i<cbi_d.length; i++) {
385 var entry = cbi_d[i];
386 var next = document.getElementById(entry.next)
387 var node = document.getElementById(entry.id)
388 var parent = document.getElementById(entry.parent)
390 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
391 node.parentNode.removeChild(node);
394 cbi_c[entry.parent]--;
395 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
397 parent.appendChild(entry.node);
399 next.parentNode.insertBefore(entry.node, next);
403 cbi_c[entry.parent]++;
407 if (entry && entry.parent) {
409 cbi_tag_last(parent);
417 function cbi_bind(obj, type, callback, mode) {
418 if (!obj.addEventListener) {
419 obj.attachEvent('on' + type,
421 var e = window.event;
423 if (!e.target && e.srcElement)
424 e.target = e.srcElement;
426 return !!callback(e);
430 obj.addEventListener(type, callback, !!mode);
435 function cbi_combobox(id, values, def, man) {
436 var selid = "cbi.combobox." + id;
437 if (document.getElementById(selid)) {
441 var obj = document.getElementById(id)
442 var sel = document.createElement("select");
444 sel.className = 'cbi-input-select';
446 if (obj.nextSibling) {
447 obj.parentNode.insertBefore(sel, obj.nextSibling);
449 obj.parentNode.appendChild(sel);
452 var dt = obj.getAttribute('cbi_datatype');
453 var op = obj.getAttribute('cbi_optional');
456 cbi_validate_field(sel, op == 'true', dt);
458 if (!values[obj.value]) {
459 if (obj.value == "") {
460 var optdef = document.createElement("option");
462 optdef.appendChild(document.createTextNode(def));
463 sel.appendChild(optdef);
465 var opt = document.createElement("option");
466 opt.value = obj.value;
467 opt.selected = "selected";
468 opt.appendChild(document.createTextNode(obj.value));
469 sel.appendChild(opt);
473 for (var i in values) {
474 var opt = document.createElement("option");
477 if (obj.value == i) {
478 opt.selected = "selected";
481 opt.appendChild(document.createTextNode(values[i]));
482 sel.appendChild(opt);
485 var optman = document.createElement("option");
487 optman.appendChild(document.createTextNode(man));
488 sel.appendChild(optman);
490 obj.style.display = "none";
492 cbi_bind(sel, "change", function() {
493 if (sel.selectedIndex == sel.options.length - 1) {
494 obj.style.display = "inline";
495 sel.parentNode.removeChild(sel);
498 obj.value = sel.options[sel.selectedIndex].value;
509 function cbi_combobox_init(id, values, def, man) {
510 var obj = document.getElementById(id);
511 cbi_bind(obj, "blur", function() {
512 cbi_combobox(id, values, def, man)
514 cbi_combobox(id, values, def, man);
517 function cbi_filebrowser(id, url, defpath) {
518 var field = document.getElementById(id);
519 var browser = window.open(
520 url + ( field.value || defpath || '' ) + '?field=' + id,
521 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
527 function cbi_browser_init(id, respath, url, defpath)
529 function cbi_browser_btnclick(e) {
530 cbi_filebrowser(id, url, defpath);
534 var field = document.getElementById(id);
536 var btn = document.createElement('img');
537 btn.className = 'cbi-image-button';
538 btn.src = respath + '/cbi/folder.gif';
539 field.parentNode.insertBefore(btn, field.nextSibling);
541 cbi_bind(btn, 'click', cbi_browser_btnclick);
544 function cbi_dynlist_init(name, respath, datatype, optional, choices)
546 var input0 = document.getElementsByName(name)[0];
547 var prefix = input0.name;
548 var parent = input0.parentNode;
549 var holder = input0.placeholder;
553 function cbi_dynlist_redraw(focus, add, del)
557 while (parent.firstChild)
559 var n = parent.firstChild;
560 var i = parseInt(n.index);
564 if (n.nodeName.toLowerCase() == 'input')
565 values.push(n.value || '');
566 else if (n.nodeName.toLowerCase() == 'select')
567 values[values.length-1] = n.options[n.selectedIndex].value;
570 parent.removeChild(n);
576 values.splice(focus, 0, '');
578 else if (values.length == 0)
584 for (var i = 0; i < values.length; i++)
586 var t = document.createElement('input');
587 t.id = prefix + '.' + (i+1);
592 t.className = 'cbi-input-text';
594 if (i == 0 && holder)
596 t.placeholder = holder;
599 var b = document.createElement('img');
600 b.src = respath + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
601 b.className = 'cbi-image-button';
603 parent.appendChild(t);
604 parent.appendChild(b);
605 parent.appendChild(document.createElement('br'));
609 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
614 cbi_combobox_init(t.id, choices[0], '', choices[1]);
615 t.nextSibling.index = i;
617 cbi_bind(t.nextSibling, 'keydown', cbi_dynlist_keydown);
618 cbi_bind(t.nextSibling, 'keypress', cbi_dynlist_keypress);
620 if (i == focus || -i == focus)
621 t.nextSibling.focus();
625 cbi_bind(t, 'keydown', cbi_dynlist_keydown);
626 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
632 else if (-i == focus)
636 /* force cursor to end */
643 cbi_bind(b, 'click', cbi_dynlist_btnclick);
647 function cbi_dynlist_keypress(ev)
649 ev = ev ? ev : window.event;
651 var se = ev.target ? ev.target : ev.srcElement;
653 if (se.nodeType == 3)
658 /* backspace, delete */
661 if (se.value.length == 0)
663 if (ev.preventDefault)
671 /* enter, arrow up, arrow down */
675 if (ev.preventDefault)
684 function cbi_dynlist_keydown(ev)
686 ev = ev ? ev : window.event;
688 var se = ev.target ? ev.target : ev.srcElement;
690 if (se.nodeType == 3)
693 var prev = se.previousSibling;
694 while (prev && prev.name != name)
695 prev = prev.previousSibling;
697 var next = se.nextSibling;
698 while (next && next.name != name)
699 next = next.nextSibling;
701 /* advance one further in combobox case */
702 if (next && next.nextSibling.name == name)
703 next = next.nextSibling;
707 /* backspace, delete */
710 var del = (se.nodeName.toLowerCase() == 'select')
711 ? true : (se.value.length == 0);
715 if (ev.preventDefault)
718 var focus = se.index;
722 cbi_dynlist_redraw(focus, -1, se.index);
731 cbi_dynlist_redraw(-1, se.index, -1);
752 function cbi_dynlist_btnclick(ev)
754 ev = ev ? ev : window.event;
756 var se = ev.target ? ev.target : ev.srcElement;
758 if (se.src.indexOf('remove') > -1)
760 se.previousSibling.value = '';
762 cbi_dynlist_keydown({
763 target: se.previousSibling,
769 cbi_dynlist_keydown({
770 target: se.previousSibling,
778 cbi_dynlist_redraw(NaN, -1, -1);
781 //Hijacks the CBI form to send via XHR (requires Prototype)
782 function cbi_hijack_forms(layer, win, fail, load) {
783 var forms = layer.getElementsByTagName('form');
784 for (var i=0; i<forms.length; i++) {
785 $(forms[i]).observe('submit', function(event) {
786 // Prevent the form from also submitting the regular way
790 event.element().request({
803 function cbi_t_add(section, tab) {
804 var t = document.getElementById('tab.' + section + '.' + tab);
805 var c = document.getElementById('container.' + section + '.' + tab);
808 cbi_t[section] = (cbi_t[section] || [ ]);
809 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
813 function cbi_t_switch(section, tab) {
814 if( cbi_t[section] && cbi_t[section][tab] ) {
815 var o = cbi_t[section][tab];
816 var h = document.getElementById('tab.' + section);
817 for( var tid in cbi_t[section] ) {
818 var o2 = cbi_t[section][tid];
819 if( o.tab.id != o2.tab.id ) {
820 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
821 o2.container.style.display = 'none';
825 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
826 o2.container.style.display = 'block';
833 function cbi_t_update() {
837 for( var sid in cbi_t )
838 for( var tid in cbi_t[sid] )
840 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
841 cbi_t[sid][tid].tab.style.display = 'none';
843 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
844 cbi_t[sid][tid].tab.style.display = '';
846 var t = cbi_t[sid][tid].tab;
847 t.className += ' cbi-tab-highlighted';
851 cbi_tag_last(cbi_t[sid][tid].container);
855 if( hl_tabs.length > 0 )
856 window.setTimeout(function() {
857 for( var i = 0; i < hl_tabs.length; i++ )
858 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
865 function cbi_validate_form(form, errmsg)
867 /* if triggered by a section removal or addition, don't validate */
868 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
871 if( form.cbi_validators )
873 for( var i = 0; i < form.cbi_validators.length; i++ )
875 var validator = form.cbi_validators[i];
876 if( !validator() && errmsg )
887 function cbi_validate_reset(form)
890 function() { cbi_validate_form(form, null) }, 100
896 function cbi_validate_compile(code)
905 for (var i = 0; i < code.length; i++)
913 switch (code.charCodeAt(i))
925 var label = code.substring(pos, i);
926 label = label.replace(/\\(.)/g, '$1');
927 label = label.replace(/^[ \t]+/g, '');
928 label = label.replace(/[ \t]+$/g, '');
930 if (label && !isNaN(label))
932 stack.push(parseFloat(label));
934 else if (label.match(/^(['"]).*\1$/))
936 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
938 else if (typeof cbi_validators[label] == 'function')
940 stack.push(cbi_validators[label]);
945 throw "Syntax error, unhandled token '"+label+"'";
950 depth += (code.charCodeAt(i) == 40);
956 if (typeof stack[stack.length-2] != 'function')
957 throw "Syntax error, argument list follows non-function";
959 stack[stack.length-1] =
960 arguments.callee(code.substring(pos, i));
971 function cbi_validate_field(cbid, optional, type)
973 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
974 var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
976 if (field && vstack && typeof vstack[0] == "function")
978 var validator = function()
983 field.className = field.className.replace(/ cbi-input-invalid/g, '');
986 var value = (field.options && field.options.selectedIndex > -1)
987 ? field.options[field.options.selectedIndex].value : field.value;
989 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
992 field.className += ' cbi-input-invalid';
1000 if( ! field.form.cbi_validators )
1001 field.form.cbi_validators = [ ];
1003 field.form.cbi_validators.push(validator);
1005 cbi_bind(field, "blur", validator);
1006 cbi_bind(field, "keyup", validator);
1008 if (field.nodeName == 'SELECT')
1010 cbi_bind(field, "change", validator);
1011 cbi_bind(field, "click", validator);
1014 field.setAttribute("cbi_validate", validator);
1015 field.setAttribute("cbi_datatype", type);
1016 field.setAttribute("cbi_optional", (!!optional).toString());
1020 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1022 cbi_validate_field(fcbox, optional, type);
1026 function cbi_row_swap(elem, up, store)
1028 var tr = elem.parentNode;
1029 while (tr && tr.nodeName.toLowerCase() != 'tr')
1035 var table = tr.parentNode;
1036 while (table && table.nodeName.toLowerCase() != 'table')
1037 table = table.parentNode;
1043 var e = up ? table.rows.length : table.rows.length - 1;
1045 for (var idx = s; idx < e; idx++)
1047 if (table.rows[idx] == tr)
1050 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
1052 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
1059 for (idx = 2; idx < table.rows.length; idx++)
1061 table.rows[idx].className = table.rows[idx].className.replace(
1062 /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
1065 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
1066 ids.push(RegExp.$1);
1069 var input = document.getElementById(store);
1071 input.value = ids.join(' ');
1076 function cbi_tag_last(container)
1080 for (var i = 0; i < container.childNodes.length; i++)
1082 var c = container.childNodes[i];
1083 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1085 c.className = c.className.replace(/ cbi-value-last$/, '');
1092 last.className += ' cbi-value-last';
1096 if( ! String.serialize )
1097 String.serialize = function(o)
1113 for( var i = 0; i < o.length; i++ )
1114 s += (s ? ', ' : '') + String.serialize(o[i]);
1116 return '[ ' + s + ' ]';
1125 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1127 return '{ ' + s + ' }';
1134 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1135 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1139 return '"' + o + '"';
1144 return o.toString();
1149 if( ! String.format )
1150 String.format = function()
1152 if (!arguments || arguments.length < 1 || !RegExp)
1155 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1156 var quot_esc = [/"/g, '"', /'/g, '''];
1158 function esc(s, r) {
1159 for( var i = 0; i < r.length; i += 2 )
1160 s = s.replace(r[i], r[i+1]);
1164 var str = arguments[0];
1166 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1167 var a = b = [], numSubstitutions = 0, numMatches = 0;
1169 while( a = re.exec(str) )
1172 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1173 var pPrecision = a[6], pType = a[7];
1183 if (numSubstitutions++ < arguments.length)
1185 var param = arguments[numSubstitutions];
1188 if (pPad && pPad.substr(0,1) == "'")
1189 pad = leftpart.substr(1,1);
1193 var justifyRight = true;
1194 if (pJustify && pJustify === "-")
1195 justifyRight = false;
1199 minLength = parseInt(pMinLength);
1202 if (pPrecision && pType == 'f')
1203 precision = parseInt(pPrecision.substring(1));
1210 subst = (parseInt(param) || 0).toString(2);
1214 subst = String.fromCharCode(parseInt(param) || 0);
1218 subst = (parseInt(param) || 0);
1222 subst = Math.abs(parseInt(param) || 0);
1226 subst = (precision > -1)
1227 ? ((parseFloat(param) || 0.0)).toFixed(precision)
1228 : (parseFloat(param) || 0.0);
1232 subst = (parseInt(param) || 0).toString(8);
1240 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1244 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1248 subst = esc(param, html_esc);
1252 subst = esc(param, quot_esc);
1256 subst = String.serialize(param);
1263 var ts = (param || 0);
1266 tm = Math.floor(ts / 60);
1271 th = Math.floor(tm / 60);
1276 td = Math.floor(th / 24);
1281 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1282 : String.format('%dh %dm %ds', th, tm, ts);
1287 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1288 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1291 var val = parseFloat(param || 0);
1292 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1294 for (i = 0; (i < units.length) && (val > mf); i++)
1297 subst = val.toFixed(pr) + ' ' + units[i];
1303 out += leftpart + subst;
1304 str = str.substr(m.length);