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))
276 function cbi_d_add(field, dep, next) {
277 var obj = document.getElementById(field);
280 for (var i=0; i<cbi_d.length; i++) {
281 if (cbi_d[i].id == field) {
290 "parent": obj.parentNode.id,
294 cbi_d.unshift(entry);
300 function cbi_d_checkvalue(target, ref) {
301 var t = document.getElementById(target);
305 var tl = document.getElementsByName(target);
307 if( tl.length > 0 && tl[0].type == 'radio' )
308 for( var i = 0; i < tl.length; i++ )
309 if( tl[i].checked ) {
314 value = value ? value : "";
315 } else if (!t.value) {
320 if (t.type == "checkbox") {
321 value = t.checked ? value : "";
325 return (value == ref)
328 function cbi_d_check(deps) {
331 for (var i=0; i<deps.length; i++) {
334 for (var j in deps[i]) {
335 if (j == "!reverse") {
337 } else if (j == "!default") {
341 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
351 function cbi_d_update() {
353 for (var i=0; i<cbi_d.length; i++) {
354 var entry = cbi_d[i];
355 var next = document.getElementById(entry.next)
356 var node = document.getElementById(entry.id)
357 var parent = document.getElementById(entry.parent)
359 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
360 node.parentNode.removeChild(node);
363 cbi_c[entry.parent]--;
364 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
366 parent.appendChild(entry.node);
368 next.parentNode.insertBefore(entry.node, next);
372 cbi_c[entry.parent]++;
376 if (entry && entry.parent) {
378 cbi_tag_last(parent);
386 function cbi_bind(obj, type, callback, mode) {
387 if (!obj.addEventListener) {
388 obj.attachEvent('on' + type,
390 var e = window.event;
392 if (!e.target && e.srcElement)
393 e.target = e.srcElement;
395 return !!callback(e);
399 obj.addEventListener(type, callback, !!mode);
404 function cbi_combobox(id, values, def, man) {
405 var selid = "cbi.combobox." + id;
406 if (document.getElementById(selid)) {
410 var obj = document.getElementById(id)
411 var sel = document.createElement("select");
413 sel.className = 'cbi-input-select';
415 if (obj.nextSibling) {
416 obj.parentNode.insertBefore(sel, obj.nextSibling);
418 obj.parentNode.appendChild(sel);
421 var dt = obj.getAttribute('cbi_datatype');
422 var op = obj.getAttribute('cbi_optional');
425 cbi_validate_field(sel, op == 'true', dt);
427 if (!values[obj.value]) {
428 if (obj.value == "") {
429 var optdef = document.createElement("option");
431 optdef.appendChild(document.createTextNode(def));
432 sel.appendChild(optdef);
434 var opt = document.createElement("option");
435 opt.value = obj.value;
436 opt.selected = "selected";
437 opt.appendChild(document.createTextNode(obj.value));
438 sel.appendChild(opt);
442 for (var i in values) {
443 var opt = document.createElement("option");
446 if (obj.value == i) {
447 opt.selected = "selected";
450 opt.appendChild(document.createTextNode(values[i]));
451 sel.appendChild(opt);
454 var optman = document.createElement("option");
456 optman.appendChild(document.createTextNode(man));
457 sel.appendChild(optman);
459 obj.style.display = "none";
461 cbi_bind(sel, "change", function() {
462 if (sel.selectedIndex == sel.options.length - 1) {
463 obj.style.display = "inline";
464 sel.parentNode.removeChild(sel);
467 obj.value = sel.options[sel.selectedIndex].value;
478 function cbi_combobox_init(id, values, def, man) {
479 var obj = document.getElementById(id);
480 cbi_bind(obj, "blur", function() {
481 cbi_combobox(id, values, def, man)
483 cbi_combobox(id, values, def, man);
486 function cbi_filebrowser(id, url, defpath) {
487 var field = document.getElementById(id);
488 var browser = window.open(
489 url + ( field.value || defpath || '' ) + '?field=' + id,
490 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
496 function cbi_browser_init(id, respath, url, defpath)
498 function cbi_browser_btnclick(e) {
499 cbi_filebrowser(id, url, defpath);
503 var field = document.getElementById(id);
505 var btn = document.createElement('img');
506 btn.className = 'cbi-image-button';
507 btn.src = respath + '/cbi/folder.gif';
508 field.parentNode.insertBefore(btn, field.nextSibling);
510 cbi_bind(btn, 'click', cbi_browser_btnclick);
513 function cbi_dynlist_init(name, respath, datatype, optional, choices)
515 var input0 = document.getElementsByName(name)[0];
516 var prefix = input0.name;
517 var parent = input0.parentNode;
518 var holder = input0.placeholder;
522 function cbi_dynlist_redraw(focus, add, del)
526 while (parent.firstChild)
528 var n = parent.firstChild;
529 var i = parseInt(n.index);
533 if (n.nodeName.toLowerCase() == 'input')
534 values.push(n.value || '');
535 else if (n.nodeName.toLowerCase() == 'select')
536 values[values.length-1] = n.options[n.selectedIndex].value;
539 parent.removeChild(n);
545 values.splice(focus, 0, '');
547 else if (values.length == 0)
553 for (var i = 0; i < values.length; i++)
555 var t = document.createElement('input');
556 t.id = prefix + '.' + (i+1);
561 t.className = 'cbi-input-text';
563 if (i == 0 && holder)
565 t.placeholder = holder;
568 var b = document.createElement('img');
569 b.src = respath + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
570 b.className = 'cbi-image-button';
572 parent.appendChild(t);
573 parent.appendChild(b);
574 parent.appendChild(document.createElement('br'));
578 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
583 cbi_combobox_init(t.id, choices[0], '', choices[1]);
584 t.nextSibling.index = i;
586 cbi_bind(t.nextSibling, 'keydown', cbi_dynlist_keydown);
587 cbi_bind(t.nextSibling, 'keypress', cbi_dynlist_keypress);
589 if (i == focus || -i == focus)
590 t.nextSibling.focus();
594 cbi_bind(t, 'keydown', cbi_dynlist_keydown);
595 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
601 else if (-i == focus)
605 /* force cursor to end */
612 cbi_bind(b, 'click', cbi_dynlist_btnclick);
616 function cbi_dynlist_keypress(ev)
618 ev = ev ? ev : window.event;
620 var se = ev.target ? ev.target : ev.srcElement;
622 if (se.nodeType == 3)
627 /* backspace, delete */
630 if (se.value.length == 0)
632 if (ev.preventDefault)
640 /* enter, arrow up, arrow down */
644 if (ev.preventDefault)
653 function cbi_dynlist_keydown(ev)
655 ev = ev ? ev : window.event;
657 var se = ev.target ? ev.target : ev.srcElement;
659 if (se.nodeType == 3)
662 var prev = se.previousSibling;
663 while (prev && prev.name != name)
664 prev = prev.previousSibling;
666 var next = se.nextSibling;
667 while (next && next.name != name)
668 next = next.nextSibling;
670 /* advance one further in combobox case */
671 if (next && next.nextSibling.name == name)
672 next = next.nextSibling;
676 /* backspace, delete */
679 var del = (se.nodeName.toLowerCase() == 'select')
680 ? true : (se.value.length == 0);
684 if (ev.preventDefault)
687 var focus = se.index;
691 cbi_dynlist_redraw(focus, -1, se.index);
700 cbi_dynlist_redraw(-1, se.index, -1);
721 function cbi_dynlist_btnclick(ev)
723 ev = ev ? ev : window.event;
725 var se = ev.target ? ev.target : ev.srcElement;
727 if (se.src.indexOf('remove') > -1)
729 se.previousSibling.value = '';
731 cbi_dynlist_keydown({
732 target: se.previousSibling,
738 cbi_dynlist_keydown({
739 target: se.previousSibling,
747 cbi_dynlist_redraw(-1, -1, -1);
750 //Hijacks the CBI form to send via XHR (requires Prototype)
751 function cbi_hijack_forms(layer, win, fail, load) {
752 var forms = layer.getElementsByTagName('form');
753 for (var i=0; i<forms.length; i++) {
754 $(forms[i]).observe('submit', function(event) {
755 // Prevent the form from also submitting the regular way
759 event.element().request({
772 function cbi_t_add(section, tab) {
773 var t = document.getElementById('tab.' + section + '.' + tab);
774 var c = document.getElementById('container.' + section + '.' + tab);
777 cbi_t[section] = (cbi_t[section] || [ ]);
778 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
782 function cbi_t_switch(section, tab) {
783 if( cbi_t[section] && cbi_t[section][tab] ) {
784 var o = cbi_t[section][tab];
785 var h = document.getElementById('tab.' + section);
786 for( var tid in cbi_t[section] ) {
787 var o2 = cbi_t[section][tid];
788 if( o.tab.id != o2.tab.id ) {
789 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
790 o2.container.style.display = 'none';
794 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
795 o2.container.style.display = 'block';
802 function cbi_t_update() {
806 for( var sid in cbi_t )
807 for( var tid in cbi_t[sid] )
809 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
810 cbi_t[sid][tid].tab.style.display = 'none';
812 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
813 cbi_t[sid][tid].tab.style.display = '';
815 var t = cbi_t[sid][tid].tab;
816 t.className += ' cbi-tab-highlighted';
820 cbi_tag_last(cbi_t[sid][tid].container);
824 if( hl_tabs.length > 0 )
825 window.setTimeout(function() {
826 for( var i = 0; i < hl_tabs.length; i++ )
827 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
834 function cbi_validate_form(form, errmsg)
836 /* if triggered by a section removal or addition, don't validate */
837 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
840 if( form.cbi_validators )
842 for( var i = 0; i < form.cbi_validators.length; i++ )
844 var validator = form.cbi_validators[i];
845 if( !validator() && errmsg )
856 function cbi_validate_reset(form)
859 function() { cbi_validate_form(form, null) }, 100
865 function cbi_validate_compile(code)
874 for (var i = 0; i < code.length; i++)
882 switch (code.charCodeAt(i))
894 var label = code.substring(pos, i);
895 label = label.replace(/\\(.)/g, '$1');
896 label = label.replace(/^[ \t]+/g, '');
897 label = label.replace(/[ \t]+$/g, '');
899 if (label && !isNaN(label))
901 stack.push(parseFloat(label));
903 else if (label.match(/^(['"]).*\1$/))
905 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
907 else if (typeof cbi_validators[label] == 'function')
909 stack.push(cbi_validators[label]);
914 throw "Syntax error, unhandled token '"+label+"'";
919 depth += (code.charCodeAt(i) == 40);
925 if (typeof stack[stack.length-2] != 'function')
926 throw "Syntax error, argument list follows non-function";
928 stack[stack.length-1] =
929 arguments.callee(code.substring(pos, i));
940 function cbi_validate_field(cbid, optional, type)
942 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
943 var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
945 if (field && vstack && typeof vstack[0] == "function")
947 var validator = function()
952 field.className = field.className.replace(/ cbi-input-invalid/g, '');
955 var value = (field.options && field.options.selectedIndex > -1)
956 ? field.options[field.options.selectedIndex].value : field.value;
958 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
961 field.className += ' cbi-input-invalid';
969 if( ! field.form.cbi_validators )
970 field.form.cbi_validators = [ ];
972 field.form.cbi_validators.push(validator);
974 cbi_bind(field, "blur", validator);
975 cbi_bind(field, "keyup", validator);
977 if (field.nodeName == 'SELECT')
979 cbi_bind(field, "change", validator);
980 cbi_bind(field, "click", validator);
983 field.setAttribute("cbi_validate", validator);
984 field.setAttribute("cbi_datatype", type);
985 field.setAttribute("cbi_optional", (!!optional).toString());
989 var fcbox = document.getElementById('cbi.combobox.' + field.id);
991 cbi_validate_field(fcbox, optional, type);
995 function cbi_row_swap(elem, up, store)
997 var tr = elem.parentNode;
998 while (tr && tr.nodeName.toLowerCase() != 'tr')
1004 var table = tr.parentNode;
1005 while (table && table.nodeName.toLowerCase() != 'table')
1006 table = table.parentNode;
1012 var e = up ? table.rows.length : table.rows.length - 1;
1014 for (var idx = s; idx < e; idx++)
1016 if (table.rows[idx] == tr)
1019 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
1021 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
1028 for (idx = 2; idx < table.rows.length; idx++)
1030 table.rows[idx].className = table.rows[idx].className.replace(
1031 /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
1034 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
1035 ids.push(RegExp.$1);
1038 var input = document.getElementById(store);
1040 input.value = ids.join(' ');
1045 function cbi_tag_last(container)
1049 for (var i = 0; i < container.childNodes.length; i++)
1051 var c = container.childNodes[i];
1052 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1054 c.className = c.className.replace(/ cbi-value-last$/, '');
1061 last.className += ' cbi-value-last';
1065 if( ! String.serialize )
1066 String.serialize = function(o)
1082 for( var i = 0; i < o.length; i++ )
1083 s += (s ? ', ' : '') + String.serialize(o[i]);
1085 return '[ ' + s + ' ]';
1094 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1096 return '{ ' + s + ' }';
1103 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1104 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1108 return '"' + o + '"';
1113 return o.toString();
1118 if( ! String.format )
1119 String.format = function()
1121 if (!arguments || arguments.length < 1 || !RegExp)
1124 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1125 var quot_esc = [/"/g, '"', /'/g, '''];
1127 function esc(s, r) {
1128 for( var i = 0; i < r.length; i += 2 )
1129 s = s.replace(r[i], r[i+1]);
1133 var str = arguments[0];
1135 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1136 var a = b = [], numSubstitutions = 0, numMatches = 0;
1138 while( a = re.exec(str) )
1141 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1142 var pPrecision = a[6], pType = a[7];
1152 if (numSubstitutions++ < arguments.length)
1154 var param = arguments[numSubstitutions];
1157 if (pPad && pPad.substr(0,1) == "'")
1158 pad = leftpart.substr(1,1);
1162 var justifyRight = true;
1163 if (pJustify && pJustify === "-")
1164 justifyRight = false;
1168 minLength = parseInt(pMinLength);
1171 if (pPrecision && pType == 'f')
1172 precision = parseInt(pPrecision.substring(1));
1179 subst = (parseInt(param) || 0).toString(2);
1183 subst = String.fromCharCode(parseInt(param) || 0);
1187 subst = (parseInt(param) || 0);
1191 subst = Math.abs(parseInt(param) || 0);
1195 subst = (precision > -1)
1196 ? ((parseFloat(param) || 0.0)).toFixed(precision)
1197 : (parseFloat(param) || 0.0);
1201 subst = (parseInt(param) || 0).toString(8);
1209 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1213 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1217 subst = esc(param, html_esc);
1221 subst = esc(param, quot_esc);
1225 subst = String.serialize(param);
1232 var ts = (param || 0);
1235 tm = Math.floor(ts / 60);
1240 th = Math.floor(tm / 60);
1245 td = Math.floor(th / 24);
1250 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1251 : String.format('%dh %dm %ds', th, tm, ts);
1256 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1257 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1260 var val = parseFloat(param || 0);
1261 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1263 for (i = 0; (i < units.length) && (val > mf); i++)
1266 subst = val.toFixed(pr) + ' ' + units[i];
1272 out += leftpart + subst;
1273 str = str.substr(m.length);