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);
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' || tl[0].type == 'checkbox'))
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 = obj.className.replace(/cbi-input-text/, '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;
508 // Retrigger validation in select
513 function cbi_combobox_init(id, values, def, man) {
514 var obj = document.getElementById(id);
515 cbi_bind(obj, "blur", function() {
516 cbi_combobox(id, values, def, man)
518 cbi_combobox(id, values, def, man);
521 function cbi_filebrowser(id, url, defpath) {
522 var field = document.getElementById(id);
523 var browser = window.open(
524 url + ( field.value || defpath || '' ) + '?field=' + id,
525 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
531 function cbi_browser_init(id, respath, url, defpath)
533 function cbi_browser_btnclick(e) {
534 cbi_filebrowser(id, url, defpath);
538 var field = document.getElementById(id);
540 var btn = document.createElement('img');
541 btn.className = 'cbi-image-button';
542 btn.src = respath + '/cbi/folder.gif';
543 field.parentNode.insertBefore(btn, field.nextSibling);
545 cbi_bind(btn, 'click', cbi_browser_btnclick);
548 function cbi_dynlist_init(name, respath, datatype, optional, url, defpath, choices)
550 var input0 = document.getElementsByName(name)[0];
551 var prefix = input0.name;
552 var parent = input0.parentNode;
553 var holder = input0.placeholder;
557 function cbi_dynlist_redraw(focus, add, del)
561 while (parent.firstChild)
563 var n = parent.firstChild;
564 var i = parseInt(n.index);
568 if (n.nodeName.toLowerCase() == 'input')
569 values.push(n.value || '');
570 else if (n.nodeName.toLowerCase() == 'select')
571 values[values.length-1] = n.options[n.selectedIndex].value;
574 parent.removeChild(n);
580 values.splice(focus, 0, '');
582 else if (values.length == 0)
588 for (var i = 0; i < values.length; i++)
590 var t = document.createElement('input');
591 t.id = prefix + '.' + (i+1);
596 t.className = 'cbi-input-text';
598 if (i == 0 && holder)
600 t.placeholder = holder;
603 var b = document.createElement('img');
604 b.src = respath + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
605 b.className = 'cbi-image-button';
607 parent.appendChild(t);
608 parent.appendChild(b);
609 if (datatype == 'file')
611 cbi_browser_init(t.id, respath, url, defpath);
614 parent.appendChild(document.createElement('br'));
618 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
623 cbi_combobox_init(t.id, choices[0], '', choices[1]);
626 cbi_bind(b, 'keydown', cbi_dynlist_keydown);
627 cbi_bind(b, 'keypress', cbi_dynlist_keypress);
629 if (i == focus || -i == focus)
634 cbi_bind(t, 'keydown', cbi_dynlist_keydown);
635 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
641 else if (-i == focus)
645 /* force cursor to end */
652 cbi_bind(b, 'click', cbi_dynlist_btnclick);
656 function cbi_dynlist_keypress(ev)
658 ev = ev ? ev : window.event;
660 var se = ev.target ? ev.target : ev.srcElement;
662 if (se.nodeType == 3)
667 /* backspace, delete */
670 if (se.value.length == 0)
672 if (ev.preventDefault)
680 /* enter, arrow up, arrow down */
684 if (ev.preventDefault)
693 function cbi_dynlist_keydown(ev)
695 ev = ev ? ev : window.event;
697 var se = ev.target ? ev.target : ev.srcElement;
699 if (se.nodeType == 3)
702 var prev = se.previousSibling;
703 while (prev && prev.name != name)
704 prev = prev.previousSibling;
706 var next = se.nextSibling;
707 while (next && next.name != name)
708 next = next.nextSibling;
710 /* advance one further in combobox case */
711 if (next && next.nextSibling.name == name)
712 next = next.nextSibling;
716 /* backspace, delete */
719 var del = (se.nodeName.toLowerCase() == 'select')
720 ? true : (se.value.length == 0);
724 if (ev.preventDefault)
727 var focus = se.index;
731 cbi_dynlist_redraw(focus, -1, se.index);
740 cbi_dynlist_redraw(-1, se.index, -1);
761 function cbi_dynlist_btnclick(ev)
763 ev = ev ? ev : window.event;
765 var se = ev.target ? ev.target : ev.srcElement;
766 var input = se.previousSibling;
767 while (input && input.name != name) {
768 input = input.previousSibling;
771 if (se.src.indexOf('remove') > -1)
775 cbi_dynlist_keydown({
782 cbi_dynlist_keydown({
791 cbi_dynlist_redraw(NaN, -1, -1);
794 //Hijacks the CBI form to send via XHR (requires Prototype)
795 function cbi_hijack_forms(layer, win, fail, load) {
796 var forms = layer.getElementsByTagName('form');
797 for (var i=0; i<forms.length; i++) {
798 $(forms[i]).observe('submit', function(event) {
799 // Prevent the form from also submitting the regular way
803 event.element().request({
816 function cbi_t_add(section, tab) {
817 var t = document.getElementById('tab.' + section + '.' + tab);
818 var c = document.getElementById('container.' + section + '.' + tab);
821 cbi_t[section] = (cbi_t[section] || [ ]);
822 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
826 function cbi_t_switch(section, tab) {
827 if( cbi_t[section] && cbi_t[section][tab] ) {
828 var o = cbi_t[section][tab];
829 var h = document.getElementById('tab.' + section);
830 for( var tid in cbi_t[section] ) {
831 var o2 = cbi_t[section][tid];
832 if( o.tab.id != o2.tab.id ) {
833 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
834 o2.container.style.display = 'none';
838 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
839 o2.container.style.display = 'block';
846 function cbi_t_update() {
850 for( var sid in cbi_t )
851 for( var tid in cbi_t[sid] )
853 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
854 cbi_t[sid][tid].tab.style.display = 'none';
856 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
857 cbi_t[sid][tid].tab.style.display = '';
859 var t = cbi_t[sid][tid].tab;
860 t.className += ' cbi-tab-highlighted';
864 cbi_tag_last(cbi_t[sid][tid].container);
868 if( hl_tabs.length > 0 )
869 window.setTimeout(function() {
870 for( var i = 0; i < hl_tabs.length; i++ )
871 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
878 function cbi_validate_form(form, errmsg)
880 /* if triggered by a section removal or addition, don't validate */
881 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
884 if( form.cbi_validators )
886 for( var i = 0; i < form.cbi_validators.length; i++ )
888 var validator = form.cbi_validators[i];
889 if( !validator() && errmsg )
900 function cbi_validate_reset(form)
903 function() { cbi_validate_form(form, null) }, 100
909 function cbi_validate_compile(code)
918 for (var i = 0; i < code.length; i++)
926 switch (code.charCodeAt(i))
938 var label = code.substring(pos, i);
939 label = label.replace(/\\(.)/g, '$1');
940 label = label.replace(/^[ \t]+/g, '');
941 label = label.replace(/[ \t]+$/g, '');
943 if (label && !isNaN(label))
945 stack.push(parseFloat(label));
947 else if (label.match(/^(['"]).*\1$/))
949 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
951 else if (typeof cbi_validators[label] == 'function')
953 stack.push(cbi_validators[label]);
958 throw "Syntax error, unhandled token '"+label+"'";
963 depth += (code.charCodeAt(i) == 40);
969 if (typeof stack[stack.length-2] != 'function')
970 throw "Syntax error, argument list follows non-function";
972 stack[stack.length-1] =
973 arguments.callee(code.substring(pos, i));
984 function cbi_validate_field(cbid, optional, type)
986 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
987 var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
989 if (field && vstack && typeof vstack[0] == "function")
991 var validator = function()
996 field.className = field.className.replace(/ cbi-input-invalid/g, '');
999 var value = (field.options && field.options.selectedIndex > -1)
1000 ? field.options[field.options.selectedIndex].value : field.value;
1002 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
1005 field.className += ' cbi-input-invalid';
1013 if( ! field.form.cbi_validators )
1014 field.form.cbi_validators = [ ];
1016 field.form.cbi_validators.push(validator);
1018 cbi_bind(field, "blur", validator);
1019 cbi_bind(field, "keyup", validator);
1021 if (field.nodeName == 'SELECT')
1023 cbi_bind(field, "change", validator);
1024 cbi_bind(field, "click", validator);
1027 field.setAttribute("cbi_validate", validator);
1028 field.setAttribute("cbi_datatype", type);
1029 field.setAttribute("cbi_optional", (!!optional).toString());
1033 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1035 cbi_validate_field(fcbox, optional, type);
1039 function cbi_row_swap(elem, up, store)
1041 var tr = elem.parentNode;
1042 while (tr && tr.nodeName.toLowerCase() != 'tr')
1048 var table = tr.parentNode;
1049 while (table && table.nodeName.toLowerCase() != 'table')
1050 table = table.parentNode;
1056 var e = up ? table.rows.length : table.rows.length - 1;
1058 for (var idx = s; idx < e; idx++)
1060 if (table.rows[idx] == tr)
1063 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
1065 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
1072 for (idx = 2; idx < table.rows.length; idx++)
1074 table.rows[idx].className = table.rows[idx].className.replace(
1075 /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
1078 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
1079 ids.push(RegExp.$1);
1082 var input = document.getElementById(store);
1084 input.value = ids.join(' ');
1089 function cbi_tag_last(container)
1093 for (var i = 0; i < container.childNodes.length; i++)
1095 var c = container.childNodes[i];
1096 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1098 c.className = c.className.replace(/ cbi-value-last$/, '');
1105 last.className += ' cbi-value-last';
1109 String.prototype.serialize = function()
1126 for( var i = 0; i < o.length; i++ )
1127 s += (s ? ', ' : '') + String.serialize(o[i]);
1129 return '[ ' + s + ' ]';
1138 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1140 return '{ ' + s + ' }';
1147 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1148 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1152 return '"' + o + '"';
1157 return o.toString();
1161 String.prototype.format = function()
1166 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1167 var quot_esc = [/"/g, '"', /'/g, '''];
1169 function esc(s, r) {
1170 for( var i = 0; i < r.length; i += 2 )
1171 s = s.replace(r[i], r[i+1]);
1177 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1178 var a = b = [], numSubstitutions = 0, numMatches = 0;
1180 while( a = re.exec(str) )
1183 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1184 var pPrecision = a[6], pType = a[7];
1194 if (numSubstitutions < arguments.length)
1196 var param = arguments[numSubstitutions++];
1199 if (pPad && pPad.substr(0,1) == "'")
1200 pad = leftpart.substr(1,1);
1204 var justifyRight = true;
1205 if (pJustify && pJustify === "-")
1206 justifyRight = false;
1210 minLength = parseInt(pMinLength);
1213 if (pPrecision && pType == 'f')
1214 precision = parseInt(pPrecision.substring(1));
1221 subst = (parseInt(param) || 0).toString(2);
1225 subst = String.fromCharCode(parseInt(param) || 0);
1229 subst = (parseInt(param) || 0);
1233 subst = Math.abs(parseInt(param) || 0);
1237 subst = (precision > -1)
1238 ? ((parseFloat(param) || 0.0)).toFixed(precision)
1239 : (parseFloat(param) || 0.0);
1243 subst = (parseInt(param) || 0).toString(8);
1251 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1255 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1259 subst = esc(param, html_esc);
1263 subst = esc(param, quot_esc);
1267 subst = String.serialize(param);
1274 var ts = (param || 0);
1277 tm = Math.floor(ts / 60);
1282 th = Math.floor(tm / 60);
1287 td = Math.floor(th / 24);
1292 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1293 : String.format('%dh %dm %ds', th, tm, ts);
1298 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1299 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1302 var val = parseFloat(param || 0);
1303 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1305 for (i = 0; (i < units.length) && (val > mf); i++)
1308 subst = val.toFixed(pr) + ' ' + units[i];
1314 out += leftpart + subst;
1315 str = str.substr(m.length);
1321 String.prototype.nobr = function()
1323 return this.replace(/[\s\n]+/g, ' ');
1326 String.serialize = function()
1329 for (var i = 1; i < arguments.length; i++)
1330 a.push(arguments[i]);
1331 return ''.serialize.apply(arguments[0], a);
1334 String.format = function()
1337 for (var i = 1; i < arguments.length; i++)
1338 a.push(arguments[i]);
1339 return ''.format.apply(arguments[0], a);
1342 String.nobr = function()
1345 for (var i = 1; i < arguments.length; i++)
1346 a.push(arguments[i]);
1347 return ''.nobr.apply(arguments[0], a);