cbi.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  1. /*
  2. LuCI - Lua Configuration Interface
  3. Copyright 2008 Steven Barth <steven@midlink.org>
  4. Copyright 2008-2012 Jo-Philipp Wich <jow@openwrt.org>
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. */
  10. var cbi_d = [];
  11. var cbi_t = [];
  12. var cbi_strings = { path: {}, label: {} };
  13. function Int(x) {
  14. return (/^-?\d+$/.test(x) ? +x : NaN);
  15. }
  16. function Dec(x) {
  17. return (/^-?\d+(?:\.\d+)?$/.test(x) ? +x : NaN);
  18. }
  19. var cbi_validators = {
  20. 'integer': function()
  21. {
  22. return !!Int(this);
  23. },
  24. 'uinteger': function()
  25. {
  26. return (Int(this) >= 0);
  27. },
  28. 'float': function()
  29. {
  30. return !!Dec(this);
  31. },
  32. 'ufloat': function()
  33. {
  34. return (Dec(this) >= 0);
  35. },
  36. 'ipaddr': function()
  37. {
  38. return cbi_validators.ip4addr.apply(this) ||
  39. cbi_validators.ip6addr.apply(this);
  40. },
  41. 'ip4addr': function()
  42. {
  43. if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
  44. {
  45. return (RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
  46. (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
  47. (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
  48. (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
  49. ((RegExp.$6.indexOf('.') < 0)
  50. ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
  51. : (cbi_validators.ip4addr.apply(RegExp.$6)))
  52. ;
  53. }
  54. return false;
  55. },
  56. 'ip6addr': function()
  57. {
  58. if( this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/) )
  59. {
  60. if( !RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)) )
  61. {
  62. var addr = RegExp.$1;
  63. if( addr == '::' )
  64. {
  65. return true;
  66. }
  67. if( addr.indexOf('.') > 0 )
  68. {
  69. var off = addr.lastIndexOf(':');
  70. if( !(off && cbi_validators.ip4addr.apply(addr.substr(off+1))) )
  71. return false;
  72. addr = addr.substr(0, off) + ':0:0';
  73. }
  74. if( addr.indexOf('::') >= 0 )
  75. {
  76. var colons = 0;
  77. var fill = '0';
  78. for( var i = 1; i < (addr.length-1); i++ )
  79. if( addr.charAt(i) == ':' )
  80. colons++;
  81. if( colons > 7 )
  82. return false;
  83. for( var i = 0; i < (7 - colons); i++ )
  84. fill += ':0';
  85. if (addr.match(/^(.*?)::(.*?)$/))
  86. addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
  87. (RegExp.$2 ? ':' + RegExp.$2 : '');
  88. }
  89. return (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null);
  90. }
  91. }
  92. return false;
  93. },
  94. 'port': function()
  95. {
  96. var p = Int(this);
  97. return (p >= 0 && p <= 65535);
  98. },
  99. 'portrange': function()
  100. {
  101. if (this.match(/^(\d+)-(\d+)$/))
  102. {
  103. var p1 = +RegExp.$1;
  104. var p2 = +RegExp.$2;
  105. return (p1 <= p2 && p2 <= 65535);
  106. }
  107. return cbi_validators.port.apply(this);
  108. },
  109. 'macaddr': function()
  110. {
  111. return (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
  112. },
  113. 'host': function(ipv4only)
  114. {
  115. return cbi_validators.hostname.apply(this) ||
  116. ((ipv4only != 1) && cbi_validators.ipaddr.apply(this)) ||
  117. ((ipv4only == 1) && cb_validators.ip4addr.apply(this));
  118. },
  119. 'hostname': function()
  120. {
  121. if (this.length <= 253)
  122. return (this.match(/^[a-zA-Z0-9]+$/) != null ||
  123. (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
  124. this.match(/[^0-9.]/)));
  125. return false;
  126. },
  127. 'network': function()
  128. {
  129. return cbi_validators.uciname.apply(this) ||
  130. cbi_validators.host.apply(this);
  131. },
  132. 'hostport': function(ipv4only)
  133. {
  134. var hp = this.split(/:/);
  135. if (hp.length == 2)
  136. return (cbi_validators.host.apply(hp[0], ipv4only) &&
  137. cbi_validators.port.apply(hp[1]));
  138. return false;
  139. },
  140. 'ip4addrport': function()
  141. {
  142. var hp = this.split(/:/);
  143. if (hp.length == 2)
  144. return (cbi_validators.ipaddr.apply(hp[0]) &&
  145. cbi_validators.port.apply(hp[1]));
  146. return false;
  147. },
  148. 'ipaddrport': function(bracket)
  149. {
  150. if (this.match(/^([^\[\]:]+):([^:]+)$/)) {
  151. var addr = RegExp.$1
  152. var port = RegExp.$2
  153. return (cbi_validators.ip4addr.apply(addr) &&
  154. cbi_validators.port.apply(port));
  155. } else if ((bracket == 1) && (this.match(/^\[(.+)\]:([^:]+)$/))) {
  156. var addr = RegExp.$1
  157. var port = RegExp.$2
  158. return (cbi_validators.ip6addr.apply(addr) &&
  159. cbi_validators.port.apply(port));
  160. } else if ((bracket != 1) && (this.match(/^([^\[\]]+):([^:]+)$/))) {
  161. var addr = RegExp.$1
  162. var port = RegExp.$2
  163. return (cbi_validators.ip6addr.apply(addr) &&
  164. cbi_validators.port.apply(port));
  165. } else {
  166. return false;
  167. }
  168. },
  169. 'wpakey': function()
  170. {
  171. var v = this;
  172. if( v.length == 64 )
  173. return (v.match(/^[a-fA-F0-9]{64}$/) != null);
  174. else
  175. return (v.length >= 8) && (v.length <= 63);
  176. },
  177. 'wepkey': function()
  178. {
  179. var v = this;
  180. if ( v.substr(0,2) == 's:' )
  181. v = v.substr(2);
  182. if( (v.length == 10) || (v.length == 26) )
  183. return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
  184. else
  185. return (v.length == 5) || (v.length == 13);
  186. },
  187. 'uciname': function()
  188. {
  189. return (this.match(/^[a-zA-Z0-9_]+$/) != null);
  190. },
  191. 'range': function(min, max)
  192. {
  193. var val = Dec(this);
  194. return (val >= +min && val <= +max);
  195. },
  196. 'min': function(min)
  197. {
  198. return (Dec(this) >= +min);
  199. },
  200. 'max': function(max)
  201. {
  202. return (Dec(this) <= +max);
  203. },
  204. 'rangelength': function(min, max)
  205. {
  206. var val = '' + this;
  207. return ((val.length >= +min) && (val.length <= +max));
  208. },
  209. 'minlength': function(min)
  210. {
  211. return ((''+this).length >= +min);
  212. },
  213. 'maxlength': function(max)
  214. {
  215. return ((''+this).length <= +max);
  216. },
  217. 'or': function()
  218. {
  219. for (var i = 0; i < arguments.length; i += 2)
  220. {
  221. if (typeof arguments[i] != 'function')
  222. {
  223. if (arguments[i] == this)
  224. return true;
  225. i--;
  226. }
  227. else if (arguments[i].apply(this, arguments[i+1]))
  228. {
  229. return true;
  230. }
  231. }
  232. return false;
  233. },
  234. 'and': function()
  235. {
  236. for (var i = 0; i < arguments.length; i += 2)
  237. {
  238. if (typeof arguments[i] != 'function')
  239. {
  240. if (arguments[i] != this)
  241. return false;
  242. i--;
  243. }
  244. else if (!arguments[i].apply(this, arguments[i+1]))
  245. {
  246. return false;
  247. }
  248. }
  249. return true;
  250. },
  251. 'neg': function()
  252. {
  253. return cbi_validators.or.apply(
  254. this.replace(/^[ \t]*![ \t]*/, ''), arguments);
  255. },
  256. 'list': function(subvalidator, subargs)
  257. {
  258. if (typeof subvalidator != 'function')
  259. return false;
  260. var tokens = this.match(/[^ \t]+/g);
  261. for (var i = 0; i < tokens.length; i++)
  262. if (!subvalidator.apply(tokens[i], subargs))
  263. return false;
  264. return true;
  265. },
  266. 'phonedigit': function()
  267. {
  268. return (this.match(/^[0-9\*#!\.]+$/) != null);
  269. },
  270. 'timehhmmss': function()
  271. {
  272. return (this.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/) != null);
  273. },
  274. 'dateyyyymmdd': function()
  275. {
  276. if (this == null) {
  277. return false;
  278. }
  279. if (this.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
  280. var year = RegExp.$1;
  281. var month = RegExp.$2;
  282. var day = RegExp.$2
  283. var days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30 , 31, 30, 31 ];
  284. function is_leap_year(year) {
  285. return ((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0);
  286. }
  287. function get_days_in_month(month, year) {
  288. if ((month == 2) && is_leap_year(year)) {
  289. return 29;
  290. } else {
  291. return days_in_month[month];
  292. }
  293. }
  294. /* Firewall rules in the past don't make sense */
  295. if (year < 2015) {
  296. return false;
  297. }
  298. if ((month <= 0) || (month > 12)) {
  299. return false;
  300. }
  301. if ((day <= 0) || (day > get_days_in_month(month, year))) {
  302. return false;
  303. }
  304. return true;
  305. } else {
  306. return false;
  307. }
  308. }
  309. };
  310. function cbi_d_add(field, dep, index) {
  311. var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
  312. if (obj) {
  313. var entry
  314. for (var i=0; i<cbi_d.length; i++) {
  315. if (cbi_d[i].id == obj.id) {
  316. entry = cbi_d[i];
  317. break;
  318. }
  319. }
  320. if (!entry) {
  321. entry = {
  322. "node": obj,
  323. "id": obj.id,
  324. "parent": obj.parentNode.id,
  325. "deps": [],
  326. "index": index
  327. };
  328. cbi_d.unshift(entry);
  329. }
  330. entry.deps.push(dep)
  331. }
  332. }
  333. function cbi_d_checkvalue(target, ref) {
  334. var t = document.getElementById(target);
  335. var value;
  336. if (!t) {
  337. var tl = document.getElementsByName(target);
  338. if( tl.length > 0 && (tl[0].type == 'radio' || tl[0].type == 'checkbox'))
  339. for( var i = 0; i < tl.length; i++ )
  340. if( tl[i].checked ) {
  341. value = tl[i].value;
  342. break;
  343. }
  344. value = value ? value : "";
  345. } else if (!t.value) {
  346. value = "";
  347. } else {
  348. value = t.value;
  349. if (t.type == "checkbox") {
  350. value = t.checked ? value : "";
  351. }
  352. }
  353. return (value == ref)
  354. }
  355. function cbi_d_check(deps) {
  356. var reverse;
  357. var def = false;
  358. for (var i=0; i<deps.length; i++) {
  359. var istat = true;
  360. reverse = false;
  361. for (var j in deps[i]) {
  362. if (j == "!reverse") {
  363. reverse = true;
  364. } else if (j == "!default") {
  365. def = true;
  366. istat = false;
  367. } else {
  368. istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
  369. }
  370. }
  371. if (istat) {
  372. return !reverse;
  373. }
  374. }
  375. return def;
  376. }
  377. function cbi_d_update() {
  378. var state = false;
  379. for (var i=0; i<cbi_d.length; i++) {
  380. var entry = cbi_d[i];
  381. var node = document.getElementById(entry.id);
  382. var parent = document.getElementById(entry.parent);
  383. if (node && node.parentNode && !cbi_d_check(entry.deps)) {
  384. node.parentNode.removeChild(node);
  385. state = true;
  386. } else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
  387. var next = undefined;
  388. for (next = parent.firstChild; next; next = next.nextSibling) {
  389. if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index) {
  390. break;
  391. }
  392. }
  393. if (!next) {
  394. parent.appendChild(entry.node);
  395. } else {
  396. parent.insertBefore(entry.node, next);
  397. }
  398. state = true;
  399. }
  400. // hide optionals widget if no choices remaining
  401. if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
  402. parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
  403. }
  404. if (entry && entry.parent) {
  405. if (!cbi_t_update())
  406. cbi_tag_last(parent);
  407. }
  408. if (state) {
  409. cbi_d_update();
  410. }
  411. }
  412. function cbi_init() {
  413. var nodes;
  414. nodes = document.querySelectorAll('[data-strings]');
  415. for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
  416. var str = JSON.parse(node.getAttribute('data-strings'));
  417. for (var key in str) {
  418. for (var key2 in str[key]) {
  419. var dst = cbi_strings[key] || (cbi_strings[key] = { });
  420. dst[key2] = str[key][key2];
  421. }
  422. }
  423. }
  424. nodes = document.querySelectorAll('[data-depends]');
  425. for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
  426. var index = parseInt(node.getAttribute('data-index'), 10);
  427. var depends = JSON.parse(node.getAttribute('data-depends'));
  428. if (!isNaN(index) && depends.length > 0) {
  429. for (var alt = 0; alt < depends.length; alt++) {
  430. cbi_d_add(node, depends[alt], index);
  431. }
  432. }
  433. }
  434. nodes = document.querySelectorAll('[data-update]');
  435. for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
  436. var events = node.getAttribute('data-update').split(' ');
  437. for (var j = 0, event; (event = events[j]) !== undefined; j++) {
  438. cbi_bind(node, event, cbi_d_update);
  439. }
  440. }
  441. nodes = document.querySelectorAll('[data-type]');
  442. for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
  443. cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
  444. node.getAttribute('data-type'));
  445. }
  446. nodes = document.querySelectorAll('[data-choices]');
  447. for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
  448. var choices = JSON.parse(node.getAttribute('data-choices'));
  449. var options = {};
  450. for (var j = 0; j < choices[0].length; j++)
  451. options[choices[0][j]] = choices[1][j];
  452. var def = (node.getAttribute('data-optional') === 'true')
  453. ? node.placeholder || '' : null;
  454. cbi_combobox_init(node, options, def,
  455. node.getAttribute('data-manual'));
  456. }
  457. nodes = document.querySelectorAll('[data-dynlist]');
  458. for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
  459. var choices = JSON.parse(node.getAttribute('data-dynlist'));
  460. var options = null;
  461. if (choices[0] && choices[0].length) {
  462. options = {};
  463. for (var j = 0; j < choices[0].length; j++)
  464. options[choices[0][j]] = choices[1][j];
  465. }
  466. cbi_dynlist_init(node, choices[2], choices[3], options);
  467. }
  468. cbi_d_update();
  469. }
  470. function cbi_bind(obj, type, callback, mode) {
  471. if (!obj.addEventListener) {
  472. obj.attachEvent('on' + type,
  473. function(){
  474. var e = window.event;
  475. if (!e.target && e.srcElement)
  476. e.target = e.srcElement;
  477. return !!callback(e);
  478. }
  479. );
  480. } else {
  481. obj.addEventListener(type, callback, !!mode);
  482. }
  483. return obj;
  484. }
  485. function cbi_combobox(id, values, def, man, focus) {
  486. var selid = "cbi.combobox." + id;
  487. if (document.getElementById(selid)) {
  488. return
  489. }
  490. var obj = document.getElementById(id)
  491. var sel = document.createElement("select");
  492. sel.id = selid;
  493. sel.index = obj.index;
  494. sel.className = obj.className.replace(/cbi-input-text/, 'cbi-input-select');
  495. if (obj.nextSibling) {
  496. obj.parentNode.insertBefore(sel, obj.nextSibling);
  497. } else {
  498. obj.parentNode.appendChild(sel);
  499. }
  500. var dt = obj.getAttribute('cbi_datatype');
  501. var op = obj.getAttribute('cbi_optional');
  502. if (dt)
  503. cbi_validate_field(sel, op == 'true', dt);
  504. if (!values[obj.value]) {
  505. if (obj.value == "") {
  506. var optdef = document.createElement("option");
  507. optdef.value = "";
  508. optdef.appendChild(document.createTextNode(typeof(def) === 'string' ? def : cbi_strings.label.choose));
  509. sel.appendChild(optdef);
  510. } else {
  511. var opt = document.createElement("option");
  512. opt.value = obj.value;
  513. opt.selected = "selected";
  514. opt.appendChild(document.createTextNode(obj.value));
  515. sel.appendChild(opt);
  516. }
  517. }
  518. for (var i in values) {
  519. var opt = document.createElement("option");
  520. opt.value = i;
  521. if (obj.value == i) {
  522. opt.selected = "selected";
  523. }
  524. opt.appendChild(document.createTextNode(values[i]));
  525. sel.appendChild(opt);
  526. }
  527. var optman = document.createElement("option");
  528. optman.value = "";
  529. optman.appendChild(document.createTextNode(typeof(man) === 'string' ? man : cbi_strings.label.custom));
  530. sel.appendChild(optman);
  531. obj.style.display = "none";
  532. cbi_bind(sel, "change", function() {
  533. if (sel.selectedIndex == sel.options.length - 1) {
  534. obj.style.display = "inline";
  535. sel.blur();
  536. sel.parentNode.removeChild(sel);
  537. obj.focus();
  538. } else {
  539. obj.value = sel.options[sel.selectedIndex].value;
  540. }
  541. try {
  542. cbi_d_update();
  543. } catch (e) {
  544. //Do nothing
  545. }
  546. })
  547. // Retrigger validation in select
  548. if (focus) {
  549. sel.focus();
  550. sel.blur();
  551. }
  552. }
  553. function cbi_combobox_init(id, values, def, man) {
  554. var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
  555. cbi_bind(obj, "blur", function() {
  556. cbi_combobox(obj.id, values, def, man, true);
  557. });
  558. cbi_combobox(obj.id, values, def, man, false);
  559. }
  560. function cbi_filebrowser(id, defpath) {
  561. var field = document.getElementById(id);
  562. var browser = window.open(
  563. cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
  564. "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
  565. );
  566. browser.focus();
  567. }
  568. function cbi_browser_init(id, defpath)
  569. {
  570. function cbi_browser_btnclick(e) {
  571. cbi_filebrowser(id, defpath);
  572. return false;
  573. }
  574. var field = document.getElementById(id);
  575. var btn = document.createElement('img');
  576. btn.className = 'cbi-image-button';
  577. btn.src = cbi_strings.path.resource + '/cbi/folder.gif';
  578. field.parentNode.insertBefore(btn, field.nextSibling);
  579. cbi_bind(btn, 'click', cbi_browser_btnclick);
  580. }
  581. function cbi_dynlist_init(parent, datatype, optional, choices)
  582. {
  583. var prefix = parent.getAttribute('data-prefix');
  584. var holder = parent.getAttribute('data-placeholder');
  585. var values;
  586. function cbi_dynlist_redraw(focus, add, del)
  587. {
  588. values = [ ];
  589. while (parent.firstChild)
  590. {
  591. var n = parent.firstChild;
  592. var i = +n.index;
  593. if (i != del)
  594. {
  595. if (n.nodeName.toLowerCase() == 'input')
  596. values.push(n.value || '');
  597. else if (n.nodeName.toLowerCase() == 'select')
  598. values[values.length-1] = n.options[n.selectedIndex].value;
  599. }
  600. parent.removeChild(n);
  601. }
  602. if (add >= 0)
  603. {
  604. focus = add+1;
  605. values.splice(focus, 0, '');
  606. }
  607. else if (values.length == 0)
  608. {
  609. focus = 0;
  610. values.push('');
  611. }
  612. for (var i = 0; i < values.length; i++)
  613. {
  614. var t = document.createElement('input');
  615. t.id = prefix + '.' + (i+1);
  616. t.name = prefix;
  617. t.value = values[i];
  618. t.type = 'text';
  619. t.index = i;
  620. t.className = 'cbi-input-text';
  621. if (i == 0 && holder)
  622. {
  623. t.placeholder = holder;
  624. }
  625. var b = document.createElement('img');
  626. b.src = cbi_strings.path.resource + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
  627. b.className = 'cbi-image-button';
  628. parent.appendChild(t);
  629. parent.appendChild(b);
  630. if (datatype == 'file')
  631. {
  632. cbi_browser_init(t.id, parent.getAttribute('data-browser-path'));
  633. }
  634. parent.appendChild(document.createElement('br'));
  635. if (datatype)
  636. {
  637. cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
  638. }
  639. if (choices)
  640. {
  641. cbi_combobox_init(t.id, choices, '', cbi_strings.label.custom);
  642. b.index = i;
  643. cbi_bind(b, 'keydown', cbi_dynlist_keydown);
  644. cbi_bind(b, 'keypress', cbi_dynlist_keypress);
  645. if (i == focus || -i == focus)
  646. b.focus();
  647. }
  648. else
  649. {
  650. cbi_bind(t, 'keydown', cbi_dynlist_keydown);
  651. cbi_bind(t, 'keypress', cbi_dynlist_keypress);
  652. if (i == focus)
  653. {
  654. t.focus();
  655. }
  656. else if (-i == focus)
  657. {
  658. t.focus();
  659. /* force cursor to end */
  660. var v = t.value;
  661. t.value = ' '
  662. t.value = v;
  663. }
  664. }
  665. cbi_bind(b, 'click', cbi_dynlist_btnclick);
  666. }
  667. }
  668. function cbi_dynlist_keypress(ev)
  669. {
  670. ev = ev ? ev : window.event;
  671. var se = ev.target ? ev.target : ev.srcElement;
  672. if (se.nodeType == 3)
  673. se = se.parentNode;
  674. switch (ev.keyCode)
  675. {
  676. /* backspace, delete */
  677. case 8:
  678. case 46:
  679. if (se.value.length == 0)
  680. {
  681. if (ev.preventDefault)
  682. ev.preventDefault();
  683. return false;
  684. }
  685. return true;
  686. /* enter, arrow up, arrow down */
  687. case 13:
  688. case 38:
  689. case 40:
  690. if (ev.preventDefault)
  691. ev.preventDefault();
  692. return false;
  693. }
  694. return true;
  695. }
  696. function cbi_dynlist_keydown(ev)
  697. {
  698. ev = ev ? ev : window.event;
  699. var se = ev.target ? ev.target : ev.srcElement;
  700. if (se.nodeType == 3)
  701. se = se.parentNode;
  702. var prev = se.previousSibling;
  703. while (prev && prev.name != prefix)
  704. prev = prev.previousSibling;
  705. var next = se.nextSibling;
  706. while (next && next.name != prefix)
  707. next = next.nextSibling;
  708. /* advance one further in combobox case */
  709. if (next && next.nextSibling.name == prefix)
  710. next = next.nextSibling;
  711. switch (ev.keyCode)
  712. {
  713. /* backspace, delete */
  714. case 8:
  715. case 46:
  716. var del = (se.nodeName.toLowerCase() == 'select')
  717. ? true : (se.value.length == 0);
  718. if (del)
  719. {
  720. if (ev.preventDefault)
  721. ev.preventDefault();
  722. var focus = se.index;
  723. if (ev.keyCode == 8)
  724. focus = -focus+1;
  725. cbi_dynlist_redraw(focus, -1, se.index);
  726. return false;
  727. }
  728. break;
  729. /* enter */
  730. case 13:
  731. cbi_dynlist_redraw(-1, se.index, -1);
  732. break;
  733. /* arrow up */
  734. case 38:
  735. if (prev)
  736. prev.focus();
  737. break;
  738. /* arrow down */
  739. case 40:
  740. if (next)
  741. next.focus();
  742. break;
  743. }
  744. return true;
  745. }
  746. function cbi_dynlist_btnclick(ev)
  747. {
  748. ev = ev ? ev : window.event;
  749. var se = ev.target ? ev.target : ev.srcElement;
  750. var input = se.previousSibling;
  751. while (input && input.name != prefix) {
  752. input = input.previousSibling;
  753. }
  754. if (se.src.indexOf('remove') > -1)
  755. {
  756. input.value = '';
  757. cbi_dynlist_keydown({
  758. target: input,
  759. keyCode: 8
  760. });
  761. }
  762. else
  763. {
  764. cbi_dynlist_keydown({
  765. target: input,
  766. keyCode: 13
  767. });
  768. }
  769. return false;
  770. }
  771. cbi_dynlist_redraw(NaN, -1, -1);
  772. }
  773. function cbi_t_add(section, tab) {
  774. var t = document.getElementById('tab.' + section + '.' + tab);
  775. var c = document.getElementById('container.' + section + '.' + tab);
  776. if( t && c ) {
  777. cbi_t[section] = (cbi_t[section] || [ ]);
  778. cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
  779. }
  780. }
  781. function cbi_t_switch(section, tab) {
  782. if( cbi_t[section] && cbi_t[section][tab] ) {
  783. var o = cbi_t[section][tab];
  784. var h = document.getElementById('tab.' + section);
  785. for( var tid in cbi_t[section] ) {
  786. var o2 = cbi_t[section][tid];
  787. if( o.tab.id != o2.tab.id ) {
  788. o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
  789. o2.container.style.display = 'none';
  790. }
  791. else {
  792. if(h) h.value = tab;
  793. o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
  794. o2.container.style.display = 'block';
  795. }
  796. }
  797. }
  798. return false
  799. }
  800. function cbi_t_update() {
  801. var hl_tabs = [ ];
  802. var updated = false;
  803. for( var sid in cbi_t )
  804. for( var tid in cbi_t[sid] )
  805. {
  806. var t = cbi_t[sid][tid].tab;
  807. var c = cbi_t[sid][tid].container;
  808. if (!c.firstElementChild) {
  809. t.style.display = 'none';
  810. }
  811. else if (t.style.display == 'none') {
  812. t.style.display = '';
  813. t.className += ' cbi-tab-highlighted';
  814. hl_tabs.push(t);
  815. }
  816. cbi_tag_last(c);
  817. updated = true;
  818. }
  819. if (hl_tabs.length > 0)
  820. window.setTimeout(function() {
  821. for( var i = 0; i < hl_tabs.length; i++ )
  822. hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
  823. }, 750);
  824. return updated;
  825. }
  826. function cbi_validate_form(form, errmsg)
  827. {
  828. /* if triggered by a section removal or addition, don't validate */
  829. if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
  830. return true;
  831. if( form.cbi_validators )
  832. {
  833. for( var i = 0; i < form.cbi_validators.length; i++ )
  834. {
  835. var validator = form.cbi_validators[i];
  836. if( !validator() && errmsg )
  837. {
  838. alert(errmsg);
  839. return false;
  840. }
  841. }
  842. }
  843. return true;
  844. }
  845. function cbi_validate_reset(form)
  846. {
  847. window.setTimeout(
  848. function() { cbi_validate_form(form, null) }, 100
  849. );
  850. return true;
  851. }
  852. function cbi_validate_compile(code)
  853. {
  854. var pos = 0;
  855. var esc = false;
  856. var depth = 0;
  857. var stack = [ ];
  858. code += ',';
  859. for (var i = 0; i < code.length; i++)
  860. {
  861. if (esc)
  862. {
  863. esc = false;
  864. continue;
  865. }
  866. switch (code.charCodeAt(i))
  867. {
  868. case 92:
  869. esc = true;
  870. break;
  871. case 40:
  872. case 44:
  873. if (depth <= 0)
  874. {
  875. if (pos < i)
  876. {
  877. var label = code.substring(pos, i);
  878. label = label.replace(/\\(.)/g, '$1');
  879. label = label.replace(/^[ \t]+/g, '');
  880. label = label.replace(/[ \t]+$/g, '');
  881. if (label && !isNaN(label))
  882. {
  883. stack.push(parseFloat(label));
  884. }
  885. else if (label.match(/^(['"]).*\1$/))
  886. {
  887. stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
  888. }
  889. else if (typeof cbi_validators[label] == 'function')
  890. {
  891. stack.push(cbi_validators[label]);
  892. stack.push(null);
  893. }
  894. else
  895. {
  896. throw "Syntax error, unhandled token '"+label+"'";
  897. }
  898. }
  899. pos = i+1;
  900. }
  901. depth += (code.charCodeAt(i) == 40);
  902. break;
  903. case 41:
  904. if (--depth <= 0)
  905. {
  906. if (typeof stack[stack.length-2] != 'function')
  907. throw "Syntax error, argument list follows non-function";
  908. stack[stack.length-1] =
  909. arguments.callee(code.substring(pos, i));
  910. pos = i+1;
  911. }
  912. break;
  913. }
  914. }
  915. return stack;
  916. }
  917. function cbi_validate_field(cbid, optional, type)
  918. {
  919. var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
  920. var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
  921. if (field && vstack && typeof vstack[0] == "function")
  922. {
  923. var validator = function()
  924. {
  925. // is not detached
  926. if( field.form )
  927. {
  928. field.className = field.className.replace(/ cbi-input-invalid/g, '');
  929. // validate value
  930. var value = (field.options && field.options.selectedIndex > -1)
  931. ? field.options[field.options.selectedIndex].value : field.value;
  932. if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
  933. {
  934. // invalid
  935. field.className += ' cbi-input-invalid';
  936. return false;
  937. }
  938. }
  939. return true;
  940. };
  941. if( ! field.form.cbi_validators )
  942. field.form.cbi_validators = [ ];
  943. field.form.cbi_validators.push(validator);
  944. cbi_bind(field, "blur", validator);
  945. cbi_bind(field, "keyup", validator);
  946. if (field.nodeName == 'SELECT')
  947. {
  948. cbi_bind(field, "change", validator);
  949. cbi_bind(field, "click", validator);
  950. }
  951. field.setAttribute("cbi_validate", validator);
  952. field.setAttribute("cbi_datatype", type);
  953. field.setAttribute("cbi_optional", (!!optional).toString());
  954. validator();
  955. var fcbox = document.getElementById('cbi.combobox.' + field.id);
  956. if (fcbox)
  957. cbi_validate_field(fcbox, optional, type);
  958. }
  959. }
  960. function cbi_row_swap(elem, up, store)
  961. {
  962. var tr = elem.parentNode;
  963. while (tr && tr.nodeName.toLowerCase() != 'tr')
  964. tr = tr.parentNode;
  965. if (!tr)
  966. return false;
  967. var table = tr.parentNode;
  968. while (table && table.nodeName.toLowerCase() != 'table')
  969. table = table.parentNode;
  970. if (!table)
  971. return false;
  972. var s = up ? 3 : 2;
  973. var e = up ? table.rows.length : table.rows.length - 1;
  974. for (var idx = s; idx < e; idx++)
  975. {
  976. if (table.rows[idx] == tr)
  977. {
  978. if (up)
  979. tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
  980. else
  981. tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
  982. break;
  983. }
  984. }
  985. var ids = [ ];
  986. for (idx = 2; idx < table.rows.length; idx++)
  987. {
  988. table.rows[idx].className = table.rows[idx].className.replace(
  989. /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
  990. );
  991. if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
  992. ids.push(RegExp.$1);
  993. }
  994. var input = document.getElementById(store);
  995. if (input)
  996. input.value = ids.join(' ');
  997. return false;
  998. }
  999. function cbi_tag_last(container)
  1000. {
  1001. var last;
  1002. for (var i = 0; i < container.childNodes.length; i++)
  1003. {
  1004. var c = container.childNodes[i];
  1005. if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
  1006. {
  1007. c.className = c.className.replace(/ cbi-value-last$/, '');
  1008. last = c;
  1009. }
  1010. }
  1011. if (last)
  1012. {
  1013. last.className += ' cbi-value-last';
  1014. }
  1015. }
  1016. String.prototype.serialize = function()
  1017. {
  1018. var o = this;
  1019. switch(typeof(o))
  1020. {
  1021. case 'object':
  1022. // null
  1023. if( o == null )
  1024. {
  1025. return 'null';
  1026. }
  1027. // array
  1028. else if( o.length )
  1029. {
  1030. var i, s = '';
  1031. for( var i = 0; i < o.length; i++ )
  1032. s += (s ? ', ' : '') + String.serialize(o[i]);
  1033. return '[ ' + s + ' ]';
  1034. }
  1035. // object
  1036. else
  1037. {
  1038. var k, s = '';
  1039. for( k in o )
  1040. s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
  1041. return '{ ' + s + ' }';
  1042. }
  1043. break;
  1044. case 'string':
  1045. // complex string
  1046. if( o.match(/[^a-zA-Z0-9_,.: -]/) )
  1047. return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
  1048. // simple string
  1049. else
  1050. return '"' + o + '"';
  1051. break;
  1052. default:
  1053. return o.toString();
  1054. }
  1055. }
  1056. String.prototype.format = function()
  1057. {
  1058. if (!RegExp)
  1059. return;
  1060. var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
  1061. var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
  1062. function esc(s, r) {
  1063. if (typeof(s) !== 'string' && !(s instanceof String))
  1064. return '';
  1065. for( var i = 0; i < r.length; i += 2 )
  1066. s = s.replace(r[i], r[i+1]);
  1067. return s;
  1068. }
  1069. var str = this;
  1070. var out = '';
  1071. var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
  1072. var a = b = [], numSubstitutions = 0, numMatches = 0;
  1073. while (a = re.exec(str))
  1074. {
  1075. var m = a[1];
  1076. var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
  1077. var pPrecision = a[6], pType = a[7];
  1078. numMatches++;
  1079. if (pType == '%')
  1080. {
  1081. subst = '%';
  1082. }
  1083. else
  1084. {
  1085. if (numSubstitutions < arguments.length)
  1086. {
  1087. var param = arguments[numSubstitutions++];
  1088. var pad = '';
  1089. if (pPad && pPad.substr(0,1) == "'")
  1090. pad = leftpart.substr(1,1);
  1091. else if (pPad)
  1092. pad = pPad;
  1093. else
  1094. pad = ' ';
  1095. var justifyRight = true;
  1096. if (pJustify && pJustify === "-")
  1097. justifyRight = false;
  1098. var minLength = -1;
  1099. if (pMinLength)
  1100. minLength = +pMinLength;
  1101. var precision = -1;
  1102. if (pPrecision && pType == 'f')
  1103. precision = +pPrecision.substring(1);
  1104. var subst = param;
  1105. switch(pType)
  1106. {
  1107. case 'b':
  1108. subst = (+param || 0).toString(2);
  1109. break;
  1110. case 'c':
  1111. subst = String.fromCharCode(+param || 0);
  1112. break;
  1113. case 'd':
  1114. subst = ~~(+param || 0);
  1115. break;
  1116. case 'u':
  1117. subst = ~~Math.abs(+param || 0);
  1118. break;
  1119. case 'f':
  1120. subst = (precision > -1)
  1121. ? ((+param || 0.0)).toFixed(precision)
  1122. : (+param || 0.0);
  1123. break;
  1124. case 'o':
  1125. subst = (+param || 0).toString(8);
  1126. break;
  1127. case 's':
  1128. subst = param;
  1129. break;
  1130. case 'x':
  1131. subst = ('' + (+param || 0).toString(16)).toLowerCase();
  1132. break;
  1133. case 'X':
  1134. subst = ('' + (+param || 0).toString(16)).toUpperCase();
  1135. break;
  1136. case 'h':
  1137. subst = esc(param, html_esc);
  1138. break;
  1139. case 'q':
  1140. subst = esc(param, quot_esc);
  1141. break;
  1142. case 'j':
  1143. subst = String.serialize(param);
  1144. break;
  1145. case 't':
  1146. var td = 0;
  1147. var th = 0;
  1148. var tm = 0;
  1149. var ts = (param || 0);
  1150. if (ts > 60) {
  1151. tm = Math.floor(ts / 60);
  1152. ts = (ts % 60);
  1153. }
  1154. if (tm > 60) {
  1155. th = Math.floor(tm / 60);
  1156. tm = (tm % 60);
  1157. }
  1158. if (th > 24) {
  1159. td = Math.floor(th / 24);
  1160. th = (th % 24);
  1161. }
  1162. subst = (td > 0)
  1163. ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
  1164. : String.format('%dh %dm %ds', th, tm, ts);
  1165. break;
  1166. case 'm':
  1167. var mf = pMinLength ? +pMinLength : 1000;
  1168. var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
  1169. var i = 0;
  1170. var val = (+param || 0);
  1171. var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
  1172. for (i = 0; (i < units.length) && (val > mf); i++)
  1173. val /= mf;
  1174. subst = (i ? val.toFixed(pr) : val) + units[i];
  1175. pMinLength = null;
  1176. break;
  1177. }
  1178. }
  1179. }
  1180. if (pMinLength) {
  1181. subst = subst.toString();
  1182. for (var i = subst.length; i < pMinLength; i++)
  1183. if (pJustify == '-')
  1184. subst = subst + ' ';
  1185. else
  1186. subst = pad + subst;
  1187. }
  1188. out += leftpart + subst;
  1189. str = str.substr(m.length);
  1190. }
  1191. return out + str;
  1192. }
  1193. String.prototype.nobr = function()
  1194. {
  1195. return this.replace(/[\s\n]+/g, '&#160;');
  1196. }
  1197. String.serialize = function()
  1198. {
  1199. var a = [ ];
  1200. for (var i = 1; i < arguments.length; i++)
  1201. a.push(arguments[i]);
  1202. return ''.serialize.apply(arguments[0], a);
  1203. }
  1204. String.format = function()
  1205. {
  1206. var a = [ ];
  1207. for (var i = 1; i < arguments.length; i++)
  1208. a.push(arguments[i]);
  1209. return ''.format.apply(arguments[0], a);
  1210. }
  1211. String.nobr = function()
  1212. {
  1213. var a = [ ];
  1214. for (var i = 1; i < arguments.length; i++)
  1215. a.push(arguments[i]);
  1216. return ''.nobr.apply(arguments[0], a);
  1217. }