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)
156 return (v.match(/^[a-zA-Z]+$/) != null ||
157 (v.match(/^[a-zA-Z0-9][a-zA-Z0-9\-.]*[a-zA-Z0-9]$/) &&
158 v.match(/[^0-9.]/)));
163 'network': function(v)
165 return cbi_validators.uciname(v) || cbi_validators.host(v);
168 'wpakey': function(v)
171 return (v.match(/^[a-fA-F0-9]{64}$/) != null);
173 return (v.length >= 8) && (v.length <= 63);
176 'wepkey': function(v)
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(v)
189 return (v.match(/^[a-zA-Z0-9_]+$/) != null);
192 'neg_network_ip4addr': function(v)
194 v = v.replace(/^\s*!/, "");
195 return cbi_validators.uciname(v) || cbi_validators.ip4addr(v);
198 'range': function(v, args)
200 var min = parseInt(args[0]);
201 var max = parseInt(args[1]);
202 var val = parseInt(v);
204 if (!isNaN(min) && !isNaN(max) && !isNaN(val))
205 return ((val >= min) && (val <= max));
210 'min': function(v, args)
212 var min = parseInt(args[0]);
213 var val = parseInt(v);
215 if (!isNaN(min) && !isNaN(val))
221 'max': function(v, args)
223 var max = parseInt(args[0]);
224 var val = parseInt(v);
226 if (!isNaN(max) && !isNaN(val))
232 'neg': function(v, args)
234 if (args[0] && typeof cbi_validators[args[0]] == "function")
235 return cbi_validators[args[0]](v.replace(/^\s*!\s*/, ''));
240 'list': function(v, args)
242 var cb = cbi_validators[args[0] || 'string'];
243 if (typeof cb == "function")
245 var cbargs = args.slice(1);
246 var values = v.match(/[^\s]+/g);
248 for (var i = 0; i < values.length; i++)
249 if (!cb(values[i], cbargs))
260 function cbi_d_add(field, dep, next) {
261 var obj = document.getElementById(field);
264 for (var i=0; i<cbi_d.length; i++) {
265 if (cbi_d[i].id == field) {
274 "parent": obj.parentNode.id,
278 cbi_d.unshift(entry);
284 function cbi_d_checkvalue(target, ref) {
285 var t = document.getElementById(target);
289 var tl = document.getElementsByName(target);
291 if( tl.length > 0 && tl[0].type == 'radio' )
292 for( var i = 0; i < tl.length; i++ )
293 if( tl[i].checked ) {
298 value = value ? value : "";
299 } else if (!t.value) {
304 if (t.type == "checkbox") {
305 value = t.checked ? value : "";
309 return (value == ref)
312 function cbi_d_check(deps) {
315 for (var i=0; i<deps.length; i++) {
318 for (var j in deps[i]) {
319 if (j == "!reverse") {
321 } else if (j == "!default") {
325 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
335 function cbi_d_update() {
337 for (var i=0; i<cbi_d.length; i++) {
338 var entry = cbi_d[i];
339 var next = document.getElementById(entry.next)
340 var node = document.getElementById(entry.id)
341 var parent = document.getElementById(entry.parent)
343 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
344 node.parentNode.removeChild(node);
347 cbi_c[entry.parent]--;
348 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
350 parent.appendChild(entry.node);
352 next.parentNode.insertBefore(entry.node, next);
356 cbi_c[entry.parent]++;
360 if (entry && entry.parent) {
362 cbi_tag_last(parent);
370 function cbi_bind(obj, type, callback, mode) {
371 if (!obj.addEventListener) {
372 obj.attachEvent('on' + type,
374 var e = window.event;
376 if (!e.target && e.srcElement)
377 e.target = e.srcElement;
379 return !!callback(e);
383 obj.addEventListener(type, callback, !!mode);
388 function cbi_combobox(id, values, def, man) {
389 var selid = "cbi.combobox." + id;
390 if (document.getElementById(selid)) {
394 var obj = document.getElementById(id)
395 var sel = document.createElement("select");
397 sel.className = 'cbi-input-select';
399 if (obj.nextSibling) {
400 obj.parentNode.insertBefore(sel, obj.nextSibling);
402 obj.parentNode.appendChild(sel);
405 var dt = obj.getAttribute('cbi_datatype');
406 var op = obj.getAttribute('cbi_optional');
409 cbi_validate_field(sel, op == 'true', dt);
411 if (!values[obj.value]) {
412 if (obj.value == "") {
413 var optdef = document.createElement("option");
415 optdef.appendChild(document.createTextNode(def));
416 sel.appendChild(optdef);
418 var opt = document.createElement("option");
419 opt.value = obj.value;
420 opt.selected = "selected";
421 opt.appendChild(document.createTextNode(obj.value));
422 sel.appendChild(opt);
426 for (var i in values) {
427 var opt = document.createElement("option");
430 if (obj.value == i) {
431 opt.selected = "selected";
434 opt.appendChild(document.createTextNode(values[i]));
435 sel.appendChild(opt);
438 var optman = document.createElement("option");
440 optman.appendChild(document.createTextNode(man));
441 sel.appendChild(optman);
443 obj.style.display = "none";
445 cbi_bind(sel, "change", function() {
446 if (sel.selectedIndex == sel.options.length - 1) {
447 obj.style.display = "inline";
448 sel.parentNode.removeChild(sel);
451 obj.value = sel.options[sel.selectedIndex].value;
462 function cbi_combobox_init(id, values, def, man) {
463 var obj = document.getElementById(id);
464 cbi_bind(obj, "blur", function() {
465 cbi_combobox(id, values, def, man)
467 cbi_combobox(id, values, def, man);
470 function cbi_filebrowser(id, url, defpath) {
471 var field = document.getElementById(id);
472 var browser = window.open(
473 url + ( field.value || defpath || '' ) + '?field=' + id,
474 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
480 function cbi_browser_init(id, respath, url, defpath)
482 function cbi_browser_btnclick(e) {
483 cbi_filebrowser(id, url, defpath);
487 var field = document.getElementById(id);
489 var btn = document.createElement('img');
490 btn.className = 'cbi-image-button';
491 btn.src = respath + '/cbi/folder.gif';
492 field.parentNode.insertBefore(btn, field.nextSibling);
494 cbi_bind(btn, 'click', cbi_browser_btnclick);
497 function cbi_dynlist_init(name, respath)
499 function cbi_dynlist_renumber(e)
501 /* in a perfect world, we could just getElementsByName() - but not if
502 * MSIE is involved... */
503 var inputs = [ ]; // = document.getElementsByName(name);
504 for (var i = 0; i < e.parentNode.childNodes.length; i++)
505 if (e.parentNode.childNodes[i].name == name)
506 inputs.push(e.parentNode.childNodes[i]);
508 for (var i = 0; i < inputs.length; i++)
510 inputs[i].id = name + '.' + (i + 1);
511 inputs[i].nextSibling.src = respath + (
512 (i+1) < inputs.length ? '/cbi/remove.gif' : '/cbi/add.gif'
519 function cbi_dynlist_keypress(ev)
521 ev = ev ? ev : window.event;
523 var se = ev.target ? ev.target : ev.srcElement;
525 if (se.nodeType == 3)
530 /* backspace, delete */
533 if (se.value.length == 0)
535 if (ev.preventDefault)
543 /* enter, arrow up, arrow down */
547 if (ev.preventDefault)
556 function cbi_dynlist_keydown(ev)
558 ev = ev ? ev : window.event;
560 var se = ev.target ? ev.target : ev.srcElement;
562 if (se.nodeType == 3)
565 var prev = se.previousSibling;
566 while (prev && prev.name != name)
567 prev = prev.previousSibling;
569 var next = se.nextSibling;
570 while (next && next.name != name)
571 next = next.nextSibling;
575 /* backspace, delete */
578 var jump = (ev.keyCode == 8)
579 ? (prev || next) : (next || prev);
581 if (se.value.length == 0 && jump)
583 se.parentNode.removeChild(se.nextSibling.nextSibling);
584 se.parentNode.removeChild(se.nextSibling);
585 se.parentNode.removeChild(se);
587 cbi_dynlist_renumber(jump);
589 if (ev.preventDefault)
592 /* IE Quirk, needs double focus somehow */
602 var n = document.createElement('input');
606 var b = document.createElement('img');
608 cbi_bind(n, 'keydown', cbi_dynlist_keydown);
609 cbi_bind(n, 'keypress', cbi_dynlist_keypress);
610 cbi_bind(b, 'click', cbi_dynlist_btnclick);
614 se.parentNode.insertBefore(n, next);
615 se.parentNode.insertBefore(b, next);
616 se.parentNode.insertBefore(document.createElement('br'), next);
620 se.parentNode.appendChild(n);
621 se.parentNode.appendChild(b);
622 se.parentNode.appendChild(document.createElement('br'));
625 var dt = se.getAttribute('cbi_datatype');
626 var op = se.getAttribute('cbi_optional') == 'true';
629 cbi_validate_field(n, op, dt);
631 cbi_dynlist_renumber(n);
652 function cbi_dynlist_btnclick(ev)
654 ev = ev ? ev : window.event;
656 var se = ev.target ? ev.target : ev.srcElement;
658 if (se.src.indexOf('remove') > -1)
660 se.previousSibling.value = '';
662 cbi_dynlist_keydown({
663 target: se.previousSibling,
669 cbi_dynlist_keydown({
670 target: se.previousSibling,
678 var inputs = document.getElementsByName(name);
679 for( var i = 0; i < inputs.length; i++ )
681 var btn = document.createElement('img');
682 btn.className = 'cbi-image-button';
683 btn.src = respath + (
684 (i+1) < inputs.length ? '/cbi/remove.gif' : '/cbi/add.gif'
687 inputs[i].parentNode.insertBefore(btn, inputs[i].nextSibling);
689 cbi_bind(inputs[i], 'keydown', cbi_dynlist_keydown);
690 cbi_bind(inputs[i], 'keypress', cbi_dynlist_keypress);
691 cbi_bind(btn, 'click', cbi_dynlist_btnclick);
695 //Hijacks the CBI form to send via XHR (requires Prototype)
696 function cbi_hijack_forms(layer, win, fail, load) {
697 var forms = layer.getElementsByTagName('form');
698 for (var i=0; i<forms.length; i++) {
699 $(forms[i]).observe('submit', function(event) {
700 // Prevent the form from also submitting the regular way
704 event.element().request({
717 function cbi_t_add(section, tab) {
718 var t = document.getElementById('tab.' + section + '.' + tab);
719 var c = document.getElementById('container.' + section + '.' + tab);
722 cbi_t[section] = (cbi_t[section] || [ ]);
723 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
727 function cbi_t_switch(section, tab) {
728 if( cbi_t[section] && cbi_t[section][tab] ) {
729 var o = cbi_t[section][tab];
730 var h = document.getElementById('tab.' + section);
731 for( var tid in cbi_t[section] ) {
732 var o2 = cbi_t[section][tid];
733 if( o.tab.id != o2.tab.id ) {
734 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
735 o2.container.style.display = 'none';
739 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
740 o2.container.style.display = 'block';
747 function cbi_t_update() {
751 for( var sid in cbi_t )
752 for( var tid in cbi_t[sid] )
754 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
755 cbi_t[sid][tid].tab.style.display = 'none';
757 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
758 cbi_t[sid][tid].tab.style.display = '';
760 var t = cbi_t[sid][tid].tab;
761 t.className += ' cbi-tab-highlighted';
765 cbi_tag_last(cbi_t[sid][tid].container);
769 if( hl_tabs.length > 0 )
770 window.setTimeout(function() {
771 for( var i = 0; i < hl_tabs.length; i++ )
772 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
779 function cbi_validate_form(form, errmsg)
781 /* if triggered by a section removal or addition, don't validate */
782 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
785 if( form.cbi_validators )
787 for( var i = 0; i < form.cbi_validators.length; i++ )
789 var validator = form.cbi_validators[i];
790 if( !validator() && errmsg )
801 function cbi_validate_reset(form)
804 function() { cbi_validate_form(form, null) }, 100
810 function cbi_validate_field(cbid, optional, type)
812 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
815 if( type.match(/^(\w+)\(([^\(\)]+)\)/) )
818 vargs = RegExp.$2.split(/\s*,\s*/);
821 var vldcb = cbi_validators[type];
825 var validator = function()
830 field.className = field.className.replace(/ cbi-input-invalid/g, '');
833 var value = (field.options && field.options.selectedIndex > -1)
834 ? field.options[field.options.selectedIndex].value : field.value;
836 if( !(((value.length == 0) && optional) || vldcb(value, vargs)) )
839 field.className += ' cbi-input-invalid';
847 if( ! field.form.cbi_validators )
848 field.form.cbi_validators = [ ];
850 field.form.cbi_validators.push(validator);
852 cbi_bind(field, "blur", validator);
853 cbi_bind(field, "keyup", validator);
855 if (field.nodeName == 'SELECT')
857 cbi_bind(field, "change", validator);
858 cbi_bind(field, "click", validator);
861 field.setAttribute("cbi_validate", validator);
862 field.setAttribute("cbi_datatype", type);
863 field.setAttribute("cbi_optional", (!!optional).toString());
867 var fcbox = document.getElementById('cbi.combobox.' + field.id);
869 cbi_validate_field(fcbox, optional, type);
873 function cbi_row_swap(elem, up, store)
875 var tr = elem.parentNode;
876 while (tr && tr.nodeName.toLowerCase() != 'tr')
882 var table = tr.parentNode;
883 while (table && table.nodeName.toLowerCase() != 'table')
884 table = table.parentNode;
890 var e = up ? table.rows.length : table.rows.length - 1;
892 for (var idx = s; idx < e; idx++)
894 if (table.rows[idx] == tr)
897 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
899 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
906 for (idx = 2; idx < table.rows.length; idx++)
908 table.rows[idx].className = table.rows[idx].className.replace(
909 /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
912 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
916 var input = document.getElementById(store);
918 input.value = ids.join(' ');
923 function cbi_tag_last(container)
927 for (var i = 0; i < container.childNodes.length; i++)
929 var c = container.childNodes[i];
930 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
932 c.className = c.className.replace(/ cbi-value-last$/, '');
939 last.className += ' cbi-value-last';
943 if( ! String.serialize )
944 String.serialize = function(o)
960 for( var i = 0; i < o.length; i++ )
961 s += (s ? ', ' : '') + String.serialize(o[i]);
963 return '[ ' + s + ' ]';
972 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
974 return '{ ' + s + ' }';
981 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
982 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
986 return '"' + o + '"';
996 if( ! String.format )
997 String.format = function()
999 if (!arguments || arguments.length < 1 || !RegExp)
1002 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1003 var quot_esc = [/"/g, '"', /'/g, '''];
1005 function esc(s, r) {
1006 for( var i = 0; i < r.length; i += 2 )
1007 s = s.replace(r[i], r[i+1]);
1011 var str = arguments[0];
1013 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1014 var a = b = [], numSubstitutions = 0, numMatches = 0;
1016 while( a = re.exec(str) )
1019 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1020 var pPrecision = a[6], pType = a[7];
1030 if (numSubstitutions++ < arguments.length)
1032 var param = arguments[numSubstitutions];
1035 if (pPad && pPad.substr(0,1) == "'")
1036 pad = leftpart.substr(1,1);
1040 var justifyRight = true;
1041 if (pJustify && pJustify === "-")
1042 justifyRight = false;
1046 minLength = parseInt(pMinLength);
1049 if (pPrecision && pType == 'f')
1050 precision = parseInt(pPrecision.substring(1));
1057 subst = (parseInt(param) || 0).toString(2);
1061 subst = String.fromCharCode(parseInt(param) || 0);
1065 subst = (parseInt(param) || 0);
1069 subst = Math.abs(parseInt(param) || 0);
1073 subst = (precision > -1)
1074 ? ((parseFloat(param) || 0.0)).toFixed(precision)
1075 : (parseFloat(param) || 0.0);
1079 subst = (parseInt(param) || 0).toString(8);
1087 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1091 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1095 subst = esc(param, html_esc);
1099 subst = esc(param, quot_esc);
1103 subst = String.serialize(param);
1110 var ts = (param || 0);
1113 tm = Math.floor(ts / 60);
1118 th = Math.floor(tm / 60);
1123 td = Math.floor(th / 24);
1128 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1129 : String.format('%dh %dm %ds', th, tm, ts);
1134 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1135 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1138 var val = parseFloat(param || 0);
1139 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1141 for (i = 0; (i < units.length) && (val > mf); i++)
1144 subst = val.toFixed(pr) + ' ' + units[i];
1150 out += leftpart + subst;
1151 str = str.substr(m.length);