PageRenderTime 39ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/phpjs.js

https://github.com/Renatabk/SilkJS
JavaScript | 2038 lines | 1755 code | 43 blank | 240 comment | 73 complexity | 059127a9be1c7e3f69eb917327c1f9af MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /** @ignore */
  2. /**
  3. * @fileoverview
  4. *
  5. * <p>PHPJS - implementations of PHP core functions in JavaScript.</p>
  6. */
  7. function array_chunk (input, size, preserve_keys) {
  8. // http://kevin.vanzonneveld.net
  9. // + original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
  10. // + improved by: Brett Zamir (http://brett-zamir.me)
  11. // % note 1: Important note: Per the ECMAScript specification, objects may not always iterate in a predictable order
  12. // * example 1: array_chunk(['Kevin', 'van', 'Zonneveld'], 2);
  13. // * returns 1: [['Kevin', 'van'], ['Zonneveld']]
  14. // * example 2: array_chunk(['Kevin', 'van', 'Zonneveld'], 2, true);
  15. // * returns 2: [{0:'Kevin', 1:'van'}, {2: 'Zonneveld'}]
  16. // * example 3: array_chunk({1:'Kevin', 2:'van', 3:'Zonneveld'}, 2);
  17. // * returns 3: [['Kevin', 'van'], ['Zonneveld']]
  18. // * example 4: array_chunk({1:'Kevin', 2:'van', 3:'Zonneveld'}, 2, true);
  19. // * returns 4: [{1: 'Kevin', 2: 'van'}, {3: 'Zonneveld'}]
  20. var x, p = '', i = 0, c = -1, l = input.length || 0, n = [];
  21. if (size < 1) {
  22. return null;
  23. }
  24. if (Object.prototype.toString.call(input) === '[object Array]') {
  25. if (preserve_keys) {
  26. while (i < l) {
  27. (x = i % size) ? n[c][i] = input[i] : n[++c] = {}, n[c][i] = input[i];
  28. i++;
  29. }
  30. }
  31. else {
  32. while (i < l) {
  33. (x = i % size) ? n[c][x] = input[i] : n[++c] = [input[i]];
  34. i++;
  35. }
  36. }
  37. }
  38. else {
  39. if (preserve_keys) {
  40. for (p in input) {
  41. if (input.hasOwnProperty(p)) {
  42. (x = i % size) ? n[c][p] = input[p] : n[++c] = {}, n[c][p] = input[p];
  43. i++;
  44. }
  45. }
  46. }
  47. else {
  48. for (p in input) {
  49. if (input.hasOwnProperty(p)) {
  50. (x = i % size) ? n[c][x] = input[p] : n[++c] = [input[p]];
  51. i++;
  52. }
  53. }
  54. }
  55. }
  56. return n;
  57. }
  58. function array_intersect () {
  59. // Returns the entries of arr1 that have values which are present in all the other arguments
  60. //
  61. // version: 1006.1915
  62. // discuss at: http://phpjs.org/functions/array_intersect
  63. // + original by: Brett Zamir (http://brett-zamir.me)
  64. // % note 1: These only output associative arrays (would need to be
  65. // % note 1: all numeric and counting from zero to be numeric)
  66. // * example 1: $array1 = {'a' : 'green', 0:'red', 1: 'blue'};
  67. // * example 1: $array2 = {'b' : 'green', 0:'yellow', 1:'red'};
  68. // * example 1: $array3 = ['green', 'red'];
  69. // * example 1: $result = array_intersect($array1, $array2, $array3);
  70. // * returns 1: {0: 'red', a: 'green'}
  71. var arr1 = arguments[0], retArr = {};
  72. var k1 = '', arr = {}, i = 0, k = '';
  73. arr1keys:
  74. for (k1 in arr1) {
  75. arrs:
  76. for (i=1; i < arguments.length; i++) {
  77. arr = arguments[i];
  78. for (k in arr) {
  79. if (arr[k] === arr1[k1]) {
  80. if (i === arguments.length-1) {
  81. retArr[k1] = arr1[k1];
  82. }
  83. // If the innermost loop always leads at least once to an equal value, continue the loop until done
  84. continue arrs;
  85. }
  86. }
  87. // If it reaches here, it wasn't found in at least one array, so try next value
  88. continue arr1keys;
  89. }
  90. }
  91. return retArr;
  92. }
  93. function array_key_exists ( key, search ) {
  94. // Checks if the given key or index exists in the array
  95. //
  96. // version: 1004.2314
  97. // discuss at: http://phpjs.org/functions/array_key_exists
  98. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  99. // + improved by: Felix Geisendoerfer (http://www.debuggable.com/felix)
  100. // * example 1: array_key_exists('kevin', {'kevin': 'van Zonneveld'});
  101. // * returns 1: true
  102. // input sanitation
  103. if (!search || (search.constructor !== Array && search.constructor !== Object)){
  104. return false;
  105. }
  106. return key in search;
  107. }
  108. function array_keys (input, search_value, argStrict) {
  109. // http://kevin.vanzonneveld.net
  110. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  111. // + input by: Brett Zamir (http://brett-zamir.me)
  112. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  113. // * example 1: array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} );
  114. // * returns 1: {0: 'firstname', 1: 'surname'}
  115. var tmp_arr = {}, strict = !!argStrict, include = true, cnt = 0;
  116. var key = '';
  117. for (key in input) {
  118. include = true;
  119. if (search_value != undefined) {
  120. if (strict && input[key] !== search_value){
  121. include = false;
  122. } else if (input[key] != search_value){
  123. include = false;
  124. }
  125. }
  126. if (include) {
  127. tmp_arr[cnt] = key;
  128. cnt++;
  129. }
  130. }
  131. return tmp_arr;
  132. }
  133. function array_unique (inputArr) {
  134. // http://kevin.vanzonneveld.net
  135. // + original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
  136. // + input by: duncan
  137. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  138. // + bugfixed by: Nate
  139. // + input by: Brett Zamir (http://brett-zamir.me)
  140. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  141. // + improved by: Michael Grier
  142. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  143. // % note 1: The second argument, sort_flags is not implemented;
  144. // % note 1: also should be sorted (asort?) first according to docs
  145. // * example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']);
  146. // * returns 1: {0: 'Kevin', 2: 'van', 3: 'Zonneveld'}
  147. // * example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'});
  148. // * returns 2: {a: 'green', 0: 'red', 1: 'blue'}
  149. var key = '', tmp_arr2 = {}, val = '';
  150. var __array_search = function (needle, haystack) {
  151. var fkey = '';
  152. for (fkey in haystack) {
  153. if (haystack.hasOwnProperty(fkey)) {
  154. if ((haystack[fkey] + '') === (needle + '')) {
  155. return fkey;
  156. }
  157. }
  158. }
  159. return false;
  160. };
  161. for (key in inputArr) {
  162. if (inputArr.hasOwnProperty(key)) {
  163. val = inputArr[key];
  164. if (false === __array_search(val, tmp_arr2)) {
  165. tmp_arr2[key] = val;
  166. }
  167. }
  168. }
  169. return tmp_arr2;
  170. }
  171. function basename (path, suffix) {
  172. // Returns the filename component of the path
  173. //
  174. // version: 1004.2314
  175. // discuss at: http://phpjs.org/functions/basename
  176. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  177. // + improved by: Ash Searle (http://hexmen.com/blog/)
  178. // + improved by: Lincoln Ramsay
  179. // + improved by: djmix
  180. // * example 1: basename('/www/site/home.htm', '.htm');
  181. // * returns 1: 'home'
  182. // * example 2: basename('ecra.php?p=1');
  183. // * returns 2: 'ecra.php?p=1'
  184. var b = path.replace(/^.*[\/\\]/g, '');
  185. if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
  186. b = b.substr(0, b.length-suffix.length);
  187. }
  188. return b;
  189. }
  190. /**
  191. * count(o)
  192. *
  193. * Simulates PHP's count() function
  194. *
  195. * @param o {mixed} object, array, string, etc.
  196. * @returns {int} size
  197. *
  198. * size is number of members of an object, length of a string, length of an array, or 1 for others
  199. */
  200. function count(o) {
  201. if (Util.isArray(o) || Util.isString(o)) {
  202. return o.length;
  203. }
  204. else if (Util.isObject(o)) {
  205. var n = 0;
  206. forEach(o, function(oo, key) {
  207. if (o.hasOwnProperty(key)) {
  208. n++;
  209. }
  210. });
  211. return n;
  212. }
  213. else {
  214. return 1;
  215. }
  216. }
  217. function date (format, timestamp) {
  218. // http://kevin.vanzonneveld.net
  219. // + original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
  220. // + parts by: Peter-Paul Koch (http://www.quirksmode.org/js/beat.html)
  221. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  222. // + improved by: MeEtc (http://yass.meetcweb.com)
  223. // + improved by: Brad Touesnard
  224. // + improved by: Tim Wiel
  225. // + improved by: Bryan Elliott
  226. //
  227. // + improved by: Brett Zamir (http://brett-zamir.me)
  228. // + improved by: David Randall
  229. // + input by: Brett Zamir (http://brett-zamir.me)
  230. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  231. // + improved by: Brett Zamir (http://brett-zamir.me)
  232. // + improved by: Brett Zamir (http://brett-zamir.me)
  233. // + improved by: Theriault
  234. // + derived from: gettimeofday
  235. // + input by: majak
  236. // + bugfixed by: majak
  237. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  238. // + input by: Alex
  239. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  240. // + improved by: Theriault
  241. // + improved by: Brett Zamir (http://brett-zamir.me)
  242. // + improved by: Theriault
  243. // + improved by: Thomas Beaucourt (http://www.webapp.fr)
  244. // + improved by: JT
  245. // + improved by: Theriault
  246. // + improved by: Rafał Kukawski (http://blog.kukawski.pl)
  247. // + bugfixed by: omid (http://phpjs.org/functions/380:380#comment_137122)
  248. // + input by: Martin
  249. // + input by: Alex Wilson
  250. // % note 1: Uses global: php_js to store the default timezone
  251. // % note 2: Although the function potentially allows timezone info (see notes), it currently does not set
  252. // % note 2: per a timezone specified by date_default_timezone_set(). Implementers might use
  253. // % note 2: this.php_js.currentTimezoneOffset and this.php_js.currentTimezoneDST set by that function
  254. // % note 2: in order to adjust the dates in this function (or our other date functions!) accordingly
  255. // * example 1: date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400);
  256. // * returns 1: '09:09:40 m is month'
  257. // * example 2: date('F j, Y, g:i a', 1062462400);
  258. // * returns 2: 'September 2, 2003, 2:26 am'
  259. // * example 3: date('Y W o', 1062462400);
  260. // * returns 3: '2003 36 2003'
  261. // * example 4: x = date('Y m d', (new Date()).getTime()/1000);
  262. // * example 4: (x+'').length == 10 // 2009 01 09
  263. // * returns 4: true
  264. // * example 5: date('W', 1104534000);
  265. // * returns 5: '53'
  266. // * example 6: date('B t', 1104534000);
  267. // * returns 6: '999 31'
  268. // * example 7: date('W U', 1293750000.82); // 2010-12-31
  269. // * returns 7: '52 1293750000'
  270. // * example 8: date('W', 1293836400); // 2011-01-01
  271. // * returns 8: '52'
  272. // * example 9: date('W Y-m-d', 1293974054); // 2011-01-02
  273. // * returns 9: '52 2011-01-02'
  274. var that = this,
  275. jsdate, f, formatChr = /\\?([a-z])/gi,
  276. formatChrCb,
  277. // Keep this here (works, but for code commented-out
  278. // below for file size reasons)
  279. //, tal= [],
  280. _pad = function (n, c) {
  281. if ((n = n + '').length < c) {
  282. return new Array((++c) - n.length).join('0') + n;
  283. }
  284. return n;
  285. },
  286. txt_words = ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  287. formatChrCb = function (t, s) {
  288. return f[t] ? f[t]() : s;
  289. };
  290. f = {
  291. // Day
  292. d: function () { // Day of month w/leading 0; 01..31
  293. return _pad(f.j(), 2);
  294. },
  295. D: function () { // Shorthand day name; Mon...Sun
  296. return f.l().slice(0, 3);
  297. },
  298. j: function () { // Day of month; 1..31
  299. return jsdate.getDate();
  300. },
  301. l: function () { // Full day name; Monday...Sunday
  302. return txt_words[f.w()] + 'day';
  303. },
  304. N: function () { // ISO-8601 day of week; 1[Mon]..7[Sun]
  305. return f.w() || 7;
  306. },
  307. S: function () { // Ordinal suffix for day of month; st, nd, rd, th
  308. var j = f.j();
  309. return j < 4 | j > 20 && ['st', 'nd', 'rd'][j%10 - 1] || 'th';
  310. },
  311. w: function () { // Day of week; 0[Sun]..6[Sat]
  312. return jsdate.getDay();
  313. },
  314. z: function () { // Day of year; 0..365
  315. var a = new Date(f.Y(), f.n() - 1, f.j()),
  316. b = new Date(f.Y(), 0, 1);
  317. return Math.round((a - b) / 864e5) + 1;
  318. },
  319. // Week
  320. W: function () { // ISO-8601 week number
  321. var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3),
  322. b = new Date(a.getFullYear(), 0, 4);
  323. return _pad(1 + Math.round((a - b) / 864e5 / 7), 2);
  324. },
  325. // Month
  326. F: function () { // Full month name; January...December
  327. return txt_words[6 + f.n()];
  328. },
  329. m: function () { // Month w/leading 0; 01...12
  330. return _pad(f.n(), 2);
  331. },
  332. M: function () { // Shorthand month name; Jan...Dec
  333. return f.F().slice(0, 3);
  334. },
  335. n: function () { // Month; 1...12
  336. return jsdate.getMonth() + 1;
  337. },
  338. t: function () { // Days in month; 28...31
  339. return (new Date(f.Y(), f.n(), 0)).getDate();
  340. },
  341. // Year
  342. L: function () { // Is leap year?; 0 or 1
  343. var j = f.Y();
  344. return j%4==0 & j%100!=0 | j%400==0;
  345. },
  346. o: function () { // ISO-8601 year
  347. var n = f.n(),
  348. W = f.W(),
  349. Y = f.Y();
  350. return Y + (n === 12 && W < 9 ? -1 : n === 1 && W > 9);
  351. },
  352. Y: function () { // Full year; e.g. 1980...2010
  353. return jsdate.getFullYear();
  354. },
  355. y: function () { // Last two digits of year; 00...99
  356. return (f.Y() + "").slice(-2);
  357. },
  358. // Time
  359. a: function () { // am or pm
  360. return jsdate.getHours() > 11 ? "pm" : "am";
  361. },
  362. A: function () { // AM or PM
  363. return f.a().toUpperCase();
  364. },
  365. B: function () { // Swatch Internet time; 000..999
  366. var H = jsdate.getUTCHours() * 36e2,
  367. // Hours
  368. i = jsdate.getUTCMinutes() * 60,
  369. // Minutes
  370. s = jsdate.getUTCSeconds(); // Seconds
  371. return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3);
  372. },
  373. g: function () { // 12-Hours; 1..12
  374. return f.G() % 12 || 12;
  375. },
  376. G: function () { // 24-Hours; 0..23
  377. return jsdate.getHours();
  378. },
  379. h: function () { // 12-Hours w/leading 0; 01..12
  380. return _pad(f.g(), 2);
  381. },
  382. H: function () { // 24-Hours w/leading 0; 00..23
  383. return _pad(f.G(), 2);
  384. },
  385. i: function () { // Minutes w/leading 0; 00..59
  386. return _pad(jsdate.getMinutes(), 2);
  387. },
  388. s: function () { // Seconds w/leading 0; 00..59
  389. return _pad(jsdate.getSeconds(), 2);
  390. },
  391. u: function () { // Microseconds; 000000-999000
  392. return _pad(jsdate.getMilliseconds() * 1000, 6);
  393. },
  394. // Timezone
  395. e: function () { // Timezone identifier; e.g. Atlantic/Azores, ...
  396. // The following works, but requires inclusion of the very large
  397. // timezone_abbreviations_list() function.
  398. /* return this.date_default_timezone_get();
  399. */
  400. throw 'Not supported (see source code of date() for timezone on how to add support)';
  401. },
  402. I: function () { // DST observed?; 0 or 1
  403. // Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC.
  404. // If they are not equal, then DST is observed.
  405. var a = new Date(f.Y(), 0),
  406. // Jan 1
  407. c = Date.UTC(f.Y(), 0),
  408. // Jan 1 UTC
  409. b = new Date(f.Y(), 6),
  410. // Jul 1
  411. d = Date.UTC(f.Y(), 6); // Jul 1 UTC
  412. return 0 + ((a - c) !== (b - d));
  413. },
  414. O: function () { // Difference to GMT in hour format; e.g. +0200
  415. var tzo = jsdate.getTimezoneOffset(),
  416. a = Math.abs(tzo);
  417. return (tzo > 0 ? "-" : "+") + _pad(Math.floor(a / 60) * 100 + a % 60, 4);
  418. },
  419. P: function () { // Difference to GMT w/colon; e.g. +02:00
  420. var O = f.O();
  421. return (O.substr(0, 3) + ":" + O.substr(3, 2));
  422. },
  423. T: function () { // Timezone abbreviation; e.g. EST, MDT, ...
  424. // The following works, but requires inclusion of the very
  425. // large timezone_abbreviations_list() function.
  426. /* var abbr = '', i = 0, os = 0, default = 0;
  427. if (!tal.length) {
  428. tal = that.timezone_abbreviations_list();
  429. }
  430. if (that.php_js && that.php_js.default_timezone) {
  431. default = that.php_js.default_timezone;
  432. for (abbr in tal) {
  433. for (i=0; i < tal[abbr].length; i++) {
  434. if (tal[abbr][i].timezone_id === default) {
  435. return abbr.toUpperCase();
  436. }
  437. }
  438. }
  439. }
  440. for (abbr in tal) {
  441. for (i = 0; i < tal[abbr].length; i++) {
  442. os = -jsdate.getTimezoneOffset() * 60;
  443. if (tal[abbr][i].offset === os) {
  444. return abbr.toUpperCase();
  445. }
  446. }
  447. }
  448. */
  449. return 'UTC';
  450. },
  451. Z: function () { // Timezone offset in seconds (-43200...50400)
  452. return -jsdate.getTimezoneOffset() * 60;
  453. },
  454. // Full Date/Time
  455. c: function () { // ISO-8601 date.
  456. return 'Y-m-d\\TH:i:sP'.replace(formatChr, formatChrCb);
  457. },
  458. r: function () { // RFC 2822
  459. return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb);
  460. },
  461. U: function () { // Seconds since UNIX epoch
  462. return jsdate / 1000 | 0;
  463. }
  464. };
  465. this.date = function (format, timestamp) {
  466. that = this;
  467. jsdate = (timestamp == null ? new Date() : // Not provided
  468. (timestamp instanceof Date) ? new Date(timestamp) : // JS Date()
  469. new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
  470. );
  471. return format.replace(formatChr, formatChrCb);
  472. };
  473. return this.date(format, timestamp);
  474. }
  475. function dirname (path) {
  476. // Returns the directory name component of the path
  477. //
  478. // version: 1004.2314
  479. // discuss at: http://phpjs.org/functions/dirname
  480. // + original by: Ozh
  481. // + improved by: XoraX (http://www.xorax.info)
  482. // * example 1: dirname('/etc/passwd');
  483. // * returns 1: '/etc'
  484. // * example 2: dirname('c:/Temp/x');
  485. // * returns 2: 'c:/Temp'
  486. // * example 3: dirname('/dir/test/');
  487. // * returns 3: '/dir'
  488. return path.replace(/\\/g,'/').replace(/\/[^\/]*\/?$/, '');
  489. }
  490. function echo() {
  491. var arg = '', argc = arguments.length, argv = arguments, i = 0;
  492. for (i=0; i<argc; i++) {
  493. arg = argv[i];
  494. res.write(arg);
  495. }
  496. }
  497. function empty (mixed_var) {
  498. // !No description available for empty. @php.js developers: Please update the function summary text file.
  499. //
  500. // version: 1004.2314
  501. // discuss at: http://phpjs.org/functions/empty
  502. // + original by: Philippe Baumann
  503. // + input by: Onno Marsman
  504. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  505. // + input by: LH
  506. // + improved by: Onno Marsman
  507. // + improved by: Francesco
  508. // + improved by: Marc Jansen
  509. // + input by: Stoyan Kyosev (http://www.svest.org/)
  510. // * example 1: empty(null);
  511. // * returns 1: true
  512. // * example 2: empty(undefined);
  513. // * returns 2: true
  514. // * example 3: empty([]);
  515. // * returns 3: true
  516. // * example 4: empty({});
  517. // * returns 4: true
  518. // * example 5: empty({'aFunc' : function () { alert('humpty'); } });
  519. // * returns 5: false
  520. var key;
  521. if (mixed_var === "" ||
  522. mixed_var === 0 ||
  523. mixed_var === "0" ||
  524. mixed_var === null ||
  525. mixed_var === false ||
  526. typeof mixed_var === 'undefined'
  527. ){
  528. return true;
  529. }
  530. if (typeof mixed_var == 'object') {
  531. for (key in mixed_var) {
  532. if (mixed_var.hasOwnProperty(key)) {
  533. return false;
  534. }
  535. }
  536. return true;
  537. }
  538. return false;
  539. }
  540. function file_exists(path) {
  541. var fs = require('fs');
  542. return fs.exists(path);
  543. }
  544. function htmlspecialchars (string, quote_style, charset, double_encode) {
  545. // http://kevin.vanzonneveld.net
  546. // + original by: Mirek Slugen
  547. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  548. // + bugfixed by: Nathan
  549. // + bugfixed by: Arno
  550. // + revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  551. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  552. // + input by: Ratheous
  553. // + input by: Mailfaker (http://www.weedem.fr/)
  554. // + reimplemented by: Brett Zamir (http://brett-zamir.me)
  555. // + input by: felix
  556. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  557. // % note 1: charset argument not supported
  558. // * example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
  559. // * returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
  560. // * example 2: htmlspecialchars("ab\"c'd", ['ENT_NOQUOTES', 'ENT_QUOTES']);
  561. // * returns 2: 'ab"c&#039;d'
  562. // * example 3: htmlspecialchars("my "&entity;" is still here", null, null, false);
  563. // * returns 3: 'my &quot;&entity;&quot; is still here'
  564. var optTemp = 0,
  565. i = 0,
  566. noquotes = false;
  567. if (typeof quote_style === 'undefined' || quote_style === null) {
  568. quote_style = 2;
  569. }
  570. string = string.toString();
  571. if (double_encode !== false) { // Put this first to avoid double-encoding
  572. string = string.replace(/&/g, '&amp;');
  573. }
  574. string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  575. var OPTS = {
  576. 'ENT_NOQUOTES': 0,
  577. 'ENT_HTML_QUOTE_SINGLE': 1,
  578. 'ENT_HTML_QUOTE_DOUBLE': 2,
  579. 'ENT_COMPAT': 2,
  580. 'ENT_QUOTES': 3,
  581. 'ENT_IGNORE': 4
  582. };
  583. if (quote_style === 0) {
  584. noquotes = true;
  585. }
  586. if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
  587. quote_style = [].concat(quote_style);
  588. for (i = 0; i < quote_style.length; i++) {
  589. // Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4
  590. if (OPTS[quote_style[i]] === 0) {
  591. noquotes = true;
  592. }
  593. else if (OPTS[quote_style[i]]) {
  594. optTemp = optTemp | OPTS[quote_style[i]];
  595. }
  596. }
  597. quote_style = optTemp;
  598. }
  599. if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
  600. string = string.replace(/'/g, '&#039;');
  601. }
  602. if (!noquotes) {
  603. string = string.replace(/"/g, '&quot;');
  604. }
  605. return string;
  606. }
  607. function is_null (mixed_var) {
  608. // Returns true if variable is null
  609. //
  610. // version: 1004.2314
  611. // discuss at: http://phpjs.org/functions/is_null
  612. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  613. // * example 1: is_null('23');
  614. // * returns 1: false
  615. // * example 2: is_null(null);
  616. // * returns 2: true
  617. return ( mixed_var === null );
  618. }
  619. function is_numeric (mixed_var) {
  620. // Returns true if value is a number or a numeric string
  621. //
  622. // version: 1004.2314
  623. // discuss at: http://phpjs.org/functions/is_numeric
  624. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  625. // + improved by: David
  626. // + improved by: taith
  627. // + bugfixed by: Tim de Koning
  628. // + bugfixed by: WebDevHobo (http://webdevhobo.blogspot.com/)
  629. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  630. // * example 1: is_numeric(186.31);
  631. // * returns 1: true
  632. // * example 2: is_numeric('Kevin van Zonneveld');
  633. // * returns 2: false
  634. // * example 3: is_numeric('+186.31e2');
  635. // * returns 3: true
  636. // * example 4: is_numeric('');
  637. // * returns 4: false
  638. // * example 4: is_numeric([]);
  639. // * returns 4: false
  640. return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
  641. }
  642. function isset () {
  643. // !No description available for isset. @php.js developers: Please update the function summary text file.
  644. //
  645. // version: 1004.2314
  646. // discuss at: http://phpjs.org/functions/isset
  647. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  648. // + improved by: FremyCompany
  649. // + improved by: Onno Marsman
  650. // * example 1: isset( undefined, true);
  651. // * returns 1: false
  652. // * example 2: isset( 'Kevin van Zonneveld' );
  653. // * returns 2: true
  654. var a=arguments, l=a.length, i=0;
  655. if (l===0) {
  656. error('Empty isset');
  657. }
  658. while (i!==l) {
  659. if (typeof(a[i])=='undefined' || a[i]===null) {
  660. return false;
  661. } else {
  662. i++;
  663. }
  664. }
  665. return true;
  666. }
  667. function lcfirst (str) {
  668. // http://kevin.vanzonneveld.net
  669. // + original by: Brett Zamir (http://brett-zamir.me)
  670. // * example 1: lcfirst('Kevin Van Zonneveld');
  671. // * returns 1: 'kevin Van Zonneveld'
  672. str += '';
  673. var f = str.charAt(0).toLowerCase();
  674. return f + str.substr(1);
  675. }
  676. function ltrim ( str, charlist ) {
  677. // http://kevin.vanzonneveld.net
  678. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  679. // + input by: Erkekjetter
  680. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  681. // + bugfixed by: Onno Marsman
  682. // * example 1: ltrim(' Kevin van Zonneveld ');
  683. // * returns 1: 'Kevin van Zonneveld '
  684. charlist = !charlist ? ' \\s\u00A0' : (charlist+'').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
  685. var re = new RegExp('^[' + charlist + ']+', 'g');
  686. return (str+'').replace(re, '');
  687. }
  688. function microtime (get_as_float) {
  689. // http://kevin.vanzonneveld.net
  690. // + original by: Paulo Freitas
  691. // * example 1: timeStamp = microtime(true);
  692. // * results 1: timeStamp > 1000000000 && timeStamp < 2000000000
  693. var now = new Date().getTime() / 1000;
  694. var s = parseInt(now, 10);
  695. return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
  696. }
  697. function number_format(number, decimals, dec_point, thousands_sep) {
  698. // http://kevin.vanzonneveld.net
  699. // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  700. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  701. // + bugfix by: Michael White (http://getsprink.com)
  702. // + bugfix by: Benjamin Lupton
  703. // + bugfix by: Allan Jensen (http://www.winternet.no)
  704. // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  705. // + bugfix by: Howard Yeend
  706. // + revised by: Luke Smith (http://lucassmith.name)
  707. // + bugfix by: Diogo Resende
  708. // + bugfix by: Rival
  709. // + input by: Kheang Hok Chin (http://www.distantia.ca/)
  710. // + improved by: davook
  711. // + improved by: Brett Zamir (http://brett-zamir.me)
  712. // + input by: Jay Klehr
  713. // + improved by: Brett Zamir (http://brett-zamir.me)
  714. // + input by: Amir Habibi (http://www.residence-mixte.com/)
  715. // + bugfix by: Brett Zamir (http://brett-zamir.me)
  716. // + improved by: Theriault
  717. // * example 1: number_format(1234.56);
  718. // * returns 1: '1,235'
  719. // * example 2: number_format(1234.56, 2, ',', ' ');
  720. // * returns 2: '1 234,56'
  721. // * example 3: number_format(1234.5678, 2, '.', '');
  722. // * returns 3: '1234.57'
  723. // * example 4: number_format(67, 2, ',', '.');
  724. // * returns 4: '67,00'
  725. // * example 5: number_format(1000);
  726. // * returns 5: '1,000'
  727. // * example 6: number_format(67.311, 2);
  728. // * returns 6: '67.31'
  729. // * example 7: number_format(1000.55, 1);
  730. // * returns 7: '1,000.6'
  731. // * example 8: number_format(67000, 5, ',', '.');
  732. // * returns 8: '67.000,00000'
  733. // * example 9: number_format(0.9, 0);
  734. // * returns 9: '1'
  735. // * example 10: number_format('1.20', 2);
  736. // * returns 10: '1.20'
  737. // * example 11: number_format('1.20', 4);
  738. // * returns 11: '1.2000'
  739. // * example 12: number_format('1.2000', 3);
  740. // * returns 12: '1.200'
  741. var n = !isFinite(+number) ? 0 : +number,
  742. prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
  743. sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
  744. dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
  745. s = '',
  746. toFixedFix = function (n, prec) {
  747. var k = Math.pow(10, prec);
  748. return '' + Math.round(n * k) / k;
  749. };
  750. // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  751. s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  752. if (s[0].length > 3) {
  753. s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
  754. }
  755. if ((s[1] || '').length < prec) {
  756. s[1] = s[1] || '';
  757. s[1] += new Array(prec - s[1].length + 1).join('0');
  758. }
  759. return s.join(dec);
  760. }
  761. function parse_str (str, array) {
  762. // http://kevin.vanzonneveld.net
  763. // + original by: Cagri Ekin
  764. // + improved by: Michael White (http://getsprink.com)
  765. // + tweaked by: Jack
  766. // + bugfixed by: Onno Marsman
  767. // + reimplemented by: stag019
  768. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  769. // + bugfixed by: stag019
  770. // - depends on: urldecode
  771. // + input by: Dreamer
  772. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  773. // % note 1: When no argument is specified, will put variables in global scope.
  774. // + bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
  775. // % note 1: When a particular argument has been passed, and the returned value is different parse_str of PHP. For example, a=b=c&d====c
  776. // * example 1: var arr = {};
  777. // * example 1: parse_str('first=foo&second=bar', arr);
  778. // * results 1: arr == { first: 'foo', second: 'bar' }
  779. // * example 2: var arr = {};
  780. // * example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr);
  781. // * results 2: arr == { str_a: "Jack and Jill didn't see the well." }
  782. var glue1 = '=',
  783. glue2 = '&',
  784. array2 = String(str).replace(/^&?([\s\S]*?)&?$/, '$1').split(glue2),
  785. i, j, chr, tmp, key, value, bracket, keys, evalStr, that = this,
  786. fixStr = function (str) {
  787. return that.urldecode(str).replace(/([\\"'])/g, '\\$1').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
  788. };
  789. if (!array) {
  790. array = this.window;
  791. }
  792. for (i = 0; i < array2.length; i++) {
  793. tmp = array2[i].split(glue1);
  794. if (tmp.length < 2) {
  795. tmp = [tmp, ''];
  796. }
  797. key = fixStr(tmp.shift());
  798. value = fixStr(tmp.join(glue1));
  799. while (key.charAt(0) === ' ') {
  800. key = key.substr(1);
  801. }
  802. if (key.indexOf('\0') !== -1) {
  803. key = key.substr(0, key.indexOf('\0'));
  804. }
  805. if (key && key.charAt(0) !== '[') {
  806. keys = [];
  807. bracket = 0;
  808. for (j = 0; j < key.length; j++) {
  809. if (key.charAt(j) === '[' && !bracket) {
  810. bracket = j + 1;
  811. } else if (key.charAt(j) === ']') {
  812. if (bracket) {
  813. if (!keys.length) {
  814. keys.push(key.substr(0, bracket - 1));
  815. }
  816. keys.push(key.substr(bracket, j - bracket));
  817. bracket = 0;
  818. if (key.charAt(j + 1) !== '[') {
  819. break;
  820. }
  821. }
  822. }
  823. }
  824. if (!keys.length) {
  825. keys = [key];
  826. }
  827. for (j = 0; j < keys[0].length; j++) {
  828. chr = keys[0].charAt(j);
  829. if (chr === ' ' || chr === '.' || chr === '[') {
  830. keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
  831. }
  832. if (chr === '[') {
  833. break;
  834. }
  835. }
  836. evalStr = 'array';
  837. for (j = 0; j < keys.length; j++) {
  838. key = keys[j];
  839. if ((key !== '' && key !== ' ') || j === 0) {
  840. key = "'" + key + "'";
  841. } else {
  842. key = eval(evalStr + '.push([]);') - 1;
  843. }
  844. evalStr += '[' + key + ']';
  845. if (j !== keys.length - 1 && eval('typeof ' + evalStr) === 'undefined') {
  846. eval(evalStr + ' = [];');
  847. }
  848. }
  849. evalStr += " = '" + value + "';\n";
  850. eval(evalStr);
  851. }
  852. }
  853. }
  854. function pathinfo (path, options) {
  855. // http://kevin.vanzonneveld.net
  856. // + original by: Nate
  857. // + revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  858. // + improved by: Brett Zamir (http://brett-zamir.me)
  859. // % note 1: Inspired by actual PHP source: php5-5.2.6/ext/standard/string.c line #1559
  860. // % note 1: The way the bitwise arguments are handled allows for greater flexibility
  861. // % note 1: & compatability. We might even standardize this code and use a similar approach for
  862. // % note 1: other bitwise PHP functions
  863. // % note 2: php.js tries very hard to stay away from a core.js file with global dependencies, because we like
  864. // % note 2: that you can just take a couple of functions and be on your way.
  865. // % note 2: But by way we implemented this function, if you want you can still declare the PATHINFO_*
  866. // % note 2: yourself, and then you can use: pathinfo('/www/index.html', PATHINFO_BASENAME | PATHINFO_EXTENSION);
  867. // % note 2: which makes it fully compliant with PHP syntax.
  868. // - depends on: dirname
  869. // - depends on: basename
  870. // * example 1: pathinfo('/www/htdocs/index.html', 1);
  871. // * returns 1: '/www/htdocs'
  872. // * example 2: pathinfo('/www/htdocs/index.html', 'PATHINFO_BASENAME');
  873. // * returns 2: 'index.html'
  874. // * example 3: pathinfo('/www/htdocs/index.html', 'PATHINFO_EXTENSION');
  875. // * returns 3: 'html'
  876. // * example 4: pathinfo('/www/htdocs/index.html', 'PATHINFO_FILENAME');
  877. // * returns 4: 'index'
  878. // * example 5: pathinfo('/www/htdocs/index.html', 2 | 4);
  879. // * returns 5: {basename: 'index.html', extension: 'html'}
  880. // * example 6: pathinfo('/www/htdocs/index.html', 'PATHINFO_ALL');
  881. // * returns 6: {dirname: '/www/htdocs', basename: 'index.html', extension: 'html', filename: 'index'}
  882. // * example 7: pathinfo('/www/htdocs/index.html');
  883. // * returns 7: {dirname: '/www/htdocs', basename: 'index.html', extension: 'html', filename: 'index'}
  884. // Working vars
  885. var opt = '', optName = '', optTemp = 0, tmp_arr = {}, cnt = 0, i=0;
  886. var have_basename = false, have_extension = false, have_filename = false;
  887. // Input defaulting & sanitation
  888. if (!path) {
  889. return false;
  890. }
  891. if (!options) {
  892. options = 'PATHINFO_ALL';
  893. }
  894. // Initialize binary arguments. Both the string & integer (constant) input is
  895. // allowed
  896. var OPTS = {
  897. 'PATHINFO_DIRNAME': 1,
  898. 'PATHINFO_BASENAME': 2,
  899. 'PATHINFO_EXTENSION': 4,
  900. 'PATHINFO_FILENAME': 8,
  901. 'PATHINFO_ALL': 0
  902. };
  903. // PATHINFO_ALL sums up all previously defined PATHINFOs (could just pre-calculate)
  904. for (optName in OPTS) {
  905. OPTS.PATHINFO_ALL = OPTS.PATHINFO_ALL | OPTS[optName];
  906. }
  907. if (typeof options !== 'number') { // Allow for a single string or an array of string flags
  908. options = [].concat(options);
  909. for (i=0; i < options.length; i++) {
  910. // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
  911. if (OPTS[options[i]]) {
  912. optTemp = optTemp | OPTS[options[i]];
  913. }
  914. }
  915. options = optTemp;
  916. }
  917. // Internal Functions
  918. var __getExt = function (path) {
  919. var str = path+'';
  920. var dotP = str.lastIndexOf('.')+1;
  921. return str.substr(dotP);
  922. };
  923. // Gather path infos
  924. if (options & OPTS.PATHINFO_DIRNAME) {
  925. tmp_arr.dirname = this.dirname(path);
  926. }
  927. if (options & OPTS.PATHINFO_BASENAME) {
  928. if (false === have_basename) {
  929. have_basename = this.basename(path);
  930. }
  931. tmp_arr.basename = have_basename;
  932. }
  933. if (options & OPTS.PATHINFO_EXTENSION) {
  934. if (false === have_basename) {
  935. have_basename = this.basename(path);
  936. }
  937. if (false === have_extension) {
  938. have_extension = __getExt(have_basename);
  939. }
  940. tmp_arr.extension = have_extension;
  941. }
  942. if (options & OPTS.PATHINFO_FILENAME) {
  943. if (false === have_basename) {
  944. have_basename = this.basename(path);
  945. }
  946. if (false === have_extension) {
  947. have_extension = __getExt(have_basename);
  948. }
  949. if (false === have_filename) {
  950. have_filename = have_basename.substr(0, (have_basename.length - have_extension.length)-1);
  951. }
  952. tmp_arr.filename = have_filename;
  953. }
  954. // If array contains only 1 element: return string
  955. cnt = 0;
  956. for (opt in tmp_arr){
  957. cnt++;
  958. }
  959. if (cnt == 1) {
  960. return tmp_arr[opt];
  961. }
  962. // Return full-blown array
  963. return tmp_arr;
  964. }
  965. function rtrim ( str, charlist ) {
  966. // http://kevin.vanzonneveld.net
  967. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  968. // + input by: Erkekjetter
  969. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  970. // + bugfixed by: Onno Marsman
  971. // + input by: rem
  972. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  973. // * example 1: rtrim(' Kevin van Zonneveld ');
  974. // * returns 1: ' Kevin van Zonneveld'
  975. charlist = !charlist ? ' \\s\u00A0' : (charlist+'').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\\$1');
  976. var re = new RegExp('[' + charlist + ']+$', 'g');
  977. return (str+'').replace(re, '');
  978. }
  979. function serialize (mixed_value) {
  980. // http://kevin.vanzonneveld.net
  981. // + original by: Arpad Ray (mailto:arpad@php.net)
  982. // + improved by: Dino
  983. // + bugfixed by: Andrej Pavlovic
  984. // + bugfixed by: Garagoth
  985. // + input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
  986. // + bugfixed by: Russell Walker (http://www.nbill.co.uk/)
  987. // + bugfixed by: Jamie Beck (http://www.terabit.ca/)
  988. // + input by: Martin (http://www.erlenwiese.de/)
  989. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  990. // - depends on: utf8_encode
  991. // % note: We feel the main purpose of this function should be to ease the transport of data between php & js
  992. // % note: Aiming for PHP-compatibility, we have to translate objects to arrays
  993. // * example 1: serialize(['Kevin', 'van', 'Zonneveld']);
  994. // * returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
  995. // * example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
  996. // * returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
  997. var _getType = function (inp) {
  998. var type = typeof inp, match;
  999. var key;
  1000. if (type == 'object' && !inp) {
  1001. return 'null';
  1002. }
  1003. if (type == "object") {
  1004. if (!inp.constructor) {
  1005. return 'object';
  1006. }
  1007. var cons = inp.constructor.toString();
  1008. match = cons.match(/(\w+)\(/);
  1009. if (match) {
  1010. cons = match[1].toLowerCase();
  1011. }
  1012. var types = ["boolean", "number", "string", "array"];
  1013. for (key in types) {
  1014. if (cons == types[key]) {
  1015. type = types[key];
  1016. break;
  1017. }
  1018. }
  1019. }
  1020. return type;
  1021. };
  1022. var type = _getType(mixed_value);
  1023. var val, ktype = '';
  1024. switch (type) {
  1025. case "function":
  1026. val = "";
  1027. break;
  1028. case "boolean":
  1029. val = "b:" + (mixed_value ? "1" : "0");
  1030. break;
  1031. case "number":
  1032. val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
  1033. break;
  1034. case "string":
  1035. mixed_value = this.utf8_encode(mixed_value);
  1036. val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
  1037. break;
  1038. case "array":
  1039. case "object":
  1040. val = "a";
  1041. /*
  1042. if (type == "object") {
  1043. var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
  1044. if (objname == undefined) {
  1045. return;
  1046. }
  1047. objname[1] = this.serialize(objname[1]);
  1048. val = "O" + objname[1].substring(1, objname[1].length - 1);
  1049. }
  1050. */
  1051. var count = 0;
  1052. var vals = "";
  1053. var okey;
  1054. var key;
  1055. for (key in mixed_value) {
  1056. ktype = _getType(mixed_value[key]);
  1057. if (ktype == "function") {
  1058. continue;
  1059. }
  1060. okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
  1061. vals += this.serialize(okey) +
  1062. this.serialize(mixed_value[key]);
  1063. count++;
  1064. }
  1065. val += ":" + count + ":{" + vals + "}";
  1066. break;
  1067. case "undefined": // Fall-through
  1068. default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
  1069. val = "N";
  1070. break;
  1071. }
  1072. if (type != "object" && type != "array") {
  1073. val += ";";
  1074. }
  1075. return val;
  1076. }
  1077. function sprintf ( ) {
  1078. // Return a formatted string
  1079. //
  1080. // version: 1004.2314
  1081. // discuss at: http://phpjs.org/functions/sprintf
  1082. // + original by: Ash Searle (http://hexmen.com/blog/)
  1083. // + namespaced by: Michael White (http://getsprink.com)
  1084. // + tweaked by: Jack
  1085. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  1086. // + input by: Paulo Ricardo F. Santos
  1087. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  1088. // + input by: Brett Zamir (http://brett-zamir.me)
  1089. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  1090. // * example 1: sprintf("%01.2f", 123.1);
  1091. // * returns 1: 123.10
  1092. // * example 2: sprintf("[%10s]", 'monkey');
  1093. // * returns 2: '[ monkey]'
  1094. // * example 3: sprintf("[%'#10s]", 'monkey');
  1095. // * returns 3: '[####monkey]'
  1096. var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
  1097. var a = arguments, i = 0, format = a[i++];
  1098. // pad()
  1099. var pad = function (str, len, chr, leftJustify) {
  1100. if (!chr) {
  1101. chr = ' ';
  1102. }
  1103. var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
  1104. return leftJustify ? str + padding : padding + str;
  1105. };
  1106. // justify()
  1107. var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  1108. var diff = minWidth - value.length;
  1109. if (diff > 0) {
  1110. if (leftJustify || !zeroPad) {
  1111. value = pad(value, minWidth, customPadChar, leftJustify);
  1112. } else {
  1113. value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  1114. }
  1115. }
  1116. return value;
  1117. };
  1118. // formatBaseX()
  1119. var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  1120. // Note: casts negative numbers to positive ones
  1121. var number = value >>> 0;
  1122. prefix = prefix && number && {
  1123. '2': '0b',
  1124. '8': '0',
  1125. '16': '0x'
  1126. }
  1127. [base] || '';
  1128. value = prefix + pad(number.toString(base), precision || 0, '0', false);
  1129. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  1130. };
  1131. // formatString()
  1132. var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  1133. if (precision != null) {
  1134. value = value.slice(0, precision);
  1135. }
  1136. return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  1137. };
  1138. // doFormat()
  1139. var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
  1140. var number;
  1141. var prefix;
  1142. var method;
  1143. var textTransform;
  1144. var value;
  1145. if (substring == '%%') {
  1146. return '%';
  1147. }
  1148. // parse flags
  1149. var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
  1150. var flagsl = flags.length;
  1151. for (var j = 0; flags && j < flagsl; j++) {
  1152. switch (flags.charAt(j)) {
  1153. case ' ':
  1154. positivePrefix = ' ';
  1155. break;
  1156. case '+':
  1157. positivePrefix = '+';
  1158. break;
  1159. case '-':
  1160. leftJustify = true;
  1161. break;
  1162. case "'":
  1163. customPadChar = flags.charAt(j+1);
  1164. break;
  1165. case '0':
  1166. zeroPad = true;
  1167. break;
  1168. case '#':
  1169. prefixBaseX = true;
  1170. break;
  1171. }
  1172. }
  1173. // parameters may be null, undefined, empty-string or real valued
  1174. // we want to ignore null, undefined and empty-string values
  1175. if (!minWidth) {
  1176. minWidth = 0;
  1177. } else if (minWidth == '*') {
  1178. minWidth = +a[i++];
  1179. } else if (minWidth.charAt(0) == '*') {
  1180. minWidth = +a[minWidth.slice(1, -1)];
  1181. } else {
  1182. minWidth = +minWidth;
  1183. }
  1184. // Note: undocumented perl feature:
  1185. if (minWidth < 0) {
  1186. minWidth = -minWidth;
  1187. leftJustify = true;
  1188. }
  1189. if (!isFinite(minWidth)) {
  1190. error('sprintf: (minimum-)width must be finite');
  1191. }
  1192. if (!precision) {
  1193. precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
  1194. } else if (precision == '*') {
  1195. precision = +a[i++];
  1196. } else if (precision.charAt(0) == '*') {
  1197. precision = +a[precision.slice(1, -1)];
  1198. } else {
  1199. precision = +precision;
  1200. }
  1201. // grab value using valueIndex if required?
  1202. value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  1203. switch (type) {
  1204. case 's':
  1205. return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  1206. case 'c':
  1207. return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  1208. case 'b':
  1209. return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  1210. case 'o':
  1211. return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  1212. case 'x':
  1213. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  1214. case 'X':
  1215. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
  1216. case 'u':
  1217. return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  1218. case 'i':
  1219. case 'd':
  1220. number = parseInt(+value, 10);
  1221. prefix = number < 0 ? '-' : positivePrefix;
  1222. value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  1223. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  1224. case 'e':
  1225. case 'E':
  1226. case 'f':
  1227. case 'F':
  1228. case 'g':
  1229. case 'G':
  1230. number = +value;
  1231. prefix = number < 0 ? '-' : positivePrefix;
  1232. method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  1233. textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  1234. v

Large files files are truncated, but you can click here to view the full file