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))
221 for (var i = 0; i < arguments.length; i += 2)
223 if (typeof arguments[i] != 'function')
225 if (arguments[i] == this)
229 else if (arguments[i].apply(this, arguments[i+1]))
239 for (var i = 0; i < arguments.length; i += 2)
241 if (typeof arguments[i] != 'function')
243 if (arguments[i] != this)
247 else if (!arguments[i].apply(this, arguments[i+1]))
257 return cbi_validators.or.apply(
258 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
261 'list': function(subvalidator, subargs)
263 if (typeof subvalidator != 'function')
266 var tokens = this.match(/[^ \t]+/g);
267 for (var i = 0; i < tokens.length; i++)
268 if (!subvalidator.apply(tokens[i], subargs))
273 'phonedigit': function()
275 return (this.match(/^[0-9\*#]+$/) != null);
280 function cbi_d_add(field, dep, next) {
281 var obj = document.getElementById(field);
284 for (var i=0; i<cbi_d.length; i++) {
285 if (cbi_d[i].id == field) {
294 "parent": obj.parentNode.id,
298 cbi_d.unshift(entry);
304 function cbi_d_checkvalue(target, ref) {
305 var t = document.getElementById(target);
309 var tl = document.getElementsByName(target);
311 if( tl.length > 0 && tl[0].type == 'radio' )
312 for( var i = 0; i < tl.length; i++ )
313 if( tl[i].checked ) {
318 value = value ? value : "";
319 } else if (!t.value) {
324 if (t.type == "checkbox") {
325 value = t.checked ? value : "";
329 return (value == ref)
332 function cbi_d_check(deps) {
335 for (var i=0; i<deps.length; i++) {
338 for (var j in deps[i]) {
339 if (j == "!reverse") {
341 } else if (j == "!default") {
345 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
355 function cbi_d_update() {
357 for (var i=0; i<cbi_d.length; i++) {
358 var entry = cbi_d[i];
359 var next = document.getElementById(entry.next)
360 var node = document.getElementById(entry.id)
361 var parent = document.getElementById(entry.parent)
363 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
364 node.parentNode.removeChild(node);
367 cbi_c[entry.parent]--;
368 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
370 parent.appendChild(entry.node);
372 next.parentNode.insertBefore(entry.node, next);
376 cbi_c[entry.parent]++;
380 if (entry && entry.parent) {
382 cbi_tag_last(parent);
390 function cbi_bind(obj, type, callback, mode) {
391 if (!obj.addEventListener) {
392 obj.attachEvent('on' + type,
394 var e = window.event;
396 if (!e.target && e.srcElement)
397 e.target = e.srcElement;
399 return !!callback(e);
403 obj.addEventListener(type, callback, !!mode);
408 function cbi_combobox(id, values, def, man) {
409 var selid = "cbi.combobox." + id;
410 if (document.getElementById(selid)) {
414 var obj = document.getElementById(id)
415 var sel = document.createElement("select");
417 sel.className = 'cbi-input-select';
419 if (obj.nextSibling) {
420 obj.parentNode.insertBefore(sel, obj.nextSibling);
422 obj.parentNode.appendChild(sel);
425 var dt = obj.getAttribute('cbi_datatype');
426 var op = obj.getAttribute('cbi_optional');
429 cbi_validate_field(sel, op == 'true', dt);
431 if (!values[obj.value]) {
432 if (obj.value == "") {
433 var optdef = document.createElement("option");
435 optdef.appendChild(document.createTextNode(def));
436 sel.appendChild(optdef);
438 var opt = document.createElement("option");
439 opt.value = obj.value;
440 opt.selected = "selected";
441 opt.appendChild(document.createTextNode(obj.value));
442 sel.appendChild(opt);
446 for (var i in values) {
447 var opt = document.createElement("option");
450 if (obj.value == i) {
451 opt.selected = "selected";
454 opt.appendChild(document.createTextNode(values[i]));
455 sel.appendChild(opt);
458 var optman = document.createElement("option");
460 optman.appendChild(document.createTextNode(man));
461 sel.appendChild(optman);
463 obj.style.display = "none";
465 cbi_bind(sel, "change", function() {
466 if (sel.selectedIndex == sel.options.length - 1) {
467 obj.style.display = "inline";
468 sel.parentNode.removeChild(sel);
471 obj.value = sel.options[sel.selectedIndex].value;
482 function cbi_combobox_init(id, values, def, man) {
483 var obj = document.getElementById(id);
484 cbi_bind(obj, "blur", function() {
485 cbi_combobox(id, values, def, man)
487 cbi_combobox(id, values, def, man);
490 function cbi_filebrowser(id, url, defpath) {
491 var field = document.getElementById(id);
492 var browser = window.open(
493 url + ( field.value || defpath || '' ) + '?field=' + id,
494 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
500 function cbi_browser_init(id, respath, url, defpath)
502 function cbi_browser_btnclick(e) {
503 cbi_filebrowser(id, url, defpath);
507 var field = document.getElementById(id);
509 var btn = document.createElement('img');
510 btn.className = 'cbi-image-button';
511 btn.src = respath + '/cbi/folder.gif';
512 field.parentNode.insertBefore(btn, field.nextSibling);
514 cbi_bind(btn, 'click', cbi_browser_btnclick);
517 function cbi_dynlist_init(name, respath, datatype, optional, choices)
519 var input0 = document.getElementsByName(name)[0];
520 var prefix = input0.name;
521 var parent = input0.parentNode;
522 var holder = input0.placeholder;
526 function cbi_dynlist_redraw(focus, add, del)
530 while (parent.firstChild)
532 var n = parent.firstChild;
533 var i = parseInt(n.index);
537 if (n.nodeName.toLowerCase() == 'input')
538 values.push(n.value || '');
539 else if (n.nodeName.toLowerCase() == 'select')
540 values[values.length-1] = n.options[n.selectedIndex].value;
543 parent.removeChild(n);
549 values.splice(focus, 0, '');
551 else if (values.length == 0)
557 for (var i = 0; i < values.length; i++)
559 var t = document.createElement('input');
560 t.id = prefix + '.' + (i+1);
565 t.className = 'cbi-input-text';
567 if (i == 0 && holder)
569 t.placeholder = holder;
572 var b = document.createElement('img');
573 b.src = respath + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
574 b.className = 'cbi-image-button';
576 parent.appendChild(t);
577 parent.appendChild(b);
578 parent.appendChild(document.createElement('br'));
582 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
587 cbi_combobox_init(t.id, choices[0], '', choices[1]);
588 t.nextSibling.index = i;
590 cbi_bind(t.nextSibling, 'keydown', cbi_dynlist_keydown);
591 cbi_bind(t.nextSibling, 'keypress', cbi_dynlist_keypress);
593 if (i == focus || -i == focus)
594 t.nextSibling.focus();
598 cbi_bind(t, 'keydown', cbi_dynlist_keydown);
599 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
605 else if (-i == focus)
609 /* force cursor to end */
616 cbi_bind(b, 'click', cbi_dynlist_btnclick);
620 function cbi_dynlist_keypress(ev)
622 ev = ev ? ev : window.event;
624 var se = ev.target ? ev.target : ev.srcElement;
626 if (se.nodeType == 3)
631 /* backspace, delete */
634 if (se.value.length == 0)
636 if (ev.preventDefault)
644 /* enter, arrow up, arrow down */
648 if (ev.preventDefault)
657 function cbi_dynlist_keydown(ev)
659 ev = ev ? ev : window.event;
661 var se = ev.target ? ev.target : ev.srcElement;
663 if (se.nodeType == 3)
666 var prev = se.previousSibling;
667 while (prev && prev.name != name)
668 prev = prev.previousSibling;
670 var next = se.nextSibling;
671 while (next && next.name != name)
672 next = next.nextSibling;
674 /* advance one further in combobox case */
675 if (next && next.nextSibling.name == name)
676 next = next.nextSibling;
680 /* backspace, delete */
683 var del = (se.nodeName.toLowerCase() == 'select')
684 ? true : (se.value.length == 0);
688 if (ev.preventDefault)
691 var focus = se.index;
695 cbi_dynlist_redraw(focus, -1, se.index);
704 cbi_dynlist_redraw(-1, se.index, -1);
725 function cbi_dynlist_btnclick(ev)
727 ev = ev ? ev : window.event;
729 var se = ev.target ? ev.target : ev.srcElement;
731 if (se.src.indexOf('remove') > -1)
733 se.previousSibling.value = '';
735 cbi_dynlist_keydown({
736 target: se.previousSibling,
742 cbi_dynlist_keydown({
743 target: se.previousSibling,
751 cbi_dynlist_redraw(NaN, -1, -1);
754 //Hijacks the CBI form to send via XHR (requires Prototype)
755 function cbi_hijack_forms(layer, win, fail, load) {
756 var forms = layer.getElementsByTagName('form');
757 for (var i=0; i<forms.length; i++) {
758 $(forms[i]).observe('submit', function(event) {
759 // Prevent the form from also submitting the regular way
763 event.element().request({
776 function cbi_t_add(section, tab) {
777 var t = document.getElementById('tab.' + section + '.' + tab);
778 var c = document.getElementById('container.' + section + '.' + tab);
781 cbi_t[section] = (cbi_t[section] || [ ]);
782 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
786 function cbi_t_switch(section, tab) {
787 if( cbi_t[section] && cbi_t[section][tab] ) {
788 var o = cbi_t[section][tab];
789 var h = document.getElementById('tab.' + section);
790 for( var tid in cbi_t[section] ) {
791 var o2 = cbi_t[section][tid];
792 if( o.tab.id != o2.tab.id ) {
793 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
794 o2.container.style.display = 'none';
798 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
799 o2.container.style.display = 'block';
806 function cbi_t_update() {
810 for( var sid in cbi_t )
811 for( var tid in cbi_t[sid] )
813 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
814 cbi_t[sid][tid].tab.style.display = 'none';
816 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
817 cbi_t[sid][tid].tab.style.display = '';
819 var t = cbi_t[sid][tid].tab;
820 t.className += ' cbi-tab-highlighted';
824 cbi_tag_last(cbi_t[sid][tid].container);
828 if( hl_tabs.length > 0 )
829 window.setTimeout(function() {
830 for( var i = 0; i < hl_tabs.length; i++ )
831 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
838 function cbi_validate_form(form, errmsg)
840 /* if triggered by a section removal or addition, don't validate */
841 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
844 if( form.cbi_validators )
846 for( var i = 0; i < form.cbi_validators.length; i++ )
848 var validator = form.cbi_validators[i];
849 if( !validator() && errmsg )
860 function cbi_validate_reset(form)
863 function() { cbi_validate_form(form, null) }, 100
869 function cbi_validate_compile(code)
878 for (var i = 0; i < code.length; i++)
886 switch (code.charCodeAt(i))
898 var label = code.substring(pos, i);
899 label = label.replace(/\\(.)/g, '$1');
900 label = label.replace(/^[ \t]+/g, '');
901 label = label.replace(/[ \t]+$/g, '');
903 if (label && !isNaN(label))
905 stack.push(parseFloat(label));
907 else if (label.match(/^(['"]).*\1$/))
909 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
911 else if (typeof cbi_validators[label] == 'function')
913 stack.push(cbi_validators[label]);
918 throw "Syntax error, unhandled token '"+label+"'";
923 depth += (code.charCodeAt(i) == 40);
929 if (typeof stack[stack.length-2] != 'function')
930 throw "Syntax error, argument list follows non-function";
932 stack[stack.length-1] =
933 arguments.callee(code.substring(pos, i));
944 function cbi_validate_field(cbid, optional, type)
946 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
947 var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
949 if (field && vstack && typeof vstack[0] == "function")
951 var validator = function()
956 field.className = field.className.replace(/ cbi-input-invalid/g, '');
959 var value = (field.options && field.options.selectedIndex > -1)
960 ? field.options[field.options.selectedIndex].value : field.value;
962 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
965 field.className += ' cbi-input-invalid';
973 if( ! field.form.cbi_validators )
974 field.form.cbi_validators = [ ];
976 field.form.cbi_validators.push(validator);
978 cbi_bind(field, "blur", validator);
979 cbi_bind(field, "keyup", validator);
981 if (field.nodeName == 'SELECT')
983 cbi_bind(field, "change", validator);
984 cbi_bind(field, "click", validator);
987 field.setAttribute("cbi_validate", validator);
988 field.setAttribute("cbi_datatype", type);
989 field.setAttribute("cbi_optional", (!!optional).toString());
993 var fcbox = document.getElementById('cbi.combobox.' + field.id);
995 cbi_validate_field(fcbox, optional, type);
999 function cbi_row_swap(elem, up, store)
1001 var tr = elem.parentNode;
1002 while (tr && tr.nodeName.toLowerCase() != 'tr')
1008 var table = tr.parentNode;
1009 while (table && table.nodeName.toLowerCase() != 'table')
1010 table = table.parentNode;
1016 var e = up ? table.rows.length : table.rows.length - 1;
1018 for (var idx = s; idx < e; idx++)
1020 if (table.rows[idx] == tr)
1023 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
1025 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
1032 for (idx = 2; idx < table.rows.length; idx++)
1034 table.rows[idx].className = table.rows[idx].className.replace(
1035 /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
1038 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
1039 ids.push(RegExp.$1);
1042 var input = document.getElementById(store);
1044 input.value = ids.join(' ');
1049 function cbi_tag_last(container)
1053 for (var i = 0; i < container.childNodes.length; i++)
1055 var c = container.childNodes[i];
1056 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1058 c.className = c.className.replace(/ cbi-value-last$/, '');
1065 last.className += ' cbi-value-last';
1069 if( ! String.serialize )
1070 String.serialize = function(o)
1086 for( var i = 0; i < o.length; i++ )
1087 s += (s ? ', ' : '') + String.serialize(o[i]);
1089 return '[ ' + s + ' ]';
1098 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1100 return '{ ' + s + ' }';
1107 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1108 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1112 return '"' + o + '"';
1117 return o.toString();
1122 if( ! String.format )
1123 String.format = function()
1125 if (!arguments || arguments.length < 1 || !RegExp)
1128 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1129 var quot_esc = [/"/g, '"', /'/g, '''];
1131 function esc(s, r) {
1132 for( var i = 0; i < r.length; i += 2 )
1133 s = s.replace(r[i], r[i+1]);
1137 var str = arguments[0];
1139 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1140 var a = b = [], numSubstitutions = 0, numMatches = 0;
1142 while( a = re.exec(str) )
1145 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1146 var pPrecision = a[6], pType = a[7];
1156 if (numSubstitutions++ < arguments.length)
1158 var param = arguments[numSubstitutions];
1161 if (pPad && pPad.substr(0,1) == "'")
1162 pad = leftpart.substr(1,1);
1166 var justifyRight = true;
1167 if (pJustify && pJustify === "-")
1168 justifyRight = false;
1172 minLength = parseInt(pMinLength);
1175 if (pPrecision && pType == 'f')
1176 precision = parseInt(pPrecision.substring(1));
1183 subst = (parseInt(param) || 0).toString(2);
1187 subst = String.fromCharCode(parseInt(param) || 0);
1191 subst = (parseInt(param) || 0);
1195 subst = Math.abs(parseInt(param) || 0);
1199 subst = (precision > -1)
1200 ? ((parseFloat(param) || 0.0)).toFixed(precision)
1201 : (parseFloat(param) || 0.0);
1205 subst = (parseInt(param) || 0).toString(8);
1213 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1217 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1221 subst = esc(param, html_esc);
1225 subst = esc(param, quot_esc);
1229 subst = String.serialize(param);
1236 var ts = (param || 0);
1239 tm = Math.floor(ts / 60);
1244 th = Math.floor(tm / 60);
1249 td = Math.floor(th / 24);
1254 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1255 : String.format('%dh %dm %ds', th, tm, ts);
1260 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1261 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1264 var val = parseFloat(param || 0);
1265 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1267 for (i = 0; (i < units.length) && (val > mf); i++)
1270 subst = val.toFixed(pr) + ' ' + units[i];
1276 out += leftpart + subst;
1277 str = str.substr(m.length);