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 'ip4addr': function(v)
47 if (v.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
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.$6.indexOf('.') < 0)
54 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
55 : (cbi_validators.ip4addr(RegExp.$6)))
62 'ip6addr': function(v)
64 if( v.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/) )
66 if( !RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)) )
75 if( addr.indexOf('.') > 0 )
77 var off = addr.lastIndexOf(':');
79 if( !(off && cbi_validators.ip4addr(addr.substr(off+1))) )
82 addr = addr.substr(0, off) + ':0:0';
85 if( addr.indexOf('::') >= 0 )
90 for( var i = 1; i < (addr.length-1); i++ )
91 if( addr.charAt(i) == ':' )
97 for( var i = 0; i < (7 - colons); i++ )
100 if (addr.match(/^(.*?)::(.*?)$/))
101 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
102 (RegExp.$2 ? ':' + RegExp.$2 : '');
105 return (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null);
114 return cbi_validators.integer(v) && (v >= 0) && (v <= 65535);
117 'portrange': function(v)
119 if( v.match(/^(\d+)-(\d+)$/) )
124 return cbi_validators.port(p1) &&
125 cbi_validators.port(p2) &&
126 (parseInt(p1) <= parseInt(p2))
131 return cbi_validators.port(v);
135 'macaddr': function(v)
137 return (v.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
142 return cbi_validators.hostname(v) || cbi_validators.ipaddr(v);
145 'hostname': function(v)
148 return (v.match(/^[a-zA-Z]+$/) != null ||
149 (v.match(/^[a-zA-Z0-9][a-zA-Z0-9\-.]*[a-zA-Z0-9]$/) &&
150 v.match(/[^0-9.]/)));
155 'network': function(v)
157 return cbi_validators.uciname(v) || cbi_validators.host(v);
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 'range': function(v, args)
186 var min = parseInt(args[0]);
187 var max = parseInt(args[1]);
188 var val = parseInt(v);
190 if (!isNaN(min) && !isNaN(max) && !isNaN(val))
191 return ((val >= min) && (val <= max));
196 'min': function(v, args)
198 var min = parseInt(args[0]);
199 var val = parseInt(v);
201 if (!isNaN(min) && !isNaN(val))
207 'max': function(v, args)
209 var max = parseInt(args[0]);
210 var val = parseInt(v);
212 if (!isNaN(max) && !isNaN(val))
218 'neg': function(v, args)
220 if (args[0] && typeof cbi_validators[args[0]] == "function")
221 return cbi_validators[args[0]](v.replace(/^\s*!\s*/, ''));
226 'list': function(v, args)
228 var cb = cbi_validators[args[0] || 'string'];
229 if (typeof cb == "function")
231 var cbargs = args.slice(1);
232 var values = v.match(/[^\s]+/g);
234 for (var i = 0; i < values.length; i++)
235 if (!cb(values[i], cbargs))
246 function cbi_d_add(field, dep, next) {
247 var obj = document.getElementById(field);
250 for (var i=0; i<cbi_d.length; i++) {
251 if (cbi_d[i].id == field) {
260 "parent": obj.parentNode.id,
264 cbi_d.unshift(entry);
270 function cbi_d_checkvalue(target, ref) {
271 var t = document.getElementById(target);
275 var tl = document.getElementsByName(target);
277 if( tl.length > 0 && tl[0].type == 'radio' )
278 for( var i = 0; i < tl.length; i++ )
279 if( tl[i].checked ) {
284 value = value ? value : "";
285 } else if (!t.value) {
290 if (t.type == "checkbox") {
291 value = t.checked ? value : "";
295 return (value == ref)
298 function cbi_d_check(deps) {
301 for (var i=0; i<deps.length; i++) {
304 for (var j in deps[i]) {
305 if (j == "!reverse") {
307 } else if (j == "!default") {
311 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
321 function cbi_d_update() {
323 for (var i=0; i<cbi_d.length; i++) {
324 var entry = cbi_d[i];
325 var next = document.getElementById(entry.next)
326 var node = document.getElementById(entry.id)
327 var parent = document.getElementById(entry.parent)
329 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
330 node.parentNode.removeChild(node);
333 cbi_c[entry.parent]--;
334 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
336 parent.appendChild(entry.node);
338 next.parentNode.insertBefore(entry.node, next);
342 cbi_c[entry.parent]++;
346 if (entry && entry.parent) {
348 cbi_tag_last(parent);
356 function cbi_bind(obj, type, callback, mode) {
357 if (!obj.addEventListener) {
358 obj.attachEvent('on' + type,
360 var e = window.event;
362 if (!e.target && e.srcElement)
363 e.target = e.srcElement;
365 return !!callback(e);
369 obj.addEventListener(type, callback, !!mode);
374 function cbi_combobox(id, values, def, man) {
375 var selid = "cbi.combobox." + id;
376 if (document.getElementById(selid)) {
380 var obj = document.getElementById(id)
381 var sel = document.createElement("select");
383 sel.className = 'cbi-input-select';
385 if (obj.nextSibling) {
386 obj.parentNode.insertBefore(sel, obj.nextSibling);
388 obj.parentNode.appendChild(sel);
391 var dt = obj.getAttribute('cbi_datatype');
392 var op = obj.getAttribute('cbi_optional');
395 cbi_validate_field(sel, op == 'true', dt);
397 if (!values[obj.value]) {
398 if (obj.value == "") {
399 var optdef = document.createElement("option");
401 optdef.appendChild(document.createTextNode(def));
402 sel.appendChild(optdef);
404 var opt = document.createElement("option");
405 opt.value = obj.value;
406 opt.selected = "selected";
407 opt.appendChild(document.createTextNode(obj.value));
408 sel.appendChild(opt);
412 for (var i in values) {
413 var opt = document.createElement("option");
416 if (obj.value == i) {
417 opt.selected = "selected";
420 opt.appendChild(document.createTextNode(values[i]));
421 sel.appendChild(opt);
424 var optman = document.createElement("option");
426 optman.appendChild(document.createTextNode(man));
427 sel.appendChild(optman);
429 obj.style.display = "none";
431 cbi_bind(sel, "change", function() {
432 if (sel.selectedIndex == sel.options.length - 1) {
433 obj.style.display = "inline";
434 sel.parentNode.removeChild(sel);
437 obj.value = sel.options[sel.selectedIndex].value;
448 function cbi_combobox_init(id, values, def, man) {
449 var obj = document.getElementById(id);
450 cbi_bind(obj, "blur", function() {
451 cbi_combobox(id, values, def, man)
453 cbi_combobox(id, values, def, man);
456 function cbi_filebrowser(id, url, defpath) {
457 var field = document.getElementById(id);
458 var browser = window.open(
459 url + ( field.value || defpath || '' ) + '?field=' + id,
460 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
466 function cbi_browser_init(id, respath, url, defpath)
468 function cbi_browser_btnclick(e) {
469 cbi_filebrowser(id, url, defpath);
473 var field = document.getElementById(id);
475 var btn = document.createElement('img');
476 btn.className = 'cbi-image-button';
477 btn.src = respath + '/cbi/folder.gif';
478 field.parentNode.insertBefore(btn, field.nextSibling);
480 cbi_bind(btn, 'click', cbi_browser_btnclick);
483 function cbi_dynlist_init(name, respath, datatype, optional, choices)
485 var input0 = document.getElementsByName(name)[0];
486 var prefix = input0.name;
487 var parent = input0.parentNode;
488 var holder = input0.placeholder;
492 function cbi_dynlist_redraw(focus, add, del)
496 while (parent.firstChild)
498 var n = parent.firstChild;
499 var i = parseInt(n.index);
503 if (n.nodeName.toLowerCase() == 'input')
504 values.push(n.value || '');
505 else if (n.nodeName.toLowerCase() == 'select')
506 values[values.length-1] = n.options[n.selectedIndex].value;
509 parent.removeChild(n);
515 values.splice(focus, 0, '');
517 else if (values.length == 0)
523 for (var i = 0; i < values.length; i++)
525 var t = document.createElement('input');
526 t.id = prefix + '.' + (i+1);
531 t.className = 'cbi-input-text';
533 if (i == 0 && holder)
535 t.placeholder = holder;
538 var b = document.createElement('img');
539 b.src = respath + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
540 b.className = 'cbi-image-button';
542 parent.appendChild(t);
543 parent.appendChild(b);
544 parent.appendChild(document.createElement('br'));
548 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
553 cbi_combobox_init(t.id, choices[0], '', choices[1]);
554 t.nextSibling.index = i;
556 cbi_bind(t.nextSibling, 'keydown', cbi_dynlist_keydown);
557 cbi_bind(t.nextSibling, 'keypress', cbi_dynlist_keypress);
559 if (i == focus || -i == focus)
560 t.nextSibling.focus();
564 cbi_bind(t, 'keydown', cbi_dynlist_keydown);
565 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
571 else if (-i == focus)
575 /* force cursor to end */
582 cbi_bind(b, 'click', cbi_dynlist_btnclick);
586 function cbi_dynlist_keypress(ev)
588 ev = ev ? ev : window.event;
590 var se = ev.target ? ev.target : ev.srcElement;
592 if (se.nodeType == 3)
597 /* backspace, delete */
600 if (se.value.length == 0)
602 if (ev.preventDefault)
610 /* enter, arrow up, arrow down */
614 if (ev.preventDefault)
623 function cbi_dynlist_keydown(ev)
625 ev = ev ? ev : window.event;
627 var se = ev.target ? ev.target : ev.srcElement;
629 if (se.nodeType == 3)
632 var prev = se.previousSibling;
633 while (prev && prev.name != name)
634 prev = prev.previousSibling;
636 var next = se.nextSibling;
637 while (next && next.name != name)
638 next = next.nextSibling;
640 /* advance one further in combobox case */
641 if (next && next.nextSibling.name == name)
642 next = next.nextSibling;
646 /* backspace, delete */
649 var del = (se.nodeName.toLowerCase() == 'select')
650 ? true : (se.value.length == 0);
654 if (ev.preventDefault)
657 var focus = se.index;
661 cbi_dynlist_redraw(focus, -1, se.index);
670 cbi_dynlist_redraw(-1, se.index, -1);
691 function cbi_dynlist_btnclick(ev)
693 ev = ev ? ev : window.event;
695 var se = ev.target ? ev.target : ev.srcElement;
697 if (se.src.indexOf('remove') > -1)
699 se.previousSibling.value = '';
701 cbi_dynlist_keydown({
702 target: se.previousSibling,
708 cbi_dynlist_keydown({
709 target: se.previousSibling,
717 cbi_dynlist_redraw(-1, -1, -1);
720 //Hijacks the CBI form to send via XHR (requires Prototype)
721 function cbi_hijack_forms(layer, win, fail, load) {
722 var forms = layer.getElementsByTagName('form');
723 for (var i=0; i<forms.length; i++) {
724 $(forms[i]).observe('submit', function(event) {
725 // Prevent the form from also submitting the regular way
729 event.element().request({
742 function cbi_t_add(section, tab) {
743 var t = document.getElementById('tab.' + section + '.' + tab);
744 var c = document.getElementById('container.' + section + '.' + tab);
747 cbi_t[section] = (cbi_t[section] || [ ]);
748 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
752 function cbi_t_switch(section, tab) {
753 if( cbi_t[section] && cbi_t[section][tab] ) {
754 var o = cbi_t[section][tab];
755 var h = document.getElementById('tab.' + section);
756 for( var tid in cbi_t[section] ) {
757 var o2 = cbi_t[section][tid];
758 if( o.tab.id != o2.tab.id ) {
759 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
760 o2.container.style.display = 'none';
764 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
765 o2.container.style.display = 'block';
772 function cbi_t_update() {
776 for( var sid in cbi_t )
777 for( var tid in cbi_t[sid] )
779 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
780 cbi_t[sid][tid].tab.style.display = 'none';
782 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
783 cbi_t[sid][tid].tab.style.display = '';
785 var t = cbi_t[sid][tid].tab;
786 t.className += ' cbi-tab-highlighted';
790 cbi_tag_last(cbi_t[sid][tid].container);
794 if( hl_tabs.length > 0 )
795 window.setTimeout(function() {
796 for( var i = 0; i < hl_tabs.length; i++ )
797 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
804 function cbi_validate_form(form, errmsg)
806 /* if triggered by a section removal or addition, don't validate */
807 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
810 if( form.cbi_validators )
812 for( var i = 0; i < form.cbi_validators.length; i++ )
814 var validator = form.cbi_validators[i];
815 if( !validator() && errmsg )
826 function cbi_validate_reset(form)
829 function() { cbi_validate_form(form, null) }, 100
835 function cbi_validate_field(cbid, optional, type)
837 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
840 if( type.match(/^(\w+)\(([^\(\)]+)\)/) )
843 vargs = RegExp.$2.split(/\s*,\s*/);
846 var vldcb = cbi_validators[type];
850 var validator = function()
855 field.className = field.className.replace(/ cbi-input-invalid/g, '');
858 var value = (field.options && field.options.selectedIndex > -1)
859 ? field.options[field.options.selectedIndex].value : field.value;
861 if( !(((value.length == 0) && optional) || vldcb(value, vargs)) )
864 field.className += ' cbi-input-invalid';
872 if( ! field.form.cbi_validators )
873 field.form.cbi_validators = [ ];
875 field.form.cbi_validators.push(validator);
877 cbi_bind(field, "blur", validator);
878 cbi_bind(field, "keyup", validator);
880 if (field.nodeName == 'SELECT')
882 cbi_bind(field, "change", validator);
883 cbi_bind(field, "click", validator);
886 field.setAttribute("cbi_validate", validator);
887 field.setAttribute("cbi_datatype", type);
888 field.setAttribute("cbi_optional", (!!optional).toString());
892 var fcbox = document.getElementById('cbi.combobox.' + field.id);
894 cbi_validate_field(fcbox, optional, type);
898 function cbi_row_swap(elem, up, store)
900 var tr = elem.parentNode;
901 while (tr && tr.nodeName.toLowerCase() != 'tr')
907 var table = tr.parentNode;
908 while (table && table.nodeName.toLowerCase() != 'table')
909 table = table.parentNode;
915 var e = up ? table.rows.length : table.rows.length - 1;
917 for (var idx = s; idx < e; idx++)
919 if (table.rows[idx] == tr)
922 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
924 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
931 for (idx = 2; idx < table.rows.length; idx++)
933 table.rows[idx].className = table.rows[idx].className.replace(
934 /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
937 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
941 var input = document.getElementById(store);
943 input.value = ids.join(' ');
948 function cbi_tag_last(container)
952 for (var i = 0; i < container.childNodes.length; i++)
954 var c = container.childNodes[i];
955 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
957 c.className = c.className.replace(/ cbi-value-last$/, '');
964 last.className += ' cbi-value-last';
968 if( ! String.serialize )
969 String.serialize = function(o)
985 for( var i = 0; i < o.length; i++ )
986 s += (s ? ', ' : '') + String.serialize(o[i]);
988 return '[ ' + s + ' ]';
997 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
999 return '{ ' + s + ' }';
1006 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1007 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1011 return '"' + o + '"';
1016 return o.toString();
1021 if( ! String.format )
1022 String.format = function()
1024 if (!arguments || arguments.length < 1 || !RegExp)
1027 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1028 var quot_esc = [/"/g, '"', /'/g, '''];
1030 function esc(s, r) {
1031 for( var i = 0; i < r.length; i += 2 )
1032 s = s.replace(r[i], r[i+1]);
1036 var str = arguments[0];
1038 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1039 var a = b = [], numSubstitutions = 0, numMatches = 0;
1041 while( a = re.exec(str) )
1044 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1045 var pPrecision = a[6], pType = a[7];
1055 if (numSubstitutions++ < arguments.length)
1057 var param = arguments[numSubstitutions];
1060 if (pPad && pPad.substr(0,1) == "'")
1061 pad = leftpart.substr(1,1);
1065 var justifyRight = true;
1066 if (pJustify && pJustify === "-")
1067 justifyRight = false;
1071 minLength = parseInt(pMinLength);
1074 if (pPrecision && pType == 'f')
1075 precision = parseInt(pPrecision.substring(1));
1082 subst = (parseInt(param) || 0).toString(2);
1086 subst = String.fromCharCode(parseInt(param) || 0);
1090 subst = (parseInt(param) || 0);
1094 subst = Math.abs(parseInt(param) || 0);
1098 subst = (precision > -1)
1099 ? ((parseFloat(param) || 0.0)).toFixed(precision)
1100 : (parseFloat(param) || 0.0);
1104 subst = (parseInt(param) || 0).toString(8);
1112 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1116 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1120 subst = esc(param, html_esc);
1124 subst = esc(param, quot_esc);
1128 subst = String.serialize(param);
1135 var ts = (param || 0);
1138 tm = Math.floor(ts / 60);
1143 th = Math.floor(tm / 60);
1148 td = Math.floor(th / 24);
1153 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1154 : String.format('%dh %dm %ds', th, tm, ts);
1159 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1160 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1163 var val = parseFloat(param || 0);
1164 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1166 for (i = 0; (i < units.length) && (val > mf); i++)
1169 subst = val.toFixed(pr) + ' ' + units[i];
1175 out += leftpart + subst;
1176 str = str.substr(m.length);