2 LuCI - Lua Configuration Interface
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008-2011 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 'neg_ipaddr': function(v)
47 return cbi_validators.ip4addr(v.replace(/^\s*!/, "")) || cbi_validators.ip6addr(v.replace(/^\s*!/, ""));
50 'ip4addr': function(v)
52 if( v.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)(\/(\d+))?$/) )
54 return (RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
55 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
56 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
57 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
58 (!RegExp.$5 || ((RegExp.$6 >= 0) && (RegExp.$6 <= 32)))
65 'neg_ip4addr': function(v)
67 return cbi_validators.ip4addr(v.replace(/^\s*!/, ""));
70 'ip6addr': function(v)
72 if( v.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/) )
74 if( !RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)) )
83 if( addr.indexOf('.') > 0 )
85 var off = addr.lastIndexOf(':');
87 if( !(off && cbi_validators.ip4addr(addr.substr(off+1))) )
90 addr = addr.substr(0, off) + ':0:0';
93 if( addr.indexOf('::') >= 0 )
98 for( var i = 1; i < (addr.length-1); i++ )
99 if( addr.charAt(i) == ':' )
105 for( var i = 0; i < (7 - colons); i++ )
108 if (addr.match(/^(.*?)::(.*?)$/))
109 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
110 (RegExp.$2 ? ':' + RegExp.$2 : '');
113 return (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null);
122 return cbi_validators.integer(v) && (v >= 0) && (v <= 65535);
125 'portrange': function(v)
127 if( v.match(/^(\d+)-(\d+)$/) )
132 return cbi_validators.port(p1) &&
133 cbi_validators.port(p2) &&
134 (parseInt(p1) <= parseInt(p2))
139 return cbi_validators.port(v);
143 'macaddr': function(v)
145 return (v.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
150 return cbi_validators.hostname(v) || cbi_validators.ipaddr(v);
153 'hostname': function(v)
154 { if ( v.length <= 253 )
155 return (v.match(/^[a-zA-Z0-9][a-zA-Z0-9\-.]*[a-zA-Z0-9]$/) != null);
160 'wpakey': function(v)
163 return (v.match(/^[a-fA-F0-9]{64}$/) != null);
165 return (v.length >= 8) && (v.length <= 63);
168 'wepkey': function(v)
170 if( v.substr(0,2) == 's:' )
173 if( (v.length == 10) || (v.length == 26) )
174 return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
176 return (v.length == 5) || (v.length == 13);
179 'uciname': function(v)
181 return (v.match(/^[a-zA-Z0-9_]+$/) != null);
184 'neg_network_ip4addr': function(v)
186 v = v.replace(/^\s*!/, "");
187 return cbi_validators.uciname(v) || cbi_validators.ip4addr(v);
190 'range': function(v, args)
192 var min = parseInt(args[0]);
193 var max = parseInt(args[1]);
194 var val = parseInt(v);
196 if (!isNaN(min) && !isNaN(max) && !isNaN(val))
197 return ((val >= min) && (val <= max));
202 'min': function(v, args)
204 var min = parseInt(args[0]);
205 var val = parseInt(v);
207 if (!isNaN(min) && !isNaN(val))
213 'max': function(v, args)
215 var max = parseInt(args[0]);
216 var val = parseInt(v);
218 if (!isNaN(max) && !isNaN(val))
226 function cbi_d_add(field, dep, next) {
227 var obj = document.getElementById(field);
230 for (var i=0; i<cbi_d.length; i++) {
231 if (cbi_d[i].id == field) {
240 "parent": obj.parentNode.id,
244 cbi_d.unshift(entry);
250 function cbi_d_checkvalue(target, ref) {
251 var t = document.getElementById(target);
255 var tl = document.getElementsByName(target);
257 if( tl.length > 0 && tl[0].type == 'radio' )
258 for( var i = 0; i < tl.length; i++ )
259 if( tl[i].checked ) {
264 value = value ? value : "";
265 } else if (!t.value) {
270 if (t.type == "checkbox") {
271 value = t.checked ? value : "";
275 return (value == ref)
278 function cbi_d_check(deps) {
281 for (var i=0; i<deps.length; i++) {
284 for (var j in deps[i]) {
285 if (j == "!reverse") {
287 } else if (j == "!default") {
291 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
301 function cbi_d_update() {
303 for (var i=0; i<cbi_d.length; i++) {
304 var entry = cbi_d[i];
305 var next = document.getElementById(entry.next)
306 var node = document.getElementById(entry.id)
307 var parent = document.getElementById(entry.parent)
309 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
310 node.parentNode.removeChild(node);
313 cbi_c[entry.parent]--;
314 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
316 parent.appendChild(entry.node);
318 next.parentNode.insertBefore(entry.node, next);
322 cbi_c[entry.parent]++;
326 if (entry && entry.parent) {
335 function cbi_bind(obj, type, callback, mode) {
336 if (!obj.addEventListener) {
337 obj.attachEvent('on' + type,
339 var e = window.event;
341 if (!e.target && e.srcElement)
342 e.target = e.srcElement;
344 return !!callback(e);
348 obj.addEventListener(type, callback, !!mode);
353 function cbi_combobox(id, values, def, man) {
354 var selid = "cbi.combobox." + id;
355 if (document.getElementById(selid)) {
359 var obj = document.getElementById(id)
360 var sel = document.createElement("select");
362 sel.className = 'cbi-input-select';
364 if (obj.nextSibling) {
365 obj.parentNode.insertBefore(sel, obj.nextSibling);
367 obj.parentNode.appendChild(sel);
370 var dt = obj.getAttribute('cbi_datatype');
371 var op = obj.getAttribute('cbi_optional');
374 cbi_validate_field(sel, op == 'true', dt);
376 if (!values[obj.value]) {
377 if (obj.value == "") {
378 var optdef = document.createElement("option");
380 optdef.appendChild(document.createTextNode(def));
381 sel.appendChild(optdef);
383 var opt = document.createElement("option");
384 opt.value = obj.value;
385 opt.selected = "selected";
386 opt.appendChild(document.createTextNode(obj.value));
387 sel.appendChild(opt);
391 for (var i in values) {
392 var opt = document.createElement("option");
395 if (obj.value == i) {
396 opt.selected = "selected";
399 opt.appendChild(document.createTextNode(values[i]));
400 sel.appendChild(opt);
403 var optman = document.createElement("option");
405 optman.appendChild(document.createTextNode(man));
406 sel.appendChild(optman);
408 obj.style.display = "none";
410 cbi_bind(sel, "change", function() {
411 if (sel.selectedIndex == sel.options.length - 1) {
412 obj.style.display = "inline";
413 sel.parentNode.removeChild(sel);
416 obj.value = sel.options[sel.selectedIndex].value;
427 function cbi_combobox_init(id, values, def, man) {
428 var obj = document.getElementById(id);
429 cbi_bind(obj, "blur", function() {
430 cbi_combobox(id, values, def, man)
432 cbi_combobox(id, values, def, man);
435 function cbi_filebrowser(id, url, defpath) {
436 var field = document.getElementById(id);
437 var browser = window.open(
438 url + ( field.value || defpath || '' ) + '?field=' + id,
439 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
445 function cbi_browser_init(id, respath, url, defpath)
447 function cbi_browser_btnclick(e) {
448 cbi_filebrowser(id, url, defpath);
452 var field = document.getElementById(id);
454 var btn = document.createElement('img');
455 btn.className = 'cbi-image-button';
456 btn.src = respath + '/cbi/folder.gif';
457 field.parentNode.insertBefore(btn, field.nextSibling);
459 cbi_bind(btn, 'click', cbi_browser_btnclick);
462 function cbi_dynlist_init(name, respath)
464 function cbi_dynlist_renumber(e)
466 /* in a perfect world, we could just getElementsByName() - but not if
467 * MSIE is involved... */
468 var inputs = [ ]; // = document.getElementsByName(name);
469 for (var i = 0; i < e.parentNode.childNodes.length; i++)
470 if (e.parentNode.childNodes[i].name == name)
471 inputs.push(e.parentNode.childNodes[i]);
473 for (var i = 0; i < inputs.length; i++)
475 inputs[i].id = name + '.' + (i + 1);
476 inputs[i].nextSibling.src = respath + (
477 (i+1) < inputs.length ? '/cbi/remove.gif' : '/cbi/add.gif'
484 function cbi_dynlist_keypress(ev)
486 ev = ev ? ev : window.event;
488 var se = ev.target ? ev.target : ev.srcElement;
490 if (se.nodeType == 3)
495 /* backspace, delete */
498 if (se.value.length == 0)
500 if (ev.preventDefault)
508 /* enter, arrow up, arrow down */
512 if (ev.preventDefault)
521 function cbi_dynlist_keydown(ev)
523 ev = ev ? ev : window.event;
525 var se = ev.target ? ev.target : ev.srcElement;
527 if (se.nodeType == 3)
530 var prev = se.previousSibling;
531 while (prev && prev.name != name)
532 prev = prev.previousSibling;
534 var next = se.nextSibling;
535 while (next && next.name != name)
536 next = next.nextSibling;
540 /* backspace, delete */
543 var jump = (ev.keyCode == 8)
544 ? (prev || next) : (next || prev);
546 if (se.value.length == 0 && jump)
548 se.parentNode.removeChild(se.nextSibling.nextSibling);
549 se.parentNode.removeChild(se.nextSibling);
550 se.parentNode.removeChild(se);
552 cbi_dynlist_renumber(jump);
554 if (ev.preventDefault)
557 /* IE Quirk, needs double focus somehow */
567 var n = document.createElement('input');
571 var b = document.createElement('img');
573 cbi_bind(n, 'keydown', cbi_dynlist_keydown);
574 cbi_bind(n, 'keypress', cbi_dynlist_keypress);
575 cbi_bind(b, 'click', cbi_dynlist_btnclick);
579 se.parentNode.insertBefore(n, next);
580 se.parentNode.insertBefore(b, next);
581 se.parentNode.insertBefore(document.createElement('br'), next);
585 se.parentNode.appendChild(n);
586 se.parentNode.appendChild(b);
587 se.parentNode.appendChild(document.createElement('br'));
590 var dt = se.getAttribute('cbi_datatype');
591 var op = se.getAttribute('cbi_optional') == 'true';
594 cbi_validate_field(n, op, dt);
596 cbi_dynlist_renumber(n);
617 function cbi_dynlist_btnclick(ev)
619 ev = ev ? ev : window.event;
621 var se = ev.target ? ev.target : ev.srcElement;
623 if (se.src.indexOf('remove') > -1)
625 se.previousSibling.value = '';
627 cbi_dynlist_keydown({
628 target: se.previousSibling,
634 cbi_dynlist_keydown({
635 target: se.previousSibling,
643 var inputs = document.getElementsByName(name);
644 for( var i = 0; i < inputs.length; i++ )
646 var btn = document.createElement('img');
647 btn.className = 'cbi-image-button';
648 btn.src = respath + (
649 (i+1) < inputs.length ? '/cbi/remove.gif' : '/cbi/add.gif'
652 inputs[i].parentNode.insertBefore(btn, inputs[i].nextSibling);
654 cbi_bind(inputs[i], 'keydown', cbi_dynlist_keydown);
655 cbi_bind(inputs[i], 'keypress', cbi_dynlist_keypress);
656 cbi_bind(btn, 'click', cbi_dynlist_btnclick);
660 //Hijacks the CBI form to send via XHR (requires Prototype)
661 function cbi_hijack_forms(layer, win, fail, load) {
662 var forms = layer.getElementsByTagName('form');
663 for (var i=0; i<forms.length; i++) {
664 $(forms[i]).observe('submit', function(event) {
665 // Prevent the form from also submitting the regular way
669 event.element().request({
682 function cbi_t_add(section, tab) {
683 var t = document.getElementById('tab.' + section + '.' + tab);
684 var c = document.getElementById('container.' + section + '.' + tab);
687 cbi_t[section] = (cbi_t[section] || [ ]);
688 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
692 function cbi_t_switch(section, tab) {
693 if( cbi_t[section] && cbi_t[section][tab] ) {
694 var o = cbi_t[section][tab];
695 var h = document.getElementById('tab.' + section);
696 for( var tid in cbi_t[section] ) {
697 var o2 = cbi_t[section][tid];
698 if( o.tab.id != o2.tab.id ) {
699 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
700 o2.container.style.display = 'none';
704 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
705 o2.container.style.display = 'block';
712 function cbi_t_update() {
715 for( var sid in cbi_t )
716 for( var tid in cbi_t[sid] )
717 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
718 cbi_t[sid][tid].tab.style.display = 'none';
720 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
721 cbi_t[sid][tid].tab.style.display = '';
723 var t = cbi_t[sid][tid].tab;
724 t.className += ' cbi-tab-highlighted';
728 if( hl_tabs.length > 0 )
729 window.setTimeout(function() {
730 for( var i = 0; i < hl_tabs.length; i++ )
731 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
736 function cbi_validate_form(form, errmsg)
738 /* if triggered by a section removal or addition, don't validate */
739 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
742 if( form.cbi_validators )
744 for( var i = 0; i < form.cbi_validators.length; i++ )
746 var validator = form.cbi_validators[i];
747 if( !validator() && errmsg )
758 function cbi_validate_reset(form)
761 function() { cbi_validate_form(form, null) }, 100
767 function cbi_validate_field(cbid, optional, type)
769 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
772 if( type.match(/^(\w+)\(([^\(\)]+)\)/) )
775 vargs = RegExp.$2.split(/\s*,\s*/);
778 var vldcb = cbi_validators[type];
782 var validator = function()
787 field.className = field.className.replace(/ cbi-input-invalid/g, '');
790 var value = (field.options && field.options.selectedIndex > -1)
791 ? field.options[field.options.selectedIndex].value : field.value;
793 if( !(((value.length == 0) && optional) || vldcb(value, vargs)) )
796 field.className += ' cbi-input-invalid';
804 if( ! field.form.cbi_validators )
805 field.form.cbi_validators = [ ];
807 field.form.cbi_validators.push(validator);
809 cbi_bind(field, "blur", validator);
810 cbi_bind(field, "keyup", validator);
812 if (field.nodeName == 'SELECT')
814 cbi_bind(field, "change", validator);
815 cbi_bind(field, "click", validator);
818 field.setAttribute("cbi_validate", validator);
819 field.setAttribute("cbi_datatype", type);
820 field.setAttribute("cbi_optional", (!!optional).toString());
824 var fcbox = document.getElementById('cbi.combobox.' + field.id);
826 cbi_validate_field(fcbox, optional, type);
830 function cbi_row_swap(elem, up, store)
832 var tr = elem.parentNode;
833 while (tr && tr.nodeName.toLowerCase() != 'tr')
839 var table = tr.parentNode;
840 while (table && table.nodeName.toLowerCase() != 'table')
841 table = table.parentNode;
847 var e = up ? table.rows.length : table.rows.length - 1;
849 for (var idx = s; idx < e; idx++)
851 if (table.rows[idx] == tr)
854 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
856 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
863 for (idx = 2; idx < table.rows.length; idx++)
865 table.rows[idx].className = table.rows[idx].className.replace(
866 /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
869 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
873 var input = document.getElementById(store);
875 input.value = ids.join(' ');
880 if( ! String.serialize )
881 String.serialize = function(o)
897 for( var i = 0; i < o.length; i++ )
898 s += (s ? ', ' : '') + String.serialize(o[i]);
900 return '[ ' + s + ' ]';
909 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
911 return '{ ' + s + ' }';
918 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
919 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
923 return '"' + o + '"';
933 if( ! String.format )
934 String.format = function()
936 if (!arguments || arguments.length < 1 || !RegExp)
939 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
940 var quot_esc = [/"/g, '"', /'/g, '''];
943 for( var i = 0; i < r.length; i += 2 )
944 s = s.replace(r[i], r[i+1]);
948 var str = arguments[0];
950 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
951 var a = b = [], numSubstitutions = 0, numMatches = 0;
953 while( a = re.exec(str) )
956 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
957 var pPrecision = a[6], pType = a[7];
967 if (numSubstitutions++ < arguments.length)
969 var param = arguments[numSubstitutions];
972 if (pPad && pPad.substr(0,1) == "'")
973 pad = leftpart.substr(1,1);
977 var justifyRight = true;
978 if (pJustify && pJustify === "-")
979 justifyRight = false;
983 minLength = parseInt(pMinLength);
986 if (pPrecision && pType == 'f')
987 precision = parseInt(pPrecision.substring(1));
994 subst = (parseInt(param) || 0).toString(2);
998 subst = String.fromCharCode(parseInt(param) || 0);
1002 subst = (parseInt(param) || 0);
1006 subst = Math.abs(parseInt(param) || 0);
1010 subst = (precision > -1)
1011 ? ((parseFloat(param) || 0.0)).toFixed(precision)
1012 : (parseFloat(param) || 0.0);
1016 subst = (parseInt(param) || 0).toString(8);
1024 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1028 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1032 subst = esc(param, html_esc);
1036 subst = esc(param, quot_esc);
1040 subst = String.serialize(param);
1047 var ts = (param || 0);
1050 tm = Math.floor(ts / 60);
1055 th = Math.floor(tm / 60);
1060 td = Math.floor(th / 24);
1065 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1066 : String.format('%dh %dm %ds', th, tm, ts);
1071 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1072 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1075 var val = parseFloat(param || 0);
1076 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1078 for (i = 0; (i < units.length) && (val > mf); i++)
1081 subst = val.toFixed(pr) + ' ' + units[i];
1087 out += leftpart + subst;
1088 str = str.substr(m.length);