2 LuCI - Lua Configuration Interface
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008-2010 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 = {
20 'integer': function(v)
22 return (v.match(/^-?[0-9]+$/) != null);
25 'uinteger': function(v)
27 return (cbi_validators.integer(v) && (v >= 0));
32 return !isNaN(parseFloat(v));
37 return (cbi_validators['float'](v) && (v >= 0));
42 return cbi_validators.ip4addr(v) || cbi_validators.ip6addr(v);
45 'ip4addr': function(v)
47 if( v.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)(\/(\d+))?$/) )
49 return (RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
50 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
51 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
52 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
53 (!RegExp.$5 || ((RegExp.$6 >= 0) && (RegExp.$6 <= 32)))
60 'ip6addr': function(v)
62 if( v.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/) )
64 if( !RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)) )
73 if( addr.indexOf('.') > 0 )
75 var off = addr.lastIndexOf(':');
77 if( !(off && cbi_validators.ip4addr(addr.substr(off+1))) )
80 addr = addr.substr(0, off) + ':0:0';
83 if( addr.indexOf('::') >= 0 )
88 for( var i = 1; i < (addr.length-1); i++ )
89 if( addr.charAt(i) == ':' )
95 for( var i = 0; i < (7 - colons); i++ )
98 if (addr.match(/^(.*?)::(.*?)$/))
99 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
100 (RegExp.$2 ? ':' + RegExp.$2 : '');
103 return (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null);
112 return cbi_validators.integer(v) && (v >= 0) && (v <= 65535);
115 'portrange': function(v)
117 if( v.match(/^(\d+)-(\d+)$/) )
122 return cbi_validators.port(p1) &&
123 cbi_validators.port(p2) &&
124 (parseInt(p1) <= parseInt(p2))
129 return cbi_validators.port(v);
133 'macaddr': function(v)
135 return (v.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
140 return cbi_validators.hostname(v) || cbi_validators.ipaddr(v);
143 'hostname': function(v)
144 { if ( v.length <= 253 )
145 return (v.match(/^[a-zA-Z0-9][a-zA-Z0-9\-.]*[a-zA-Z0-9]$/) != null);
148 'wpakey': function(v)
151 return (v.match(/^[a-fA-F0-9]{64}$/) != null);
153 return (v.length >= 8) && (v.length <= 63);
156 'wepkey': function(v)
158 if( v.substr(0,2) == 's:' )
161 if( (v.length == 10) || (v.length == 26) )
162 return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
164 return (v.length == 5) || (v.length == 13);
167 'uciname': function(v)
169 return (v.match(/^[a-zA-Z0-9_]+$/) != null);
172 'range': function(v, args)
174 var min = parseInt(args[0]);
175 var max = parseInt(args[1]);
176 var val = parseInt(v);
178 if (!isNaN(min) && !isNaN(max) && !isNaN(val))
179 return ((val >= min) && (val <= max));
186 function cbi_d_add(field, dep, next) {
187 var obj = document.getElementById(field);
190 for (var i=0; i<cbi_d.length; i++) {
191 if (cbi_d[i].id == field) {
200 "parent": obj.parentNode.id,
204 cbi_d.unshift(entry);
210 function cbi_d_checkvalue(target, ref) {
211 var t = document.getElementById(target);
215 var tl = document.getElementsByName(target);
217 if( tl.length > 0 && tl[0].type == 'radio' )
218 for( var i = 0; i < tl.length; i++ )
219 if( tl[i].checked ) {
224 value = value ? value : "";
225 } else if (!t.value) {
230 if (t.type == "checkbox") {
231 value = t.checked ? value : "";
235 return (value == ref)
238 function cbi_d_check(deps) {
241 for (var i=0; i<deps.length; i++) {
244 for (var j in deps[i]) {
245 if (j == "!reverse") {
247 } else if (j == "!default") {
251 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
261 function cbi_d_update() {
263 for (var i=0; i<cbi_d.length; i++) {
264 var entry = cbi_d[i];
265 var next = document.getElementById(entry.next)
266 var node = document.getElementById(entry.id)
267 var parent = document.getElementById(entry.parent)
269 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
270 node.parentNode.removeChild(node);
273 cbi_c[entry.parent]--;
274 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
276 parent.appendChild(entry.node);
278 next.parentNode.insertBefore(entry.node, next);
282 cbi_c[entry.parent]++;
286 if (entry && entry.parent) {
295 function cbi_bind(obj, type, callback, mode) {
296 if (!obj.addEventListener) {
297 obj.attachEvent('on' + type,
299 var e = window.event;
301 if (!e.target && e.srcElement)
302 e.target = e.srcElement;
304 return !!callback(e);
308 obj.addEventListener(type, callback, !!mode);
313 function cbi_combobox(id, values, def, man) {
314 var selid = "cbi.combobox." + id;
315 if (document.getElementById(selid)) {
319 var obj = document.getElementById(id)
320 var sel = document.createElement("select");
322 sel.className = 'cbi-input-select';
324 if (obj.nextSibling) {
325 obj.parentNode.insertBefore(sel, obj.nextSibling);
327 obj.parentNode.appendChild(sel);
330 var dt = obj.getAttribute('cbi_datatype');
331 var op = obj.getAttribute('cbi_optional');
334 cbi_validate_field(sel, op == 'true', dt);
336 if (!values[obj.value]) {
337 if (obj.value == "") {
338 var optdef = document.createElement("option");
340 optdef.appendChild(document.createTextNode(def));
341 sel.appendChild(optdef);
343 var opt = document.createElement("option");
344 opt.value = obj.value;
345 opt.selected = "selected";
346 opt.appendChild(document.createTextNode(obj.value));
347 sel.appendChild(opt);
351 for (var i in values) {
352 var opt = document.createElement("option");
355 if (obj.value == i) {
356 opt.selected = "selected";
359 opt.appendChild(document.createTextNode(values[i]));
360 sel.appendChild(opt);
363 var optman = document.createElement("option");
365 optman.appendChild(document.createTextNode(man));
366 sel.appendChild(optman);
368 obj.style.display = "none";
370 cbi_bind(sel, "change", function() {
371 if (sel.selectedIndex == sel.options.length - 1) {
372 obj.style.display = "inline";
373 sel.parentNode.removeChild(sel);
376 obj.value = sel.options[sel.selectedIndex].value;
387 function cbi_combobox_init(id, values, def, man) {
388 var obj = document.getElementById(id);
389 cbi_bind(obj, "blur", function() {
390 cbi_combobox(id, values, def, man)
392 cbi_combobox(id, values, def, man);
395 function cbi_filebrowser(id, url, defpath) {
396 var field = document.getElementById(id);
397 var browser = window.open(
398 url + ( field.value || defpath || '' ) + '?field=' + id,
399 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
405 function cbi_browser_init(id, respath, url, defpath)
407 function cbi_browser_btnclick(e) {
408 cbi_filebrowser(id, url, defpath);
412 var field = document.getElementById(id);
414 var btn = document.createElement('img');
415 btn.className = 'cbi-image-button';
416 btn.src = respath + '/cbi/folder.gif';
417 field.parentNode.insertBefore(btn, field.nextSibling);
419 cbi_bind(btn, 'click', cbi_browser_btnclick);
422 function cbi_dynlist_init(name, respath)
424 function cbi_dynlist_renumber(e)
426 /* in a perfect world, we could just getElementsByName() - but not if
427 * MSIE is involved... */
428 var inputs = [ ]; // = document.getElementsByName(name);
429 for (var i = 0; i < e.parentNode.childNodes.length; i++)
430 if (e.parentNode.childNodes[i].name == name)
431 inputs.push(e.parentNode.childNodes[i]);
433 for (var i = 0; i < inputs.length; i++)
435 inputs[i].id = name + '.' + (i + 1);
436 inputs[i].nextSibling.src = respath + (
437 (i+1) < inputs.length ? '/cbi/remove.gif' : '/cbi/add.gif'
444 function cbi_dynlist_keypress(ev)
446 ev = ev ? ev : window.event;
448 var se = ev.target ? ev.target : ev.srcElement;
450 if (se.nodeType == 3)
455 /* backspace, delete */
458 if (se.value.length == 0)
460 if (ev.preventDefault)
468 /* enter, arrow up, arrow down */
472 if (ev.preventDefault)
481 function cbi_dynlist_keydown(ev)
483 ev = ev ? ev : window.event;
485 var se = ev.target ? ev.target : ev.srcElement;
487 if (se.nodeType == 3)
490 var prev = se.previousSibling;
491 while (prev && prev.name != name)
492 prev = prev.previousSibling;
494 var next = se.nextSibling;
495 while (next && next.name != name)
496 next = next.nextSibling;
500 /* backspace, delete */
503 var jump = (ev.keyCode == 8)
504 ? (prev || next) : (next || prev);
506 if (se.value.length == 0 && jump)
508 se.parentNode.removeChild(se.nextSibling.nextSibling);
509 se.parentNode.removeChild(se.nextSibling);
510 se.parentNode.removeChild(se);
512 cbi_dynlist_renumber(jump);
514 if (ev.preventDefault)
517 /* IE Quirk, needs double focus somehow */
527 var n = document.createElement('input');
531 var b = document.createElement('img');
533 cbi_bind(n, 'keydown', cbi_dynlist_keydown);
534 cbi_bind(n, 'keypress', cbi_dynlist_keypress);
535 cbi_bind(b, 'click', cbi_dynlist_btnclick);
539 se.parentNode.insertBefore(n, next);
540 se.parentNode.insertBefore(b, next);
541 se.parentNode.insertBefore(document.createElement('br'), next);
545 se.parentNode.appendChild(n);
546 se.parentNode.appendChild(b);
547 se.parentNode.appendChild(document.createElement('br'));
550 var dt = se.getAttribute('cbi_datatype');
551 var op = se.getAttribute('cbi_optional') == 'true';
554 cbi_validate_field(n, op, dt);
556 cbi_dynlist_renumber(n);
577 function cbi_dynlist_btnclick(ev)
579 ev = ev ? ev : window.event;
581 var se = ev.target ? ev.target : ev.srcElement;
583 if (se.src.indexOf('remove') > -1)
585 se.previousSibling.value = '';
587 cbi_dynlist_keydown({
588 target: se.previousSibling,
594 cbi_dynlist_keydown({
595 target: se.previousSibling,
603 var inputs = document.getElementsByName(name);
604 for( var i = 0; i < inputs.length; i++ )
606 var btn = document.createElement('img');
607 btn.className = 'cbi-image-button';
608 btn.src = respath + (
609 (i+1) < inputs.length ? '/cbi/remove.gif' : '/cbi/add.gif'
612 inputs[i].parentNode.insertBefore(btn, inputs[i].nextSibling);
614 cbi_bind(inputs[i], 'keydown', cbi_dynlist_keydown);
615 cbi_bind(inputs[i], 'keypress', cbi_dynlist_keypress);
616 cbi_bind(btn, 'click', cbi_dynlist_btnclick);
620 //Hijacks the CBI form to send via XHR (requires Prototype)
621 function cbi_hijack_forms(layer, win, fail, load) {
622 var forms = layer.getElementsByTagName('form');
623 for (var i=0; i<forms.length; i++) {
624 $(forms[i]).observe('submit', function(event) {
625 // Prevent the form from also submitting the regular way
629 event.element().request({
642 function cbi_t_add(section, tab) {
643 var t = document.getElementById('tab.' + section + '.' + tab);
644 var c = document.getElementById('container.' + section + '.' + tab);
647 cbi_t[section] = (cbi_t[section] || [ ]);
648 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
652 function cbi_t_switch(section, tab) {
653 if( cbi_t[section] && cbi_t[section][tab] ) {
654 var o = cbi_t[section][tab];
655 var h = document.getElementById('tab.' + section);
656 for( var tid in cbi_t[section] ) {
657 var o2 = cbi_t[section][tid];
658 if( o.tab.id != o2.tab.id ) {
659 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
660 o2.container.style.display = 'none';
664 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
665 o2.container.style.display = 'block';
672 function cbi_t_update() {
675 for( var sid in cbi_t )
676 for( var tid in cbi_t[sid] )
677 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
678 cbi_t[sid][tid].tab.style.display = 'none';
680 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
681 cbi_t[sid][tid].tab.style.display = '';
683 var t = cbi_t[sid][tid].tab;
684 t.className += ' cbi-tab-highlighted';
688 if( hl_tabs.length > 0 )
689 window.setTimeout(function() {
690 for( var i = 0; i < hl_tabs.length; i++ )
691 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
696 function cbi_validate_form(form, errmsg)
698 /* if triggered by a section removal or addition, don't validate */
699 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
702 if( form.cbi_validators )
704 for( var i = 0; i < form.cbi_validators.length; i++ )
706 var validator = form.cbi_validators[i];
707 if( !validator() && errmsg )
718 function cbi_validate_reset(form)
721 function() { cbi_validate_form(form, null) }, 100
727 function cbi_validate_field(cbid, optional, type)
729 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
732 if( type.match(/^(\w+)\(([^\(\)]+)\)/) )
735 vargs = RegExp.$2.split(/\s*,\s*/);
738 var vldcb = cbi_validators[type];
742 var validator = function()
747 field.className = field.className.replace(/ cbi-input-invalid/g, '');
750 var value = (field.options && field.options.selectedIndex > -1)
751 ? field.options[field.options.selectedIndex].value : field.value;
753 if( !(((value.length == 0) && optional) || vldcb(value, vargs)) )
756 field.className += ' cbi-input-invalid';
764 if( ! field.form.cbi_validators )
765 field.form.cbi_validators = [ ];
767 field.form.cbi_validators.push(validator);
769 cbi_bind(field, "blur", validator);
770 cbi_bind(field, "keyup", validator);
772 if (field.nodeName == 'SELECT')
774 cbi_bind(field, "change", validator);
775 cbi_bind(field, "click", validator);
778 field.setAttribute("cbi_validate", validator);
779 field.setAttribute("cbi_datatype", type);
780 field.setAttribute("cbi_optional", (!!optional).toString());
784 var fcbox = document.getElementById('cbi.combobox.' + field.id);
786 cbi_validate_field(fcbox, optional, type);
790 function cbi_row_swap(elem, up, store)
792 var tr = elem.parentNode;
793 while (tr && tr.nodeName.toLowerCase() != 'tr')
799 var table = tr.parentNode;
800 while (table && table.nodeName.toLowerCase() != 'table')
801 table = table.parentNode;
807 var e = up ? table.rows.length : table.rows.length - 1;
809 for (var idx = s; idx < e; idx++)
811 if (table.rows[idx] == tr)
814 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
816 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
823 for (idx = 2; idx < table.rows.length; idx++)
825 table.rows[idx].className = table.rows[idx].className.replace(
826 /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
829 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
833 var input = document.getElementById(store);
835 input.value = ids.join(' ');
840 if( ! String.serialize )
841 String.serialize = function(o)
857 for( var i = 0; i < o.length; i++ )
858 s += (s ? ', ' : '') + String.serialize(o[i]);
860 return '[ ' + s + ' ]';
869 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
871 return '{ ' + s + ' }';
878 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
879 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
883 return '"' + o + '"';
893 if( ! String.format )
894 String.format = function()
896 if (!arguments || arguments.length < 1 || !RegExp)
899 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
900 var quot_esc = [/"/g, '"', /'/g, '''];
903 for( var i = 0; i < r.length; i += 2 )
904 s = s.replace(r[i], r[i+1]);
908 var str = arguments[0];
910 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
911 var a = b = [], numSubstitutions = 0, numMatches = 0;
913 while( a = re.exec(str) )
916 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
917 var pPrecision = a[6], pType = a[7];
927 if (numSubstitutions++ < arguments.length)
929 var param = arguments[numSubstitutions];
932 if (pPad && pPad.substr(0,1) == "'")
933 pad = leftpart.substr(1,1);
937 var justifyRight = true;
938 if (pJustify && pJustify === "-")
939 justifyRight = false;
943 minLength = parseInt(pMinLength);
946 if (pPrecision && pType == 'f')
947 precision = parseInt(pPrecision.substring(1));
954 subst = (parseInt(param) || 0).toString(2);
958 subst = String.fromCharCode(parseInt(param) || 0);
962 subst = (parseInt(param) || 0);
966 subst = Math.abs(parseInt(param) || 0);
970 subst = (precision > -1)
971 ? ((parseFloat(param) || 0.0)).toFixed(precision)
972 : (parseFloat(param) || 0.0);
976 subst = (parseInt(param) || 0).toString(8);
984 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
988 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
992 subst = esc(param, html_esc);
996 subst = esc(param, quot_esc);
1000 subst = String.serialize(param);
1007 var ts = (param || 0);
1010 tm = Math.floor(ts / 60);
1015 th = Math.floor(tm / 60);
1020 td = Math.floor(th / 24);
1025 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1026 : String.format('%dh %dm %ds', th, tm, ts);
1031 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1032 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1035 var val = (param || 0);
1036 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1038 for (i = 0; (i < units.length) && (val > mf); i++)
1041 subst = val.toFixed(pr) + ' ' + units[i];
1047 out += leftpart + subst;
1048 str = str.substr(m.length);