luci-base: cbi.js, ui.js: add custom validation callbacks, new ui widgets
[oweals/luci.git] / modules / luci-base / htdocs / luci-static / resources / cbi.js
1 /*
2         LuCI - Lua Configuration Interface
3
4         Copyright 2008 Steven Barth <steven@midlink.org>
5         Copyright 2008-2018 Jo-Philipp Wich <jo@mein.io>
6
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
10
11         http://www.apache.org/licenses/LICENSE-2.0
12 */
13
14 var cbi_d = [];
15 var cbi_strings = { path: {}, label: {} };
16
17 function s8(bytes, off) {
18         var n = bytes[off];
19         return (n > 0x7F) ? (n - 256) >>> 0 : n;
20 }
21
22 function u16(bytes, off) {
23         return ((bytes[off + 1] << 8) + bytes[off]) >>> 0;
24 }
25
26 function sfh(s) {
27         if (s === null || s.length === 0)
28                 return null;
29
30         var bytes = [];
31
32         for (var i = 0; i < s.length; i++) {
33                 var ch = s.charCodeAt(i);
34
35                 if (ch <= 0x7F)
36                         bytes.push(ch);
37                 else if (ch <= 0x7FF)
38                         bytes.push(((ch >>>  6) & 0x1F) | 0xC0,
39                                    ( ch         & 0x3F) | 0x80);
40                 else if (ch <= 0xFFFF)
41                         bytes.push(((ch >>> 12) & 0x0F) | 0xE0,
42                                    ((ch >>>  6) & 0x3F) | 0x80,
43                                    ( ch         & 0x3F) | 0x80);
44                 else if (code <= 0x10FFFF)
45                         bytes.push(((ch >>> 18) & 0x07) | 0xF0,
46                                    ((ch >>> 12) & 0x3F) | 0x80,
47                                    ((ch >>   6) & 0x3F) | 0x80,
48                                    ( ch         & 0x3F) | 0x80);
49         }
50
51         if (!bytes.length)
52                 return null;
53
54         var hash = (bytes.length >>> 0),
55             len = (bytes.length >>> 2),
56             off = 0, tmp;
57
58         while (len--) {
59                 hash += u16(bytes, off);
60                 tmp   = ((u16(bytes, off + 2) << 11) ^ hash) >>> 0;
61                 hash  = ((hash << 16) ^ tmp) >>> 0;
62                 hash += hash >>> 11;
63                 off  += 4;
64         }
65
66         switch ((bytes.length & 3) >>> 0) {
67         case 3:
68                 hash += u16(bytes, off);
69                 hash  = (hash ^ (hash << 16)) >>> 0;
70                 hash  = (hash ^ (s8(bytes, off + 2) << 18)) >>> 0;
71                 hash += hash >>> 11;
72                 break;
73
74         case 2:
75                 hash += u16(bytes, off);
76                 hash  = (hash ^ (hash << 11)) >>> 0;
77                 hash += hash >>> 17;
78                 break;
79
80         case 1:
81                 hash += s8(bytes, off);
82                 hash  = (hash ^ (hash << 10)) >>> 0;
83                 hash += hash >>> 1;
84                 break;
85         }
86
87         hash  = (hash ^ (hash << 3)) >>> 0;
88         hash += hash >>> 5;
89         hash  = (hash ^ (hash << 4)) >>> 0;
90         hash += hash >>> 17;
91         hash  = (hash ^ (hash << 25)) >>> 0;
92         hash += hash >>> 6;
93
94         return (0x100000000 + hash).toString(16).substr(1);
95 }
96
97 function _(s) {
98         return (window.TR && TR[sfh(s)]) || s;
99 }
100
101 function Int(x) {
102         return (/^-?\d+$/.test(x) ? +x : NaN);
103 }
104
105 function Dec(x) {
106         return (/^-?\d+(?:\.\d+)?$/.test(x) ? +x : NaN);
107 }
108
109 function IPv4(x) {
110         if (!x.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
111                 return null;
112
113         if (RegExp.$1 > 255 || RegExp.$2 > 255 || RegExp.$3 > 255 || RegExp.$4 > 255)
114                 return null;
115
116         return [ +RegExp.$1, +RegExp.$2, +RegExp.$3, +RegExp.$4 ];
117 }
118
119 function IPv6(x) {
120         if (x.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
121                 var v6 = RegExp.$1, v4 = IPv4(RegExp.$2);
122
123                 if (!v4)
124                         return null;
125
126                 x = v6 + ':' + (v4[0] * 256 + v4[1]).toString(16)
127                        + ':' + (v4[2] * 256 + v4[3]).toString(16);
128         }
129
130         if (!x.match(/^[a-fA-F0-9:]+$/))
131                 return null;
132
133         var prefix_suffix = x.split(/::/);
134
135         if (prefix_suffix.length > 2)
136                 return null;
137
138         var prefix = (prefix_suffix[0] || '0').split(/:/);
139         var suffix = prefix_suffix.length > 1 ? (prefix_suffix[1] || '0').split(/:/) : [];
140
141         if (suffix.length ? (prefix.length + suffix.length > 7)
142                           : ((prefix_suffix.length < 2 && prefix.length < 8) || prefix.length > 8))
143                 return null;
144
145         var i, word;
146         var words = [];
147
148         for (i = 0, word = parseInt(prefix[0], 16); i < prefix.length; word = parseInt(prefix[++i], 16))
149                 if (prefix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
150                         words.push(word);
151                 else
152                         return null;
153
154         for (i = 0; i < (8 - prefix.length - suffix.length); i++)
155                 words.push(0);
156
157         for (i = 0, word = parseInt(suffix[0], 16); i < suffix.length; word = parseInt(suffix[++i], 16))
158                 if (suffix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
159                         words.push(word);
160                 else
161                         return null;
162
163         return words;
164 }
165
166 var CBIValidatorPrototype = {
167         apply: function(name, value, args) {
168                 var func;
169
170                 if (typeof(name) === 'function')
171                         func = name;
172                 else if (typeof(this.types[name]) === 'function')
173                         func = this.types[name];
174                 else
175                         return false;
176
177                 if (value !== undefined && value !== null)
178                         this.value = value;
179
180                 return func.apply(this, args);
181         },
182
183         assert: function(condition, message) {
184                 if (!condition) {
185                         this.field.classList.add('cbi-input-invalid');
186                         this.error = message;
187                         return false;
188                 }
189
190                 this.field.classList.remove('cbi-input-invalid');
191                 this.error = null;
192                 return true;
193         },
194
195         compile: function(code) {
196                 var pos = 0;
197                 var esc = false;
198                 var depth = 0;
199                 var stack = [ ];
200
201                 code += ',';
202
203                 for (var i = 0; i < code.length; i++) {
204                         if (esc) {
205                                 esc = false;
206                                 continue;
207                         }
208
209                         switch (code.charCodeAt(i))
210                         {
211                         case 92:
212                                 esc = true;
213                                 break;
214
215                         case 40:
216                         case 44:
217                                 if (depth <= 0) {
218                                         if (pos < i) {
219                                                 var label = code.substring(pos, i);
220                                                         label = label.replace(/\\(.)/g, '$1');
221                                                         label = label.replace(/^[ \t]+/g, '');
222                                                         label = label.replace(/[ \t]+$/g, '');
223
224                                                 if (label && !isNaN(label)) {
225                                                         stack.push(parseFloat(label));
226                                                 }
227                                                 else if (label.match(/^(['"]).*\1$/)) {
228                                                         stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
229                                                 }
230                                                 else if (typeof this.types[label] == 'function') {
231                                                         stack.push(this.types[label]);
232                                                         stack.push(null);
233                                                 }
234                                                 else {
235                                                         throw "Syntax error, unhandled token '"+label+"'";
236                                                 }
237                                         }
238
239                                         pos = i+1;
240                                 }
241
242                                 depth += (code.charCodeAt(i) == 40);
243                                 break;
244
245                         case 41:
246                                 if (--depth <= 0) {
247                                         if (typeof stack[stack.length-2] != 'function')
248                                                 throw "Syntax error, argument list follows non-function";
249
250                                         stack[stack.length-1] = this.compile(code.substring(pos, i));
251                                         pos = i+1;
252                                 }
253
254                                 break;
255                         }
256                 }
257
258                 return stack;
259         },
260
261         validate: function() {
262                 /* element is detached */
263                 if (!findParent(this.field, 'body') && !findParent(this.field, '[data-field]'))
264                         return true;
265
266                 this.field.classList.remove('cbi-input-invalid');
267                 this.value = (this.field.value != null) ? this.field.value : '';
268                 this.error = null;
269
270                 var valid;
271
272                 if (this.value.length === 0)
273                         valid = this.assert(this.optional, _('non-empty value'));
274                 else
275                         valid = this.vstack[0].apply(this, this.vstack[1]);
276
277                 if (valid !== true) {
278                         this.field.setAttribute('data-tooltip', _('Expecting %s').format(this.error));
279                         this.field.setAttribute('data-tooltip-style', 'error');
280                         this.field.dispatchEvent(new CustomEvent('validation-failure', { bubbles: true }));
281                         return false;
282                 }
283
284                 if (typeof(this.vfunc) == 'function')
285                         valid = this.vfunc(this.value);
286
287                 if (valid !== true) {
288                         this.assert(false, valid);
289                         this.field.setAttribute('data-tooltip', valid);
290                         this.field.setAttribute('data-tooltip-style', 'error');
291                         this.field.dispatchEvent(new CustomEvent('validation-failure', { bubbles: true }));
292                         return false;
293                 }
294
295                 this.field.removeAttribute('data-tooltip');
296                 this.field.removeAttribute('data-tooltip-style');
297                 this.field.dispatchEvent(new CustomEvent('validation-success', { bubbles: true }));
298                 return true;
299         },
300
301         types: {
302                 integer: function() {
303                         return this.assert(Int(this.value) !== NaN, _('valid integer value'));
304                 },
305
306                 uinteger: function() {
307                         return this.assert(Int(this.value) >= 0, _('positive integer value'));
308                 },
309
310                 float: function() {
311                         return this.assert(Dec(this.value) !== NaN, _('valid decimal value'));
312                 },
313
314                 ufloat: function() {
315                         return this.assert(Dec(this.value) >= 0, _('positive decimal value'));
316                 },
317
318                 ipaddr: function(nomask) {
319                         return this.assert(this.apply('ip4addr', null, [nomask]) || this.apply('ip6addr', null, [nomask]),
320                                 nomask ? _('valid IP address') : _('valid IP address or prefix'));
321                 },
322
323                 ip4addr: function(nomask) {
324                         var re = nomask ? /^(\d+\.\d+\.\d+\.\d+)$/ : /^(\d+\.\d+\.\d+\.\d+)(?:\/(\d+\.\d+\.\d+\.\d+)|\/(\d{1,2}))?$/,
325                             m = this.value.match(re);
326
327                         return this.assert(m && IPv4(m[1]) && (m[2] ? IPv4(m[2]) : (m[3] ? this.apply('ip4prefix', m[3]) : true)),
328                                 nomask ? _('valid IPv4 address') : _('valid IPv4 address or network'));
329                 },
330
331                 ip6addr: function(nomask) {
332                         var re = nomask ? /^([0-9a-fA-F:.]+)$/ : /^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/,
333                             m = this.value.match(re);
334
335                         return this.assert(m && IPv6(m[1]) && (m[2] ? this.apply('ip6prefix', m[2]) : true),
336                                 nomask ? _('valid IPv6 address') : _('valid IPv6 address or prefix'));
337                 },
338
339                 ip4prefix: function() {
340                         return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 32,
341                                 _('valid IPv4 prefix value (0-32)'));
342                 },
343
344                 ip6prefix: function() {
345                         return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 128,
346                                 _('valid IPv6 prefix value (0-128)'));
347                 },
348
349                 cidr: function() {
350                         return this.assert(this.apply('cidr4') || this.apply('cidr6'), _('valid IPv4 or IPv6 CIDR'));
351                 },
352
353                 cidr4: function() {
354                         var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
355                         return this.assert(m && IPv4(m[1]) && this.apply('ip4prefix', m[2]), _('valid IPv4 CIDR'));
356                 },
357
358                 cidr6: function() {
359                         var m = this.value.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
360                         return this.assert(m && IPv6(m[1]) && this.apply('ip6prefix', m[2]), _('valid IPv6 CIDR'));
361                 },
362
363                 ipnet4: function() {
364                         var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
365                         return this.assert(m && IPv4(m[1]) && IPv4(m[2]), _('IPv4 network in address/netmask notation'));
366                 },
367
368                 ipnet6: function() {
369                         var m = this.value.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
370                         return this.assert(m && IPv6(m[1]) && IPv6(m[2]), _('IPv6 network in address/netmask notation'));
371                 },
372
373                 ip6hostid: function() {
374                         if (this.value == "eui64" || this.value == "random")
375                                 return true;
376
377                         var v6 = IPv6(this.value);
378                         return this.assert(!(!v6 || v6[0] || v6[1] || v6[2] || v6[3]), _('valid IPv6 host id'));
379                 },
380
381                 ipmask: function() {
382                         return this.assert(this.apply('ipmask4') || this.apply('ipmask6'),
383                                 _('valid network in address/netmask notation'));
384                 },
385
386                 ipmask4: function() {
387                         return this.assert(this.apply('cidr4') || this.apply('ipnet4') || this.apply('ip4addr'),
388                                 _('valid IPv4 network'));
389                 },
390
391                 ipmask6: function() {
392                         return this.assert(this.apply('cidr6') || this.apply('ipnet6') || this.apply('ip6addr'),
393                                 _('valid IPv6 network'));
394                 },
395
396                 port: function() {
397                         var p = Int(this.value);
398                         return this.assert(p >= 0 && p <= 65535, _('valid port value'));
399                 },
400
401                 portrange: function() {
402                         if (this.value.match(/^(\d+)-(\d+)$/)) {
403                                 var p1 = +RegExp.$1;
404                                 var p2 = +RegExp.$2;
405                                 return this.assert(p1 <= p2 && p2 <= 65535,
406                                         _('valid port or port range (port1-port2)'));
407                         }
408
409                         return this.assert(this.apply('port'), _('valid port or port range (port1-port2)'));
410                 },
411
412                 macaddr: function() {
413                         return this.assert(this.value.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null,
414                                 _('valid MAC address'));
415                 },
416
417                 host: function(ipv4only) {
418                         return this.assert(this.apply('hostname') || this.apply(ipv4only == 1 ? 'ip4addr' : 'ipaddr'),
419                                 _('valid hostname or IP address'));
420                 },
421
422                 hostname: function(strict) {
423                         if (this.value.length <= 253)
424                                 return this.assert(
425                                         (this.value.match(/^[a-zA-Z0-9_]+$/) != null ||
426                                                 (this.value.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
427                                                  this.value.match(/[^0-9.]/))) &&
428                                         (!strict || !this.value.match(/^_/)),
429                                         _('valid hostname'));
430
431                         return this.assert(false, _('valid hostname'));
432                 },
433
434                 network: function() {
435                         return this.assert(this.apply('uciname') || this.apply('host'),
436                                 _('valid UCI identifier, hostname or IP address'));
437                 },
438
439                 hostport: function(ipv4only) {
440                         var hp = this.value.split(/:/);
441                         return this.assert(hp.length == 2 && this.apply('host', hp[0], [ipv4only]) && this.apply('port', hp[1]),
442                                 _('valid host:port'));
443                 },
444
445                 ip4addrport: function() {
446                         var hp = this.value.split(/:/);
447                         return this.assert(hp.length == 2 && this.apply('ip4addr', hp[0], [true]) && this.apply('port', hp[1]),
448                                 _('valid IPv4 address:port'));
449                 },
450
451                 ipaddrport: function(bracket) {
452                         var m4 = this.value.match(/^([^\[\]:]+):(\d+)$/),
453                             m6 = this.value.match((bracket == 1) ? /^\[(.+)\]:(\d+)$/ : /^([^\[\]]+):(\d+)$/);
454
455                         if (m4)
456                                 return this.assert(this.apply('ip4addr', m4[1], [true]) && this.apply('port', m4[2]),
457                                         _('valid address:port'));
458
459                         return this.assert(m6 && this.apply('ip6addr', m6[1], [true]) && this.apply('port', m6[2]),
460                                 _('valid address:port'));
461                 },
462
463                 wpakey: function() {
464                         var v = this.value;
465
466                         if (v.length == 64)
467                                 return this.assert(v.match(/^[a-fA-F0-9]{64}$/), _('valid hexadecimal WPA key'));
468
469                         return this.assert((v.length >= 8) && (v.length <= 63), _('key between 8 and 63 characters'));
470                 },
471
472                 wepkey: function() {
473                         var v = this.value;
474
475                         if (v.substr(0, 2) === 's:')
476                                 v = v.substr(2);
477
478                         if ((v.length == 10) || (v.length == 26))
479                                 return this.assert(v.match(/^[a-fA-F0-9]{10,26}$/), _('valid hexadecimal WEP key'));
480
481                         return this.assert((v.length === 5) || (v.length === 13), _('key with either 5 or 13 characters'));
482                 },
483
484                 uciname: function() {
485                         return this.assert(this.value.match(/^[a-zA-Z0-9_]+$/), _('valid UCI identifier'));
486                 },
487
488                 range: function(min, max) {
489                         var val = Dec(this.value);
490                         return this.assert(val >= +min && val <= +max, _('value between %f and %f').format(min, max));
491                 },
492
493                 min: function(min) {
494                         return this.assert(Dec(this.value) >= +min, _('value greater or equal to %f').format(min));
495                 },
496
497                 max: function(max) {
498                         return this.assert(Dec(this.value) <= +max, _('value smaller or equal to %f').format(max));
499                 },
500
501                 rangelength: function(min, max) {
502                         var val = '' + this.value;
503                         return this.assert((val.length >= +min) && (val.length <= +max),
504                                 _('value between %d and %d characters').format(min, max));
505                 },
506
507                 minlength: function(min) {
508                         return this.assert((''+this.value).length >= +min,
509                                 _('value with at least %d characters').format(min));
510                 },
511
512                 maxlength: function(max) {
513                         return this.assert((''+this.value).length <= +max,
514                                 _('value with at most %d characters').format(max));
515                 },
516
517                 or: function() {
518                         var errors = [];
519
520                         for (var i = 0; i < arguments.length; i += 2) {
521                                 if (typeof arguments[i] != 'function') {
522                                         if (arguments[i] == this.value)
523                                                 return this.assert(true);
524                                         errors.push('"%s"'.format(arguments[i]));
525                                         i--;
526                                 }
527                                 else if (arguments[i].apply(this, arguments[i+1])) {
528                                         return this.assert(true);
529                                 }
530                                 else {
531                                         errors.push(this.error);
532                                 }
533                         }
534
535                         return this.assert(false, _('one of:\n - %s'.format(errors.join('\n - '))));
536                 },
537
538                 and: function() {
539                         for (var i = 0; i < arguments.length; i += 2) {
540                                 if (typeof arguments[i] != 'function') {
541                                         if (arguments[i] != this.value)
542                                                 return this.assert(false, '"%s"'.format(arguments[i]));
543                                         i--;
544                                 }
545                                 else if (!arguments[i].apply(this, arguments[i+1])) {
546                                         return this.assert(false, this.error);
547                                 }
548                         }
549
550                         return this.assert(true);
551                 },
552
553                 neg: function() {
554                         return this.apply('or', this.value.replace(/^[ \t]*![ \t]*/, ''), arguments);
555                 },
556
557                 list: function(subvalidator, subargs) {
558                         this.field.setAttribute('data-is-list', 'true');
559
560                         var tokens = this.value.match(/[^ \t]+/g);
561                         for (var i = 0; i < tokens.length; i++)
562                                 if (!this.apply(subvalidator, tokens[i], subargs))
563                                         return this.assert(false, this.error);
564
565                         return this.assert(true);
566                 },
567
568                 phonedigit: function() {
569                         return this.assert(this.value.match(/^[0-9\*#!\.]+$/),
570                                 _('valid phone digit (0-9, "*", "#", "!" or ".")'));
571                 },
572
573                 timehhmmss: function() {
574                         return this.assert(this.value.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/),
575                                 _('valid time (HH:MM:SS)'));
576                 },
577
578                 dateyyyymmdd: function() {
579                         if (this.value.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
580                                 var year  = +RegExp.$1,
581                                     month = +RegExp.$2,
582                                     day   = +RegExp.$3,
583                                     days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
584
585                                 function is_leap_year(year) {
586                                         return ((!(year % 4) && (year % 100)) || !(year % 400));
587                                 }
588
589                                 function get_days_in_month(month, year) {
590                                         return (month === 2 && is_leap_year(year)) ? 29 : days_in_month[month - 1];
591                                 }
592
593                                 /* Firewall rules in the past don't make sense */
594                                 return this.assert(year >= 2015 && month && month <= 12 && day && day <= get_days_in_month(month, year),
595                                         _('valid date (YYYY-MM-DD)'));
596
597                         }
598
599                         return this.assert(false, _('valid date (YYYY-MM-DD)'));
600                 },
601
602                 unique: function(subvalidator, subargs) {
603                         var ctx = this,
604                                 option = findParent(ctx.field, '[data-type][data-name]'),
605                             section = findParent(option, '.cbi-section'),
606                             query = '[data-type="%s"][data-name="%s"]'.format(option.getAttribute('data-type'), option.getAttribute('data-name')),
607                             unique = true;
608
609                         section.querySelectorAll(query).forEach(function(sibling) {
610                                 if (sibling === option)
611                                         return;
612
613                                 var values = L.dom.callClassMethod(sibling.querySelector('[data-idref]'), 'getValue');
614
615                                 if (!Array.isArray(values) && sibling.querySelector('[data-is-list]'))
616                                         values = String(values || '').match(/[^ \t]+/g) || [];
617                                 else if (!Array.isArray(values))
618                                         values = (values != null) ? [ values ] : [];
619
620                                 if (values.indexOf(ctx.value) != -1)
621                                         unique = false;
622                         });
623
624                         if (!unique)
625                                 return this.assert(false, _('unique value'));
626
627                         if (typeof(subvalidator) === 'function')
628                                 return this.apply(subvalidator, undefined, subargs);
629
630                         return this.assert(true);
631                 },
632
633                 hexstring: function() {
634                         return this.assert(this.value.match(/^([a-f0-9][a-f0-9]|[A-F0-9][A-F0-9])+$/),
635                                 _('hexadecimal encoded value'));
636                 },
637
638                 string: function() {
639                         return true;
640                 }
641         }
642 };
643
644 function CBIValidator(field, type, optional, vfunc)
645 {
646         this.field = field;
647         this.optional = optional;
648         this.vfunc = vfunc;
649         this.vstack = this.compile(type);
650 }
651
652 CBIValidator.prototype = CBIValidatorPrototype;
653
654
655 function cbi_d_add(field, dep, index) {
656         var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
657         if (obj) {
658                 var entry
659                 for (var i=0; i<cbi_d.length; i++) {
660                         if (cbi_d[i].id == obj.id) {
661                                 entry = cbi_d[i];
662                                 break;
663                         }
664                 }
665                 if (!entry) {
666                         entry = {
667                                 "node": obj,
668                                 "id": obj.id,
669                                 "parent": obj.parentNode.id,
670                                 "deps": [],
671                                 "index": index
672                         };
673                         cbi_d.unshift(entry);
674                 }
675                 entry.deps.push(dep)
676         }
677 }
678
679 function cbi_d_checkvalue(target, ref) {
680         var value = null,
681             query = 'input[id="'+target+'"], input[name="'+target+'"], ' +
682                     'select[id="'+target+'"], select[name="'+target+'"]';
683
684         document.querySelectorAll(query).forEach(function(i) {
685                 if (value === null && ((i.type !== 'radio' && i.type !== 'checkbox') || i.checked === true))
686                         value = i.value;
687         });
688
689         return (((value !== null) ? value : "") == ref);
690 }
691
692 function cbi_d_check(deps) {
693         var reverse;
694         var def = false;
695         for (var i=0; i<deps.length; i++) {
696                 var istat = true;
697                 reverse = false;
698                 for (var j in deps[i]) {
699                         if (j == "!reverse") {
700                                 reverse = true;
701                         } else if (j == "!default") {
702                                 def = true;
703                                 istat = false;
704                         } else {
705                                 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
706                         }
707                 }
708
709                 if (istat ^ reverse) {
710                         return true;
711                 }
712         }
713         return def;
714 }
715
716 function cbi_d_update() {
717         var state = false;
718         for (var i=0; i<cbi_d.length; i++) {
719                 var entry = cbi_d[i];
720                 var node  = document.getElementById(entry.id);
721                 var parent = document.getElementById(entry.parent);
722
723                 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
724                         node.parentNode.removeChild(node);
725                         state = true;
726                 }
727                 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
728                         var next = undefined;
729
730                         for (next = parent.firstChild; next; next = next.nextSibling) {
731                                 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
732                                         break;
733                         }
734
735                         if (!next)
736                                 parent.appendChild(entry.node);
737                         else
738                                 parent.insertBefore(entry.node, next);
739
740                         state = true;
741                 }
742
743                 // hide optionals widget if no choices remaining
744                 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
745                         parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
746         }
747
748         if (entry && entry.parent)
749                 cbi_tag_last(parent);
750
751         if (state)
752                 cbi_d_update();
753         else if (parent)
754                 parent.dispatchEvent(new CustomEvent('dependency-update', { bubbles: true }));
755 }
756
757 function cbi_init() {
758         var nodes;
759
760         document.querySelectorAll('.cbi-dropdown').forEach(function(node) {
761                 cbi_dropdown_init(node);
762                 node.addEventListener('cbi-dropdown-change', cbi_d_update);
763         });
764
765         nodes = document.querySelectorAll('[data-strings]');
766
767         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
768                 var str = JSON.parse(node.getAttribute('data-strings'));
769                 for (var key in str) {
770                         for (var key2 in str[key]) {
771                                 var dst = cbi_strings[key] || (cbi_strings[key] = { });
772                                     dst[key2] = str[key][key2];
773                         }
774                 }
775         }
776
777         nodes = document.querySelectorAll('[data-depends]');
778
779         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
780                 var index = parseInt(node.getAttribute('data-index'), 10);
781                 var depends = JSON.parse(node.getAttribute('data-depends'));
782                 if (!isNaN(index) && depends.length > 0) {
783                         for (var alt = 0; alt < depends.length; alt++)
784                                 cbi_d_add(node, depends[alt], index);
785                 }
786         }
787
788         nodes = document.querySelectorAll('[data-update]');
789
790         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
791                 var events = node.getAttribute('data-update').split(' ');
792                 for (var j = 0, event; (event = events[j]) !== undefined; j++)
793                         node.addEventListener(event, cbi_d_update);
794         }
795
796         nodes = document.querySelectorAll('[data-choices]');
797
798         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
799                 var choices = JSON.parse(node.getAttribute('data-choices')),
800                     options = {};
801
802                 for (var j = 0; j < choices[0].length; j++)
803                         options[choices[0][j]] = choices[1][j];
804
805                 var def = (node.getAttribute('data-optional') === 'true')
806                         ? node.placeholder || '' : null;
807
808                 var cb = new L.ui.Combobox(node.value, options, {
809                         name: node.getAttribute('name'),
810                         sort: choices[0],
811                         select_placeholder: def || _('-- Please choose --'),
812                         custom_placeholder: node.getAttribute('data-manual') || _('-- custom --')
813                 });
814
815                 var n = cb.render();
816                 n.addEventListener('cbi-dropdown-change', cbi_d_update);
817                 node.parentNode.replaceChild(n, node);
818         }
819
820         nodes = document.querySelectorAll('[data-dynlist]');
821
822         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
823                 var choices = JSON.parse(node.getAttribute('data-dynlist')),
824                     values = JSON.parse(node.getAttribute('data-values') || '[]'),
825                     options = null;
826
827                 if (choices[0] && choices[0].length) {
828                         options = {};
829
830                         for (var j = 0; j < choices[0].length; j++)
831                                 options[choices[0][j]] = choices[1][j];
832                 }
833
834                 var dl = new L.ui.DynamicList(values, options, {
835                         name: node.getAttribute('data-prefix'),
836                         sort: choices[0],
837                         datatype: choices[2],
838                         optional: choices[3],
839                         placeholder: node.getAttribute('data-placeholder')
840                 });
841
842                 var n = dl.render();
843                 n.addEventListener('cbi-dynlist-change', cbi_d_update);
844                 node.parentNode.replaceChild(n, node);
845         }
846
847         nodes = document.querySelectorAll('[data-type]');
848
849         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
850                 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
851                                    node.getAttribute('data-type'));
852         }
853
854         document.querySelectorAll('[data-browser]').forEach(cbi_browser_init);
855
856         document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
857                 s.parentNode.classList.add('cbi-tooltip-container');
858         });
859
860         document.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i) {
861                 var handler = function(ev) {
862                         var bits = this.name.split(/\./),
863                             section = document.getElementById('cbi-' + bits[2] + '-' + bits[3]);
864
865                     section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
866                 };
867
868                 i.addEventListener('mouseover', handler);
869                 i.addEventListener('mouseout', handler);
870         });
871
872         document.querySelectorAll('[data-ui-widget]').forEach(function(node) {
873                 var args = JSON.parse(node.getAttribute('data-ui-widget') || '[]'),
874                     widget = new (Function.prototype.bind.apply(L.ui[args[0]], args)),
875                     markup = widget.render();
876
877                 markup.addEventListener('widget-change', cbi_d_update);
878                 node.parentNode.replaceChild(markup, node);
879         });
880
881         cbi_d_update();
882 }
883
884 function cbi_filebrowser(id, defpath) {
885         var field   = L.dom.elem(id) ? id : document.getElementById(id);
886         var browser = window.open(
887                 cbi_strings.path.browser + (field.value || defpath || '') + '?field=' + field.id,
888                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
889         );
890
891         browser.focus();
892 }
893
894 function cbi_browser_init(field)
895 {
896         field.parentNode.insertBefore(
897                 E('img', {
898                         'src': L.resource('cbi/folder.gif'),
899                         'class': 'cbi-image-button',
900                         'click': function(ev) {
901                                 cbi_filebrowser(field, field.getAttribute('data-browser'));
902                                 ev.preventDefault();
903                         }
904                 }), field.nextSibling);
905 }
906
907 function cbi_validate_form(form, errmsg)
908 {
909         /* if triggered by a section removal or addition, don't validate */
910         if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
911                 return true;
912
913         if (form.cbi_validators) {
914                 for (var i = 0; i < form.cbi_validators.length; i++) {
915                         var validator = form.cbi_validators[i];
916
917                         if (!validator() && errmsg) {
918                                 alert(errmsg);
919                                 return false;
920                         }
921                 }
922         }
923
924         return true;
925 }
926
927 function cbi_validate_reset(form)
928 {
929         window.setTimeout(
930                 function() { cbi_validate_form(form, null) }, 100
931         );
932
933         return true;
934 }
935
936 function cbi_validate_field(cbid, optional, type)
937 {
938         var field = isElem(cbid) ? cbid : document.getElementById(cbid);
939         var validatorFn;
940
941         try {
942                 var cbiValidator = new CBIValidator(field, type, optional);
943                 validatorFn = cbiValidator.validate.bind(cbiValidator);
944         }
945         catch(e) {
946                 validatorFn = null;
947         };
948
949         if (validatorFn !== null) {
950                 var form = findParent(field, 'form');
951
952                 if (!form.cbi_validators)
953                         form.cbi_validators = [ ];
954
955                 form.cbi_validators.push(validatorFn);
956
957                 field.addEventListener("blur",  validatorFn);
958                 field.addEventListener("keyup", validatorFn);
959                 field.addEventListener("cbi-dropdown-change", validatorFn);
960
961                 if (matchesElem(field, 'select')) {
962                         field.addEventListener("change", validatorFn);
963                         field.addEventListener("click",  validatorFn);
964                 }
965
966                 validatorFn();
967         }
968 }
969
970 function cbi_row_swap(elem, up, store)
971 {
972         var tr = findParent(elem.parentNode, '.cbi-section-table-row');
973
974         if (!tr)
975                 return false;
976
977         tr.classList.remove('flash');
978
979         if (up) {
980                 var prev = tr.previousElementSibling;
981
982                 if (prev && prev.classList.contains('cbi-section-table-row'))
983                         tr.parentNode.insertBefore(tr, prev);
984                 else
985                         return;
986         }
987         else {
988                 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
989
990                 if (next && next.classList.contains('cbi-section-table-row'))
991                         tr.parentNode.insertBefore(tr, next);
992                 else if (!next)
993                         tr.parentNode.appendChild(tr);
994                 else
995                         return;
996         }
997
998         var ids = [ ];
999
1000         for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1001                 var node = tr.parentNode.childNodes[i];
1002                 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1003                         node.classList.remove('cbi-rowstyle-1');
1004                         node.classList.remove('cbi-rowstyle-2');
1005                         node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1006
1007                         if (/-([^\-]+)$/.test(node.id))
1008                                 ids.push(RegExp.$1);
1009                 }
1010         }
1011
1012         var input = document.getElementById(store);
1013         if (input)
1014                 input.value = ids.join(' ');
1015
1016         window.scrollTo(0, tr.offsetTop);
1017         void tr.offsetWidth;
1018         tr.classList.add('flash');
1019
1020         return false;
1021 }
1022
1023 function cbi_tag_last(container)
1024 {
1025         var last;
1026
1027         for (var i = 0; i < container.childNodes.length; i++) {
1028                 var c = container.childNodes[i];
1029                 if (matchesElem(c, 'div')) {
1030                         c.classList.remove('cbi-value-last');
1031                         last = c;
1032                 }
1033         }
1034
1035         if (last)
1036                 last.classList.add('cbi-value-last');
1037 }
1038
1039 function cbi_submit(elem, name, value, action)
1040 {
1041         var form = elem.form || findParent(elem, 'form');
1042
1043         if (!form)
1044                 return false;
1045
1046         if (action)
1047                 form.action = action;
1048
1049         if (name) {
1050                 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
1051                         E('input', { type: 'hidden', name: name });
1052
1053                 hidden.value = value || '1';
1054                 form.appendChild(hidden);
1055         }
1056
1057         form.submit();
1058         return true;
1059 }
1060
1061 String.prototype.format = function()
1062 {
1063         if (!RegExp)
1064                 return;
1065
1066         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
1067         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
1068
1069         function esc(s, r) {
1070                 if (typeof(s) !== 'string' && !(s instanceof String))
1071                         return '';
1072
1073                 for (var i = 0; i < r.length; i += 2)
1074                         s = s.replace(r[i], r[i+1]);
1075
1076                 return s;
1077         }
1078
1079         var str = this;
1080         var out = '';
1081         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1082         var a = b = [], numSubstitutions = 0, numMatches = 0;
1083
1084         while (a = re.exec(str)) {
1085                 var m = a[1];
1086                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1087                 var pPrecision = a[6], pType = a[7];
1088
1089                 numMatches++;
1090
1091                 if (pType == '%') {
1092                         subst = '%';
1093                 }
1094                 else {
1095                         if (numSubstitutions < arguments.length) {
1096                                 var param = arguments[numSubstitutions++];
1097
1098                                 var pad = '';
1099                                 if (pPad && pPad.substr(0,1) == "'")
1100                                         pad = leftpart.substr(1,1);
1101                                 else if (pPad)
1102                                         pad = pPad;
1103                                 else
1104                                         pad = ' ';
1105
1106                                 var justifyRight = true;
1107                                 if (pJustify && pJustify === "-")
1108                                         justifyRight = false;
1109
1110                                 var minLength = -1;
1111                                 if (pMinLength)
1112                                         minLength = +pMinLength;
1113
1114                                 var precision = -1;
1115                                 if (pPrecision && pType == 'f')
1116                                         precision = +pPrecision.substring(1);
1117
1118                                 var subst = param;
1119
1120                                 switch(pType) {
1121                                         case 'b':
1122                                                 subst = (+param || 0).toString(2);
1123                                                 break;
1124
1125                                         case 'c':
1126                                                 subst = String.fromCharCode(+param || 0);
1127                                                 break;
1128
1129                                         case 'd':
1130                                                 subst = ~~(+param || 0);
1131                                                 break;
1132
1133                                         case 'u':
1134                                                 subst = ~~Math.abs(+param || 0);
1135                                                 break;
1136
1137                                         case 'f':
1138                                                 subst = (precision > -1)
1139                                                         ? ((+param || 0.0)).toFixed(precision)
1140                                                         : (+param || 0.0);
1141                                                 break;
1142
1143                                         case 'o':
1144                                                 subst = (+param || 0).toString(8);
1145                                                 break;
1146
1147                                         case 's':
1148                                                 subst = param;
1149                                                 break;
1150
1151                                         case 'x':
1152                                                 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1153                                                 break;
1154
1155                                         case 'X':
1156                                                 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1157                                                 break;
1158
1159                                         case 'h':
1160                                                 subst = esc(param, html_esc);
1161                                                 break;
1162
1163                                         case 'q':
1164                                                 subst = esc(param, quot_esc);
1165                                                 break;
1166
1167                                         case 't':
1168                                                 var td = 0;
1169                                                 var th = 0;
1170                                                 var tm = 0;
1171                                                 var ts = (param || 0);
1172
1173                                                 if (ts > 60) {
1174                                                         tm = Math.floor(ts / 60);
1175                                                         ts = (ts % 60);
1176                                                 }
1177
1178                                                 if (tm > 60) {
1179                                                         th = Math.floor(tm / 60);
1180                                                         tm = (tm % 60);
1181                                                 }
1182
1183                                                 if (th > 24) {
1184                                                         td = Math.floor(th / 24);
1185                                                         th = (th % 24);
1186                                                 }
1187
1188                                                 subst = (td > 0)
1189                                                         ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1190                                                         : String.format('%dh %dm %ds', th, tm, ts);
1191
1192                                                 break;
1193
1194                                         case 'm':
1195                                                 var mf = pMinLength ? +pMinLength : 1000;
1196                                                 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1197
1198                                                 var i = 0;
1199                                                 var val = (+param || 0);
1200                                                 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1201
1202                                                 for (i = 0; (i < units.length) && (val > mf); i++)
1203                                                         val /= mf;
1204
1205                                                 subst = (i ? val.toFixed(pr) : val) + units[i];
1206                                                 pMinLength = null;
1207                                                 break;
1208                                 }
1209                         }
1210                 }
1211
1212                 if (pMinLength) {
1213                         subst = subst.toString();
1214                         for (var i = subst.length; i < pMinLength; i++)
1215                                 if (pJustify == '-')
1216                                         subst = subst + ' ';
1217                                 else
1218                                         subst = pad + subst;
1219                 }
1220
1221                 out += leftpart + subst;
1222                 str = str.substr(m.length);
1223         }
1224
1225         return out + str;
1226 }
1227
1228 String.prototype.nobr = function()
1229 {
1230         return this.replace(/[\s\n]+/g, '&#160;');
1231 }
1232
1233 String.format = function()
1234 {
1235         var a = [ ];
1236
1237         for (var i = 1; i < arguments.length; i++)
1238                 a.push(arguments[i]);
1239
1240         return ''.format.apply(arguments[0], a);
1241 }
1242
1243 String.nobr = function()
1244 {
1245         var a = [ ];
1246
1247         for (var i = 1; i < arguments.length; i++)
1248                 a.push(arguments[i]);
1249
1250         return ''.nobr.apply(arguments[0], a);
1251 }
1252
1253 if (window.NodeList && !NodeList.prototype.forEach) {
1254         NodeList.prototype.forEach = function (callback, thisArg) {
1255                 thisArg = thisArg || window;
1256                 for (var i = 0; i < this.length; i++) {
1257                         callback.call(thisArg, this[i], i, this);
1258                 }
1259         };
1260 }
1261
1262 if (!window.requestAnimationFrame) {
1263         window.requestAnimationFrame = function(f) {
1264                 window.setTimeout(function() {
1265                         f(new Date().getTime())
1266                 }, 1000/30);
1267         };
1268 }
1269
1270
1271 function isElem(e) { return L.dom.elem(e) }
1272 function toElem(s) { return L.dom.parse(s) }
1273 function matchesElem(node, selector) { return L.dom.matches(node, selector) }
1274 function findParent(node, selector) { return L.dom.parent(node, selector) }
1275 function E() { return L.dom.create.apply(L.dom, arguments) }
1276
1277 if (typeof(window.CustomEvent) !== 'function') {
1278         function CustomEvent(event, params) {
1279                 params = params || { bubbles: false, cancelable: false, detail: undefined };
1280                 var evt = document.createEvent('CustomEvent');
1281                     evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
1282                 return evt;
1283         }
1284
1285         CustomEvent.prototype = window.Event.prototype;
1286         window.CustomEvent = CustomEvent;
1287 }
1288
1289 function cbi_dropdown_init(sb) {
1290         var dl = new L.ui.Dropdown(sb, null, { name: sb.getAttribute('name') });
1291         return dl.bind(sb);
1292 }
1293
1294 function cbi_update_table(table, data, placeholder) {
1295         var target = isElem(table) ? table : document.querySelector(table);
1296
1297         if (!isElem(target))
1298                 return;
1299
1300         target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
1301                 var titles = [];
1302
1303                 thead.querySelectorAll('.th').forEach(function(th) {
1304                         titles.push(th);
1305                 });
1306
1307                 if (Array.isArray(data)) {
1308                         var n = 0, rows = target.querySelectorAll('.tr');
1309
1310                         data.forEach(function(row) {
1311                                 var trow = E('div', { 'class': 'tr' });
1312
1313                                 for (var i = 0; i < titles.length; i++) {
1314                                         var text = (titles[i].innerText || '').trim();
1315                                         var td = trow.appendChild(E('div', {
1316                                                 'class': titles[i].className,
1317                                                 'data-title': (text !== '') ? text : null
1318                                         }, row[i] || ''));
1319
1320                                         td.classList.remove('th');
1321                                         td.classList.add('td');
1322                                 }
1323
1324                                 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
1325
1326                                 if (rows[n])
1327                                         target.replaceChild(trow, rows[n]);
1328                                 else
1329                                         target.appendChild(trow);
1330                         });
1331
1332                         while (rows[++n])
1333                                 target.removeChild(rows[n]);
1334
1335                         if (placeholder && target.firstElementChild === target.lastElementChild) {
1336                                 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
1337                                 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
1338
1339                                 td.classList.remove('th');
1340                                 td.classList.add('td');
1341                         }
1342                 }
1343                 else {
1344                         thead.parentNode.style.display = 'none';
1345
1346                         thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
1347                                 if (trow !== thead) {
1348                                         var n = 0;
1349                                         trow.querySelectorAll('.th, .td').forEach(function(td) {
1350                                                 if (n < titles.length) {
1351                                                         var text = (titles[n++].innerText || '').trim();
1352                                                         if (text !== '')
1353                                                                 td.setAttribute('data-title', text);
1354                                                 }
1355                                         });
1356                                 }
1357                         });
1358
1359                         thead.parentNode.style.display = '';
1360                 }
1361         });
1362 }
1363
1364 function showModal(title, children)
1365 {
1366         return L.showModal(title, children);
1367 }
1368
1369 function hideModal()
1370 {
1371         return L.hideModal();
1372 }
1373
1374
1375 document.addEventListener('DOMContentLoaded', function() {
1376         document.addEventListener('validation-failure', function(ev) {
1377                 if (ev.target === document.activeElement)
1378                         L.showTooltip(ev);
1379         });
1380
1381         document.addEventListener('validation-success', function(ev) {
1382                 if (ev.target === document.activeElement)
1383                         L.hideTooltip(ev);
1384         });
1385
1386         document.querySelectorAll('.table').forEach(cbi_update_table);
1387 });