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, datatype, optional, choices)
499 var input0 = document.getElementsByName(name)[0];
500 var prefix = input0.name;
501 var parent = input0.parentNode;
505 function cbi_dynlist_redraw(focus, add, del)
509 while (parent.firstChild)
511 var n = parent.firstChild;
512 var i = parseInt(n.index);
516 if (n.nodeName.toLowerCase() == 'input')
517 values.push(n.value || '');
518 else if (n.nodeName.toLowerCase() == 'select')
519 values[values.length-1] = n.options[n.selectedIndex].value;
522 parent.removeChild(n);
528 values.splice(focus, 0, '');
530 else if (values.length == 0)
536 for (var i = 0; i < values.length; i++)
538 var t = document.createElement('input');
539 t.id = prefix + '.' + (i+1);
544 t.className = 'cbi-input-text';
546 var b = document.createElement('img');
547 b.src = respath + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
548 b.className = 'cbi-image-button';
550 parent.appendChild(t);
551 parent.appendChild(b);
552 parent.appendChild(document.createElement('br'));
556 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
561 cbi_combobox_init(t.id, choices[0], '', choices[1]);
562 t.nextSibling.index = i;
564 cbi_bind(t.nextSibling, 'keydown', cbi_dynlist_keydown);
565 cbi_bind(t.nextSibling, 'keypress', cbi_dynlist_keypress);
567 if (i == focus || -i == focus)
568 t.nextSibling.focus();
572 cbi_bind(t, 'keydown', cbi_dynlist_keydown);
573 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
579 else if (-i == focus)
583 /* force cursor to end */
590 cbi_bind(b, 'click', cbi_dynlist_btnclick);
594 function cbi_dynlist_keypress(ev)
596 ev = ev ? ev : window.event;
598 var se = ev.target ? ev.target : ev.srcElement;
600 if (se.nodeType == 3)
605 /* backspace, delete */
608 if (se.value.length == 0)
610 if (ev.preventDefault)
618 /* enter, arrow up, arrow down */
622 if (ev.preventDefault)
631 function cbi_dynlist_keydown(ev)
633 ev = ev ? ev : window.event;
635 var se = ev.target ? ev.target : ev.srcElement;
637 if (se.nodeType == 3)
640 var prev = se.previousSibling;
641 while (prev && prev.name != name)
642 prev = prev.previousSibling;
644 var next = se.nextSibling;
645 while (next && next.name != name)
646 next = next.nextSibling;
648 /* advance one further in combobox case */
649 if (next && next.nextSibling.name == name)
650 next = next.nextSibling;
654 /* backspace, delete */
657 var del = (se.nodeName.toLowerCase() == 'select')
658 ? true : (se.value.length == 0);
662 if (ev.preventDefault)
665 var focus = se.index;
669 cbi_dynlist_redraw(focus, -1, se.index);
678 cbi_dynlist_redraw(-1, se.index, -1);
699 function cbi_dynlist_btnclick(ev)
701 ev = ev ? ev : window.event;
703 var se = ev.target ? ev.target : ev.srcElement;
705 if (se.src.indexOf('remove') > -1)
707 se.previousSibling.value = '';
709 cbi_dynlist_keydown({
710 target: se.previousSibling,
716 cbi_dynlist_keydown({
717 target: se.previousSibling,
725 cbi_dynlist_redraw(0, -1, -1);
728 //Hijacks the CBI form to send via XHR (requires Prototype)
729 function cbi_hijack_forms(layer, win, fail, load) {
730 var forms = layer.getElementsByTagName('form');
731 for (var i=0; i<forms.length; i++) {
732 $(forms[i]).observe('submit', function(event) {
733 // Prevent the form from also submitting the regular way
737 event.element().request({
750 function cbi_t_add(section, tab) {
751 var t = document.getElementById('tab.' + section + '.' + tab);
752 var c = document.getElementById('container.' + section + '.' + tab);
755 cbi_t[section] = (cbi_t[section] || [ ]);
756 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
760 function cbi_t_switch(section, tab) {
761 if( cbi_t[section] && cbi_t[section][tab] ) {
762 var o = cbi_t[section][tab];
763 var h = document.getElementById('tab.' + section);
764 for( var tid in cbi_t[section] ) {
765 var o2 = cbi_t[section][tid];
766 if( o.tab.id != o2.tab.id ) {
767 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
768 o2.container.style.display = 'none';
772 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
773 o2.container.style.display = 'block';
780 function cbi_t_update() {
784 for( var sid in cbi_t )
785 for( var tid in cbi_t[sid] )
787 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
788 cbi_t[sid][tid].tab.style.display = 'none';
790 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
791 cbi_t[sid][tid].tab.style.display = '';
793 var t = cbi_t[sid][tid].tab;
794 t.className += ' cbi-tab-highlighted';
798 cbi_tag_last(cbi_t[sid][tid].container);
802 if( hl_tabs.length > 0 )
803 window.setTimeout(function() {
804 for( var i = 0; i < hl_tabs.length; i++ )
805 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
812 function cbi_validate_form(form, errmsg)
814 /* if triggered by a section removal or addition, don't validate */
815 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
818 if( form.cbi_validators )
820 for( var i = 0; i < form.cbi_validators.length; i++ )
822 var validator = form.cbi_validators[i];
823 if( !validator() && errmsg )
834 function cbi_validate_reset(form)
837 function() { cbi_validate_form(form, null) }, 100
843 function cbi_validate_field(cbid, optional, type)
845 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
848 if( type.match(/^(\w+)\(([^\(\)]+)\)/) )
851 vargs = RegExp.$2.split(/\s*,\s*/);
854 var vldcb = cbi_validators[type];
858 var validator = function()
863 field.className = field.className.replace(/ cbi-input-invalid/g, '');
866 var value = (field.options && field.options.selectedIndex > -1)
867 ? field.options[field.options.selectedIndex].value : field.value;
869 if( !(((value.length == 0) && optional) || vldcb(value, vargs)) )
872 field.className += ' cbi-input-invalid';
880 if( ! field.form.cbi_validators )
881 field.form.cbi_validators = [ ];
883 field.form.cbi_validators.push(validator);
885 cbi_bind(field, "blur", validator);
886 cbi_bind(field, "keyup", validator);
888 if (field.nodeName == 'SELECT')
890 cbi_bind(field, "change", validator);
891 cbi_bind(field, "click", validator);
894 field.setAttribute("cbi_validate", validator);
895 field.setAttribute("cbi_datatype", type);
896 field.setAttribute("cbi_optional", (!!optional).toString());
900 var fcbox = document.getElementById('cbi.combobox.' + field.id);
902 cbi_validate_field(fcbox, optional, type);
906 function cbi_row_swap(elem, up, store)
908 var tr = elem.parentNode;
909 while (tr && tr.nodeName.toLowerCase() != 'tr')
915 var table = tr.parentNode;
916 while (table && table.nodeName.toLowerCase() != 'table')
917 table = table.parentNode;
923 var e = up ? table.rows.length : table.rows.length - 1;
925 for (var idx = s; idx < e; idx++)
927 if (table.rows[idx] == tr)
930 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
932 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
939 for (idx = 2; idx < table.rows.length; idx++)
941 table.rows[idx].className = table.rows[idx].className.replace(
942 /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
945 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
949 var input = document.getElementById(store);
951 input.value = ids.join(' ');
956 function cbi_tag_last(container)
960 for (var i = 0; i < container.childNodes.length; i++)
962 var c = container.childNodes[i];
963 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
965 c.className = c.className.replace(/ cbi-value-last$/, '');
972 last.className += ' cbi-value-last';
976 if( ! String.serialize )
977 String.serialize = function(o)
993 for( var i = 0; i < o.length; i++ )
994 s += (s ? ', ' : '') + String.serialize(o[i]);
996 return '[ ' + s + ' ]';
1005 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1007 return '{ ' + s + ' }';
1014 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1015 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1019 return '"' + o + '"';
1024 return o.toString();
1029 if( ! String.format )
1030 String.format = function()
1032 if (!arguments || arguments.length < 1 || !RegExp)
1035 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1036 var quot_esc = [/"/g, '"', /'/g, '''];
1038 function esc(s, r) {
1039 for( var i = 0; i < r.length; i += 2 )
1040 s = s.replace(r[i], r[i+1]);
1044 var str = arguments[0];
1046 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1047 var a = b = [], numSubstitutions = 0, numMatches = 0;
1049 while( a = re.exec(str) )
1052 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1053 var pPrecision = a[6], pType = a[7];
1063 if (numSubstitutions++ < arguments.length)
1065 var param = arguments[numSubstitutions];
1068 if (pPad && pPad.substr(0,1) == "'")
1069 pad = leftpart.substr(1,1);
1073 var justifyRight = true;
1074 if (pJustify && pJustify === "-")
1075 justifyRight = false;
1079 minLength = parseInt(pMinLength);
1082 if (pPrecision && pType == 'f')
1083 precision = parseInt(pPrecision.substring(1));
1090 subst = (parseInt(param) || 0).toString(2);
1094 subst = String.fromCharCode(parseInt(param) || 0);
1098 subst = (parseInt(param) || 0);
1102 subst = Math.abs(parseInt(param) || 0);
1106 subst = (precision > -1)
1107 ? ((parseFloat(param) || 0.0)).toFixed(precision)
1108 : (parseFloat(param) || 0.0);
1112 subst = (parseInt(param) || 0).toString(8);
1120 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1124 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1128 subst = esc(param, html_esc);
1132 subst = esc(param, quot_esc);
1136 subst = String.serialize(param);
1143 var ts = (param || 0);
1146 tm = Math.floor(ts / 60);
1151 th = Math.floor(tm / 60);
1156 td = Math.floor(th / 24);
1161 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1162 : String.format('%dh %dm %ds', th, tm, ts);
1167 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1168 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1171 var val = parseFloat(param || 0);
1172 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1174 for (i = 0; (i < units.length) && (val > mf); i++)
1177 subst = val.toFixed(pr) + ' ' + units[i];
1183 out += leftpart + subst;
1184 str = str.substr(m.length);