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 '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);
158 'wpakey': function(v)
161 return (v.match(/^[a-fA-F0-9]{64}$/) != null);
163 return (v.length >= 8) && (v.length <= 63);
166 'wepkey': function(v)
168 if( v.substr(0,2) == 's:' )
171 if( (v.length == 10) || (v.length == 26) )
172 return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
174 return (v.length == 5) || (v.length == 13);
177 'uciname': function(v)
179 return (v.match(/^[a-zA-Z0-9_]+$/) != null);
182 'range': function(v, args)
184 var min = parseInt(args[0]);
185 var max = parseInt(args[1]);
186 var val = parseInt(v);
188 if (!isNaN(min) && !isNaN(max) && !isNaN(val))
189 return ((val >= min) && (val <= max));
196 function cbi_d_add(field, dep, next) {
197 var obj = document.getElementById(field);
200 for (var i=0; i<cbi_d.length; i++) {
201 if (cbi_d[i].id == field) {
210 "parent": obj.parentNode.id,
214 cbi_d.unshift(entry);
220 function cbi_d_checkvalue(target, ref) {
221 var t = document.getElementById(target);
225 var tl = document.getElementsByName(target);
227 if( tl.length > 0 && tl[0].type == 'radio' )
228 for( var i = 0; i < tl.length; i++ )
229 if( tl[i].checked ) {
234 value = value ? value : "";
235 } else if (!t.value) {
240 if (t.type == "checkbox") {
241 value = t.checked ? value : "";
245 return (value == ref)
248 function cbi_d_check(deps) {
251 for (var i=0; i<deps.length; i++) {
254 for (var j in deps[i]) {
255 if (j == "!reverse") {
257 } else if (j == "!default") {
261 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
271 function cbi_d_update() {
273 for (var i=0; i<cbi_d.length; i++) {
274 var entry = cbi_d[i];
275 var next = document.getElementById(entry.next)
276 var node = document.getElementById(entry.id)
277 var parent = document.getElementById(entry.parent)
279 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
280 node.parentNode.removeChild(node);
283 cbi_c[entry.parent]--;
284 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
286 parent.appendChild(entry.node);
288 next.parentNode.insertBefore(entry.node, next);
292 cbi_c[entry.parent]++;
296 if (entry && entry.parent) {
305 function cbi_bind(obj, type, callback, mode) {
306 if (!obj.addEventListener) {
307 obj.attachEvent('on' + type,
309 var e = window.event;
311 if (!e.target && e.srcElement)
312 e.target = e.srcElement;
314 return !!callback(e);
318 obj.addEventListener(type, callback, !!mode);
323 function cbi_combobox(id, values, def, man) {
324 var selid = "cbi.combobox." + id;
325 if (document.getElementById(selid)) {
329 var obj = document.getElementById(id)
330 var sel = document.createElement("select");
332 sel.className = 'cbi-input-select';
334 if (obj.nextSibling) {
335 obj.parentNode.insertBefore(sel, obj.nextSibling);
337 obj.parentNode.appendChild(sel);
340 var dt = obj.getAttribute('cbi_datatype');
341 var op = obj.getAttribute('cbi_optional');
344 cbi_validate_field(sel, op == 'true', dt);
346 if (!values[obj.value]) {
347 if (obj.value == "") {
348 var optdef = document.createElement("option");
350 optdef.appendChild(document.createTextNode(def));
351 sel.appendChild(optdef);
353 var opt = document.createElement("option");
354 opt.value = obj.value;
355 opt.selected = "selected";
356 opt.appendChild(document.createTextNode(obj.value));
357 sel.appendChild(opt);
361 for (var i in values) {
362 var opt = document.createElement("option");
365 if (obj.value == i) {
366 opt.selected = "selected";
369 opt.appendChild(document.createTextNode(values[i]));
370 sel.appendChild(opt);
373 var optman = document.createElement("option");
375 optman.appendChild(document.createTextNode(man));
376 sel.appendChild(optman);
378 obj.style.display = "none";
380 cbi_bind(sel, "change", function() {
381 if (sel.selectedIndex == sel.options.length - 1) {
382 obj.style.display = "inline";
383 sel.parentNode.removeChild(sel);
386 obj.value = sel.options[sel.selectedIndex].value;
397 function cbi_combobox_init(id, values, def, man) {
398 var obj = document.getElementById(id);
399 cbi_bind(obj, "blur", function() {
400 cbi_combobox(id, values, def, man)
402 cbi_combobox(id, values, def, man);
405 function cbi_filebrowser(id, url, defpath) {
406 var field = document.getElementById(id);
407 var browser = window.open(
408 url + ( field.value || defpath || '' ) + '?field=' + id,
409 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
415 function cbi_browser_init(id, respath, url, defpath)
417 function cbi_browser_btnclick(e) {
418 cbi_filebrowser(id, url, defpath);
422 var field = document.getElementById(id);
424 var btn = document.createElement('img');
425 btn.className = 'cbi-image-button';
426 btn.src = respath + '/cbi/folder.gif';
427 field.parentNode.insertBefore(btn, field.nextSibling);
429 cbi_bind(btn, 'click', cbi_browser_btnclick);
432 function cbi_dynlist_init(name, respath)
434 function cbi_dynlist_renumber(e)
436 /* in a perfect world, we could just getElementsByName() - but not if
437 * MSIE is involved... */
438 var inputs = [ ]; // = document.getElementsByName(name);
439 for (var i = 0; i < e.parentNode.childNodes.length; i++)
440 if (e.parentNode.childNodes[i].name == name)
441 inputs.push(e.parentNode.childNodes[i]);
443 for (var i = 0; i < inputs.length; i++)
445 inputs[i].id = name + '.' + (i + 1);
446 inputs[i].nextSibling.src = respath + (
447 (i+1) < inputs.length ? '/cbi/remove.gif' : '/cbi/add.gif'
454 function cbi_dynlist_keypress(ev)
456 ev = ev ? ev : window.event;
458 var se = ev.target ? ev.target : ev.srcElement;
460 if (se.nodeType == 3)
465 /* backspace, delete */
468 if (se.value.length == 0)
470 if (ev.preventDefault)
478 /* enter, arrow up, arrow down */
482 if (ev.preventDefault)
491 function cbi_dynlist_keydown(ev)
493 ev = ev ? ev : window.event;
495 var se = ev.target ? ev.target : ev.srcElement;
497 if (se.nodeType == 3)
500 var prev = se.previousSibling;
501 while (prev && prev.name != name)
502 prev = prev.previousSibling;
504 var next = se.nextSibling;
505 while (next && next.name != name)
506 next = next.nextSibling;
510 /* backspace, delete */
513 var jump = (ev.keyCode == 8)
514 ? (prev || next) : (next || prev);
516 if (se.value.length == 0 && jump)
518 se.parentNode.removeChild(se.nextSibling.nextSibling);
519 se.parentNode.removeChild(se.nextSibling);
520 se.parentNode.removeChild(se);
522 cbi_dynlist_renumber(jump);
524 if (ev.preventDefault)
527 /* IE Quirk, needs double focus somehow */
537 var n = document.createElement('input');
541 var b = document.createElement('img');
543 cbi_bind(n, 'keydown', cbi_dynlist_keydown);
544 cbi_bind(n, 'keypress', cbi_dynlist_keypress);
545 cbi_bind(b, 'click', cbi_dynlist_btnclick);
549 se.parentNode.insertBefore(n, next);
550 se.parentNode.insertBefore(b, next);
551 se.parentNode.insertBefore(document.createElement('br'), next);
555 se.parentNode.appendChild(n);
556 se.parentNode.appendChild(b);
557 se.parentNode.appendChild(document.createElement('br'));
560 var dt = se.getAttribute('cbi_datatype');
561 var op = se.getAttribute('cbi_optional') == 'true';
564 cbi_validate_field(n, op, dt);
566 cbi_dynlist_renumber(n);
587 function cbi_dynlist_btnclick(ev)
589 ev = ev ? ev : window.event;
591 var se = ev.target ? ev.target : ev.srcElement;
593 if (se.src.indexOf('remove') > -1)
595 se.previousSibling.value = '';
597 cbi_dynlist_keydown({
598 target: se.previousSibling,
604 cbi_dynlist_keydown({
605 target: se.previousSibling,
613 var inputs = document.getElementsByName(name);
614 for( var i = 0; i < inputs.length; i++ )
616 var btn = document.createElement('img');
617 btn.className = 'cbi-image-button';
618 btn.src = respath + (
619 (i+1) < inputs.length ? '/cbi/remove.gif' : '/cbi/add.gif'
622 inputs[i].parentNode.insertBefore(btn, inputs[i].nextSibling);
624 cbi_bind(inputs[i], 'keydown', cbi_dynlist_keydown);
625 cbi_bind(inputs[i], 'keypress', cbi_dynlist_keypress);
626 cbi_bind(btn, 'click', cbi_dynlist_btnclick);
630 //Hijacks the CBI form to send via XHR (requires Prototype)
631 function cbi_hijack_forms(layer, win, fail, load) {
632 var forms = layer.getElementsByTagName('form');
633 for (var i=0; i<forms.length; i++) {
634 $(forms[i]).observe('submit', function(event) {
635 // Prevent the form from also submitting the regular way
639 event.element().request({
652 function cbi_t_add(section, tab) {
653 var t = document.getElementById('tab.' + section + '.' + tab);
654 var c = document.getElementById('container.' + section + '.' + tab);
657 cbi_t[section] = (cbi_t[section] || [ ]);
658 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
662 function cbi_t_switch(section, tab) {
663 if( cbi_t[section] && cbi_t[section][tab] ) {
664 var o = cbi_t[section][tab];
665 var h = document.getElementById('tab.' + section);
666 for( var tid in cbi_t[section] ) {
667 var o2 = cbi_t[section][tid];
668 if( o.tab.id != o2.tab.id ) {
669 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
670 o2.container.style.display = 'none';
674 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
675 o2.container.style.display = 'block';
682 function cbi_t_update() {
685 for( var sid in cbi_t )
686 for( var tid in cbi_t[sid] )
687 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
688 cbi_t[sid][tid].tab.style.display = 'none';
690 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
691 cbi_t[sid][tid].tab.style.display = '';
693 var t = cbi_t[sid][tid].tab;
694 t.className += ' cbi-tab-highlighted';
698 if( hl_tabs.length > 0 )
699 window.setTimeout(function() {
700 for( var i = 0; i < hl_tabs.length; i++ )
701 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
706 function cbi_validate_form(form, errmsg)
708 /* if triggered by a section removal or addition, don't validate */
709 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
712 if( form.cbi_validators )
714 for( var i = 0; i < form.cbi_validators.length; i++ )
716 var validator = form.cbi_validators[i];
717 if( !validator() && errmsg )
728 function cbi_validate_reset(form)
731 function() { cbi_validate_form(form, null) }, 100
737 function cbi_validate_field(cbid, optional, type)
739 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
742 if( type.match(/^(\w+)\(([^\(\)]+)\)/) )
745 vargs = RegExp.$2.split(/\s*,\s*/);
748 var vldcb = cbi_validators[type];
752 var validator = function()
757 field.className = field.className.replace(/ cbi-input-invalid/g, '');
760 var value = (field.options && field.options.selectedIndex > -1)
761 ? field.options[field.options.selectedIndex].value : field.value;
763 if( !(((value.length == 0) && optional) || vldcb(value, vargs)) )
766 field.className += ' cbi-input-invalid';
774 if( ! field.form.cbi_validators )
775 field.form.cbi_validators = [ ];
777 field.form.cbi_validators.push(validator);
779 cbi_bind(field, "blur", validator);
780 cbi_bind(field, "keyup", validator);
782 if (field.nodeName == 'SELECT')
784 cbi_bind(field, "change", validator);
785 cbi_bind(field, "click", validator);
788 field.setAttribute("cbi_validate", validator);
789 field.setAttribute("cbi_datatype", type);
790 field.setAttribute("cbi_optional", (!!optional).toString());
794 var fcbox = document.getElementById('cbi.combobox.' + field.id);
796 cbi_validate_field(fcbox, optional, type);
800 function cbi_row_swap(elem, up, store)
802 var tr = elem.parentNode;
803 while (tr && tr.nodeName.toLowerCase() != 'tr')
809 var table = tr.parentNode;
810 while (table && table.nodeName.toLowerCase() != 'table')
811 table = table.parentNode;
817 var e = up ? table.rows.length : table.rows.length - 1;
819 for (var idx = s; idx < e; idx++)
821 if (table.rows[idx] == tr)
824 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
826 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
833 for (idx = 2; idx < table.rows.length; idx++)
835 table.rows[idx].className = table.rows[idx].className.replace(
836 /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
839 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
843 var input = document.getElementById(store);
845 input.value = ids.join(' ');
850 if( ! String.serialize )
851 String.serialize = function(o)
867 for( var i = 0; i < o.length; i++ )
868 s += (s ? ', ' : '') + String.serialize(o[i]);
870 return '[ ' + s + ' ]';
879 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
881 return '{ ' + s + ' }';
888 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
889 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
893 return '"' + o + '"';
903 if( ! String.format )
904 String.format = function()
906 if (!arguments || arguments.length < 1 || !RegExp)
909 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
910 var quot_esc = [/"/g, '"', /'/g, '''];
913 for( var i = 0; i < r.length; i += 2 )
914 s = s.replace(r[i], r[i+1]);
918 var str = arguments[0];
920 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
921 var a = b = [], numSubstitutions = 0, numMatches = 0;
923 while( a = re.exec(str) )
926 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
927 var pPrecision = a[6], pType = a[7];
937 if (numSubstitutions++ < arguments.length)
939 var param = arguments[numSubstitutions];
942 if (pPad && pPad.substr(0,1) == "'")
943 pad = leftpart.substr(1,1);
947 var justifyRight = true;
948 if (pJustify && pJustify === "-")
949 justifyRight = false;
953 minLength = parseInt(pMinLength);
956 if (pPrecision && pType == 'f')
957 precision = parseInt(pPrecision.substring(1));
964 subst = (parseInt(param) || 0).toString(2);
968 subst = String.fromCharCode(parseInt(param) || 0);
972 subst = (parseInt(param) || 0);
976 subst = Math.abs(parseInt(param) || 0);
980 subst = (precision > -1)
981 ? ((parseFloat(param) || 0.0)).toFixed(precision)
982 : (parseFloat(param) || 0.0);
986 subst = (parseInt(param) || 0).toString(8);
994 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
998 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1002 subst = esc(param, html_esc);
1006 subst = esc(param, quot_esc);
1010 subst = String.serialize(param);
1017 var ts = (param || 0);
1020 tm = Math.floor(ts / 60);
1025 th = Math.floor(tm / 60);
1030 td = Math.floor(th / 24);
1035 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1036 : String.format('%dh %dm %ds', th, tm, ts);
1041 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1042 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1045 var val = parseFloat(param || 0);
1046 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1048 for (i = 0; (i < units.length) && (val > mf); i++)
1051 subst = val.toFixed(pr) + ' ' + units[i];
1057 out += leftpart + subst;
1058 str = str.substr(m.length);