PageRenderTime 78ms CodeModel.GetById 36ms RepoModel.GetById 1ms app.codeStats 2ms

/js/yii/vendors/phpjs/php.js

http://github.com/phpnode/YiiJS
JavaScript | 7274 lines | 4178 code | 533 blank | 2563 comment | 1166 complexity | f435a70ee00a32b18ecea0911100c6b9 MD5 | raw file

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

  1. /*
  2. * More info at: http://phpjs.org
  3. *
  4. * This is version: 3.24
  5. * php.js is copyright 2011 Kevin van Zonneveld.
  6. *
  7. * Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
  8. * (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
  9. * (http://getsprink.com), Waldo Malqui Silva, Paulo Freitas, Jonas Raoni
  10. * Soares Silva (http://www.jsfromhell.com), Jack, Philip Peterson, Ates Goral
  11. * (http://magnetiq.com), Legaev Andrey, Ratheous, Alex, Martijn Wieringa,
  12. * Nate, lmeyrick (https://sourceforge.net/projects/bcmath-js/), Enrique
  13. * Gonzalez, Philippe Baumann, Rafał Kukawski (http://blog.kukawski.pl),
  14. * Webtoolkit.info (http://www.webtoolkit.info/), Ole Vrijenhoek, Ash Searle
  15. * (http://hexmen.com/blog/), travc, Carlos R. L. Rodrigues
  16. * (http://www.jsfromhell.com), Jani Hartikainen, stag019, GeekFG
  17. * (http://geekfg.blogspot.com), WebDevHobo (http://webdevhobo.blogspot.com/),
  18. * Erkekjetter, pilus, Rafał Kukawski (http://blog.kukawski.pl/), Johnny Mast
  19. * (http://www.phpvrouwen.nl), T.Wild,
  20. * http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
  21. * d3x, Michael Grier, Andrea Giammarchi (http://webreflection.blogspot.com),
  22. * marrtins, Mailfaker (http://www.weedem.fr/), Steve Hilder, gettimeofday,
  23. * mdsjack (http://www.mdsjack.bo.it), felix, majak, Steven Levithan
  24. * (http://blog.stevenlevithan.com), Mirek Slugen, Oleg Eremeev, Felix
  25. * Geisendoerfer (http://www.debuggable.com/felix), Martin
  26. * (http://www.erlenwiese.de/), gorthaur, Lars Fischer, Joris, AJ, Paul Smith,
  27. * Tim de Koning (http://www.kingsquare.nl), KELAN, Josh Fraser
  28. * (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
  29. * Chris, Marc Palau, Kevin van Zonneveld (http://kevin.vanzonneveld.net/),
  30. * Arpad Ray (mailto:arpad@php.net), Breaking Par Consulting Inc
  31. * (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
  32. * Nathan, Karol Kowalski, David, Dreamer, Diplom@t (http://difane.com/), Caio
  33. * Ariede (http://caioariede.com), Robin, Imgen Tata (http://www.myipdf.com/),
  34. * Pellentesque Malesuada, saulius, Aman Gupta, Sakimori, Tyler Akins
  35. * (http://rumkin.com), Thunder.m, Public Domain
  36. * (http://www.json.org/json2.js), Michael White, Kankrelune
  37. * (http://www.webfaktory.info/), Alfonso Jimenez
  38. * (http://www.alfonsojimenez.com), Frank Forte, vlado houba, Marco, Billy,
  39. * David James, madipta, noname, sankai, class_exists, Jalal Berrami, ger,
  40. * Itsacon (http://www.itsacon.net/), Scott Cariss, nobbler, Arno, Denny
  41. * Wardhana, ReverseSyntax, Mateusz "loonquawl" Zalega, Slawomir Kaniecki,
  42. * Francois, Fox, mktime, Douglas Crockford (http://javascript.crockford.com),
  43. * john (http://www.jd-tech.net), Oskar Larsson Högfeldt
  44. * (http://oskar-lh.name/), marc andreu, Nick Kolosov (http://sammy.ru), date,
  45. * Marc Jansen, Steve Clay, Olivier Louvignes (http://mg-crea.com/), Soren
  46. * Hansen, merabi, Subhasis Deb, josh, T0bsn, Tim Wiel, Brad Touesnard, MeEtc
  47. * (http://yass.meetcweb.com), Peter-Paul Koch
  48. * (http://www.quirksmode.org/js/beat.html), Pyerre, Jon Hohle, duncan, Bayron
  49. * Guevara, Adam Wallner (http://web2.bitbaro.hu/), paulo kuong, Gilbert,
  50. * Lincoln Ramsay, Thiago Mata (http://thiagomata.blog.com), Linuxworld,
  51. * lmeyrick (https://sourceforge.net/projects/bcmath-js/this.), djmix, Bryan
  52. * Elliott, David Randall, Sanjoy Roy, jmweb, Francesco, Stoyan Kyosev
  53. * (http://www.svest.org/), J A R, kenneth, T. Wild, Ole Vrijenhoek
  54. * (http://www.nervous.nl/), Raphael (Ao RUDLER), Shingo, LH, JB, nord_ua, jd,
  55. * JT, Thomas Beaucourt (http://www.webapp.fr), Ozh, XoraX
  56. * (http://www.xorax.info), EdorFaus, Eugene Bulkin (http://doubleaw.com/),
  57. * Der Simon (http://innerdom.sourceforge.net/), 0m3r, echo is bad,
  58. * FremyCompany, stensi, Kristof Coomans (SCK-CEN Belgian Nucleair Research
  59. * Centre), Devan Penner-Woelk, Pierre-Luc Paour, Martin Pool, Brant Messenger
  60. * (http://www.brantmessenger.com/), Kirk Strobeck, Saulo Vallory, Christoph,
  61. * Wagner B. Soares, Artur Tchernychev, Valentina De Rosa, Jason Wong
  62. * (http://carrot.org/), Daniel Esteban, strftime, Rick Waldron, Mick@el,
  63. * Anton Ongson, Bjorn Roesbeke (http://www.bjornroesbeke.be/), Simon Willison
  64. * (http://simonwillison.net), Gabriel Paderni, Philipp Lenssen, Marco van
  65. * Oort, Bug?, Blues (http://tech.bluesmoon.info/), Tomasz Wesolowski, rezna,
  66. * Eric Nagel, Evertjan Garretsen, Luke Godfrey, Pul, Bobby Drake, uestla,
  67. * Alan C, Ulrich, Zahlii, Yves Sucaet, sowberry, Norman "zEh" Fuchs, hitwork,
  68. * johnrembo, Brian Tafoya (http://www.premasolutions.com/), Nick Callen,
  69. * Steven Levithan (stevenlevithan.com), ejsanders, Scott Baker, Philippe
  70. * Jausions (http://pear.php.net/user/jausions), Aidan Lister
  71. * (http://aidanlister.com/), Rob, e-mike, HKM, ChaosNo1, metjay, strcasecmp,
  72. * strcmp, Taras Bogach, jpfle, Alexander Ermolaev
  73. * (http://snippets.dzone.com/user/AlexanderErmolaev), DxGx, kilops, Orlando,
  74. * dptr1988, Le Torbi, James (http://www.james-bell.co.uk/), Pedro Tainha
  75. * (http://www.pedrotainha.com), James, penutbutterjelly, Arnout Kazemier
  76. * (http://www.3rd-Eden.com), 3D-GRAF, daniel airton wermann
  77. * (http://wermann.com.br), jakes, Yannoo, FGFEmperor, gabriel paderni, Atli
  78. * Þór, Maximusya, Diogo Resende, Rival, Howard Yeend, Allan Jensen
  79. * (http://www.winternet.no), davook, Benjamin Lupton, baris ozdil, Greg
  80. * Frazier, Manish, Matt Bradley, Cord, fearphage
  81. * (http://http/my.opera.com/fearphage/), Matteo, Victor, taith, Tim de
  82. * Koning, Ryan W Tenney (http://ryan.10e.us), Tod Gentille, Alexander M
  83. * Beedie, Riddler (http://www.frontierwebdev.com/), Luis Salazar
  84. * (http://www.freaky-media.com/), Rafał Kukawski, T.J. Leahy, Luke Smith
  85. * (http://lucassmith.name), Kheang Hok Chin (http://www.distantia.ca/),
  86. * Russell Walker (http://www.nbill.co.uk/), Jamie Beck
  87. * (http://www.terabit.ca/), Garagoth, Andrej Pavlovic, Dino, Le Torbi
  88. * (http://www.letorbi.de/), Ben (http://benblume.co.uk/), DtTvB
  89. * (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Michael, Chris
  90. * McMacken, setcookie, YUI Library:
  91. * http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Andreas,
  92. * Blues at http://hacks.bluesmoon.info/strftime/strftime.js, rem, Josep Sanz
  93. * (http://www.ws3.es/), Cagri Ekin, Lorenzo Pisani, incidence, Amirouche, Jay
  94. * Klehr, Amir Habibi (http://www.residence-mixte.com/), Tony, booeyOH, meo,
  95. * William, Greenseed, Yen-Wei Liu, Ben Bryan, Leslie Hoare, mk.keck
  96. *
  97. * Dual licensed under the MIT (MIT-LICENSE.txt)
  98. * and GPL (GPL-LICENSE.txt) licenses.
  99. *
  100. * Permission is hereby granted, free of charge, to any person obtaining a
  101. * copy of this software and associated documentation files (the
  102. * "Software"), to deal in the Software without restriction, including
  103. * without limitation the rights to use, copy, modify, merge, publish,
  104. * distribute, sublicense, and/or sell copies of the Software, and to
  105. * permit persons to whom the Software is furnished to do so, subject to
  106. * the following conditions:
  107. *
  108. * The above copyright notice and this permission notice shall be included
  109. * in all copies or substantial portions of the Software.
  110. *
  111. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  112. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  113. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  114. * IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
  115. * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  116. * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  117. * OTHER DEALINGS IN THE SOFTWARE.
  118. */
  119. // jslint.com configuration options. See: http://wiki.github.com/kvz/phpjs/jslint-options
  120. /* global window */
  121. /* jslint adsafe: false, bitwise: false, browser: false, cap: false, css: false, debug: false, devel: false, eqeqeq: true, evil: false, forin: false, fragment: false, immed: true, indent: 4, laxbreak: false, maxerr: 100, maxlen: 80, newcap: true, nomen: false, on: true, onevar: false, passfail: false, plusplus: false, regexp: false, rhino: false, safe: false, sidebar: false, strict: false, sub: false, undef: true, white: false, widget: false */
  122. // Our idea with CommonJS is that you can do the following:
  123. // var php = require('php');
  124. // php.md5('test');
  125. var php = {};
  126. php.ini_set = function (varname, newvalue) {
  127. // http://kevin.vanzonneveld.net
  128. // + original by: Brett Zamir (http://brett-zamir.me)
  129. // % note 1: This will not set a global_value or access level for the ini item
  130. // * example 1: ini_set('date.timezone', 'America/Chicago');
  131. // * returns 1: 'Asia/Hong_Kong'
  132. var oldval = '',
  133. that = this;
  134. this.php_js = this.php_js || {};
  135. this.php_js.ini = this.php_js.ini || {};
  136. this.php_js.ini[varname] = this.php_js.ini[varname] || {};
  137. oldval = this.php_js.ini[varname].local_value;
  138. var _setArr = function (oldval) { // Although these are set individually, they are all accumulated
  139. if (typeof oldval === 'undefined') {
  140. that.php_js.ini[varname].local_value = [];
  141. }
  142. that.php_js.ini[varname].local_value.push(newvalue);
  143. };
  144. switch (varname) {
  145. case 'extension':
  146. if (typeof this.dl === 'function') {
  147. this.dl(newvalue); // This function is only experimental in php.js
  148. }
  149. _setArr(oldval, newvalue);
  150. break;
  151. default:
  152. this.php_js.ini[varname].local_value = newvalue;
  153. break;
  154. }
  155. return oldval;
  156. };
  157. php.ini_get = function (varname) {
  158. // http://kevin.vanzonneveld.net
  159. // + original by: Brett Zamir (http://brett-zamir.me)
  160. // % note 1: The ini values must be set by ini_set or manually within an ini file
  161. // * example 1: ini_get('date.timezone');
  162. // * returns 1: 'Asia/Hong_Kong'
  163. if (this.php_js && this.php_js.ini && this.php_js.ini[varname] && this.php_js.ini[varname].local_value !== undefined) {
  164. if (this.php_js.ini[varname].local_value === null) {
  165. return '';
  166. }
  167. return this.php_js.ini[varname].local_value;
  168. }
  169. return '';
  170. }
  171. php.ctype_digit = function (text) {
  172. // http://kevin.vanzonneveld.net
  173. // + original by: Brett Zamir (http://brett-zamir.me)
  174. // - depends on: setlocale
  175. // * example 1: ctype_digit('150');
  176. // * returns 1: true
  177. if (typeof text !== 'string') {
  178. return false;
  179. }
  180. // BEGIN REDUNDANT
  181. this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
  182. // END REDUNDANT
  183. return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.dg) !== -1;
  184. };
  185. php.gmmktime = function () {
  186. // http://kevin.vanzonneveld.net
  187. // + original by: Brett Zamir (http://brett-zamir.me)
  188. // + derived from: mktime
  189. // * example 1: gmmktime(14, 10, 2, 2, 1, 2008);
  190. // * returns 1: 1201875002
  191. // * example 2: gmmktime(0, 0, -1, 1, 1, 1970);
  192. // * returns 2: -1
  193. var d = new Date(),
  194. r = arguments,
  195. i = 0,
  196. e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear'];
  197. for (i = 0; i < e.length; i++) {
  198. if (typeof r[i] === 'undefined') {
  199. r[i] = d['getUTC' + e[i]]();
  200. r[i] += (i === 3); // +1 to fix JS months.
  201. } else {
  202. r[i] = parseInt(r[i], 10);
  203. if (isNaN(r[i])) {
  204. return false;
  205. }
  206. }
  207. }
  208. // Map years 0-69 to 2000-2069 and years 70-100 to 1970-2000.
  209. r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0);
  210. // Set year, month (-1 to fix JS months), and date.
  211. // !This must come before the call to setHours!
  212. d.setUTCFullYear(r[5], r[3] - 1, r[4]);
  213. // Set hours, minutes, and seconds.
  214. d.setUTCHours(r[0], r[1], r[2]);
  215. // Divide milliseconds by 1000 to return seconds and drop decimal.
  216. // Add 1 second if negative or it'll be off from PHP by 1 second.
  217. return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0);
  218. };
  219. php.getdate = function (timestamp) {
  220. // http://kevin.vanzonneveld.net
  221. // + original by: Paulo Freitas
  222. // + input by: Alex
  223. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  224. // * example 1: getdate(1055901520);
  225. // * returns 1: {'seconds': 40, 'minutes': 58, 'hours': 21, 'mday': 17, 'wday': 2, 'mon': 6, 'year': 2003, 'yday': 167, 'weekday': 'Tuesday', 'month': 'June', '0': 1055901520}
  226. var _w = ['Sun', 'Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur'];
  227. var _m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  228. var d = ((typeof(timestamp) == 'undefined') ? new Date() : // Not provided
  229. (typeof(timestamp) == 'object') ? new Date(timestamp) : // Javascript Date()
  230. new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
  231. );
  232. var w = d.getDay();
  233. var m = d.getMonth();
  234. var y = d.getFullYear();
  235. var r = {};
  236. r.seconds = d.getSeconds();
  237. r.minutes = d.getMinutes();
  238. r.hours = d.getHours();
  239. r.mday = d.getDate();
  240. r.wday = w;
  241. r.mon = m + 1;
  242. r.year = y;
  243. r.yday = Math.floor((d - (new Date(y, 0, 1))) / 86400000);
  244. r.weekday = _w[w] + 'day';
  245. r.month = _m[m];
  246. r['0'] = parseInt(d.getTime() / 1000, 10);
  247. return r;
  248. };
  249. php.checkdate = function (m, d, y) {
  250. // Returns true(1) if it is a valid date in gregorian calendar
  251. //
  252. // version: 1103.1210
  253. // discuss at: http://phpjs.org/functions/checkdate
  254. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  255. // + improved by: Pyerre
  256. // + improved by: Theriault
  257. // * example 1: checkdate(12, 31, 2000);
  258. // * returns 1: true
  259. // * example 2: checkdate(2, 29, 2001);
  260. // * returns 2: false
  261. // * example 3: checkdate(3, 31, 2008);
  262. // * returns 3: true
  263. // * example 4: checkdate(1, 390, 2000);
  264. // * returns 4: false
  265. return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
  266. };
  267. php.gmdate = function (format, timestamp) {
  268. // Format a GMT date/time
  269. //
  270. // version: 1103.1210
  271. // discuss at: http://phpjs.org/functions/gmdate
  272. // + original by: Brett Zamir (http://brett-zamir.me)
  273. // + input by: Alex
  274. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  275. // - depends on: date
  276. // * example 1: gmdate('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400); // Return will depend on your timezone
  277. // * returns 1: '07:09:40 m is month'
  278. var dt = ((typeof(timestamp) == 'undefined') ? new Date() : // Not provided
  279. (typeof(timestamp) == 'object') ? new Date(timestamp) : // Javascript Date()
  280. new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
  281. );
  282. timestamp = Date.parse(dt.toUTCString().slice(0, -4)) / 1000;
  283. return this.date(format, timestamp);
  284. };
  285. php.mt_rand = function (min, max) {
  286. // Returns a random number from Mersenne Twister
  287. //
  288. // version: 1103.1210
  289. // discuss at: http://phpjs.org/functions/mt_rand
  290. // + original by: Onno Marsman
  291. // * example 1: mt_rand(1, 1);
  292. // * returns 1: 1
  293. var argc = arguments.length;
  294. if (argc === 0) {
  295. min = 0;
  296. max = 2147483647;
  297. } else if (argc === 1) {
  298. throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given');
  299. }
  300. return Math.floor(Math.random() * (max - min + 1)) + min;
  301. };
  302. php.abs = function (mixed_number) {
  303. // Return the absolute value of the number
  304. //
  305. // version: 1103.1210
  306. // discuss at: http://phpjs.org/functions/abs
  307. // + original by: Waldo Malqui Silva
  308. // + improved by: Karol Kowalski
  309. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  310. // + improved by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  311. // * example 1: \php.abs(4.2);
  312. // * returns 1: 4.2
  313. // * example 2: \php.abs(-4.2);
  314. // * returns 2: 4.2
  315. // * example 3: \php.abs(-5);
  316. // * returns 3: 5
  317. // * example 4: \php.abs('_argos');
  318. // * returns 4: 0
  319. return Math.abs(mixed_number) || 0;
  320. };
  321. php.addcslashes = function (str, charlist) {
  322. // Escapes all chars mentioned in charlist with backslash. It creates octal representations if asked to backslash characters with 8th bit set or with ASCII<32 (except '\n', '\r', '\t' etc...)
  323. //
  324. // version: 1103.1210
  325. // discuss at: http://phpjs.org/functions/addcslashes
  326. // + original by: Brett Zamir (http://brett-zamir.me)
  327. // % note 1: We show double backslashes in the return value example code below because a JavaScript string will not
  328. // % note 1: render them as backslashes otherwise
  329. // * example 1: \php.addcslashes('foo[ ]', 'A..z'); // Escape all ASCII within capital A to lower z range, including square brackets
  330. // * returns 1: "\\f\\o\\o\\[ \\]"
  331. // * example 2: \php.addcslashes("zoo['.']", 'z..A'); // Only escape z, period, and A here since not a lower-to-higher range
  332. // * returns 2: "\\zoo['\\.']"
  333. // * example 3: \php.addcslashes("@a\u0000\u0010\u00A9", "\0..\37!@\177..\377") == '\\@a\\000\\020\\302\\251'); // Escape as octals those specified and less than 32 (0x20) or greater than 126 (0x7E), but not otherwise
  334. // * returns 3: true
  335. // * example 4: \php.addcslashes("\u0020\u007E", "\40..\175") == '\\ ~'); // Those between 32 (0x20 or 040) and 126 (0x7E or 0176) decimal value will be backslashed if specified (not octalized)
  336. // * returns 4: true
  337. // * example 5: \php.addcslashes("\r\u0007\n", '\0..\37'); // Recognize C escape sequences if specified
  338. // * returns 5: "\\r\\a\\n"
  339. // * example 6: \php.addcslashes("\r\u0007\n", '\0'); // Do not recognize C escape sequences if not specified
  340. // * returns 7: "\r\u0007\n"
  341. var target = '',
  342. chrs = [],
  343. i = 0,
  344. j = 0,
  345. c = '',
  346. next = '',
  347. rangeBegin = '',
  348. rangeEnd = '',
  349. chr = '',
  350. begin = 0,
  351. end = 0,
  352. octalLength = 0,
  353. postOctalPos = 0,
  354. cca = 0,
  355. escHexGrp = [],
  356. encoded = '',
  357. percentHex = /%([\dA-Fa-f]+)/g;
  358. var _pad = function (n, c) {
  359. if ((n = n + "").length < c) {
  360. return new Array(++c - n.length).join("0") + n;
  361. } else {
  362. return n;
  363. }
  364. };
  365. for (i = 0; i < charlist.length; i++) {
  366. c = charlist.charAt(i);
  367. next = charlist.charAt(i + 1);
  368. if (c === '\\' && next && (/\d/).test(next)) { // Octal
  369. rangeBegin = charlist.slice(i + 1).match(/^\d+/)[0];
  370. octalLength = rangeBegin.length;
  371. postOctalPos = i + octalLength + 1;
  372. if (charlist.charAt(postOctalPos) + charlist.charAt(postOctalPos + 1) === '..') { // Octal begins range
  373. begin = rangeBegin.charCodeAt(0);
  374. if ((/\\\d/).test(charlist.charAt(postOctalPos + 2) + charlist.charAt(postOctalPos + 3))) { // Range ends with octal
  375. rangeEnd = charlist.slice(postOctalPos + 3).match(/^\d+/)[0];
  376. i += 1; // Skip range end backslash
  377. } else if (charlist.charAt(postOctalPos + 2)) { // Range ends with character
  378. rangeEnd = charlist.charAt(postOctalPos + 2);
  379. } else {
  380. throw 'Range with no end point';
  381. }
  382. end = rangeEnd.charCodeAt(0);
  383. if (end > begin) { // Treat as a range
  384. for (j = begin; j <= end; j++) {
  385. chrs.push(String.fromCharCode(j));
  386. }
  387. } else { // Supposed to treat period, begin and end as individual characters only, not a range
  388. chrs.push('.', rangeBegin, rangeEnd);
  389. }
  390. i += rangeEnd.length + 2; // Skip dots and range end (already skipped range end backslash if present)
  391. } else { // Octal is by itself
  392. chr = String.fromCharCode(parseInt(rangeBegin, 8));
  393. chrs.push(chr);
  394. }
  395. i += octalLength; // Skip range begin
  396. } else if (next + charlist.charAt(i + 2) === '..') { // Character begins range
  397. rangeBegin = c;
  398. begin = rangeBegin.charCodeAt(0);
  399. if ((/\\\d/).test(charlist.charAt(i + 3) + charlist.charAt(i + 4))) { // Range ends with octal
  400. rangeEnd = charlist.slice(i + 4).match(/^\d+/)[0];
  401. i += 1; // Skip range end backslash
  402. } else if (charlist.charAt(i + 3)) { // Range ends with character
  403. rangeEnd = charlist.charAt(i + 3);
  404. } else {
  405. throw 'Range with no end point';
  406. }
  407. end = rangeEnd.charCodeAt(0);
  408. if (end > begin) { // Treat as a range
  409. for (j = begin; j <= end; j++) {
  410. chrs.push(String.fromCharCode(j));
  411. }
  412. } else { // Supposed to treat period, begin and end as individual characters only, not a range
  413. chrs.push('.', rangeBegin, rangeEnd);
  414. }
  415. i += rangeEnd.length + 2; // Skip dots and range end (already skipped range end backslash if present)
  416. } else { // Character is by itself
  417. chrs.push(c);
  418. }
  419. }
  420. for (i = 0; i < str.length; i++) {
  421. c = str.charAt(i);
  422. if (chrs.indexOf(c) !== -1) {
  423. target += '\\';
  424. cca = c.charCodeAt(0);
  425. if (cca < 32 || cca > 126) { // Needs special escaping
  426. switch (c) {
  427. case '\n':
  428. target += 'n';
  429. break;
  430. case '\t':
  431. target += 't';
  432. break;
  433. case '\u000D':
  434. target += 'r';
  435. break;
  436. case '\u0007':
  437. target += 'a';
  438. break;
  439. case '\v':
  440. target += 'v';
  441. break;
  442. case '\b':
  443. target += 'b';
  444. break;
  445. case '\f':
  446. target += 'f';
  447. break;
  448. default:
  449. //target += _pad(cca.toString(8), 3);break; // Sufficient for UTF-16
  450. encoded = encodeURIComponent(c);
  451. // 3-length-padded UTF-8 octets
  452. if ((escHexGrp = percentHex.exec(encoded)) !== null) {
  453. target += _pad(parseInt(escHexGrp[1], 16).toString(8), 3); // already added a slash above
  454. }
  455. while ((escHexGrp = percentHex.exec(encoded)) !== null) {
  456. target += '\\' + _pad(parseInt(escHexGrp[1], 16).toString(8), 3);
  457. }
  458. break;
  459. }
  460. } else { // Perform regular backslashed escaping
  461. target += c;
  462. }
  463. } else { // Just add the character unescaped
  464. target += c;
  465. }
  466. }
  467. return target;
  468. };
  469. php.addslashes = function (str) {
  470. // Escapes single quote, double quotes and backslash characters in a string with backslashes
  471. //
  472. // version: 1103.1210
  473. // discuss at: http://phpjs.org/functions/addslashes
  474. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  475. // + improved by: Ates Goral (http://magnetiq.com)
  476. // + improved by: marrtins
  477. // + improved by: Nate
  478. // + improved by: Onno Marsman
  479. // + input by: Denny Wardhana
  480. // + improved by: Brett Zamir (http://brett-zamir.me)
  481. // + improved by: Oskar Larsson Högfeldt (http://oskar-lh.name/)
  482. // * example 1: \php.addslashes("kevin's birthday");
  483. // * returns 1: 'kevin\'s birthday'
  484. return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
  485. };
  486. php.array_chunk = function (input, size) {
  487. // Split array into chunks
  488. //
  489. // version: 1103.1210
  490. // discuss at: http://phpjs.org/functions/array_chunk
  491. // + original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
  492. // * example 1: \php.array_chunk(['Kevin', 'van', 'Zonneveld'], 2);
  493. // * returns 1: {0 : {0: 'Kevin', 1: 'van'} , 1 : {0: 'Zonneveld'}}
  494. for (var x, i = 0, c = -1, l = input.length, n = []; i < l; i++) {
  495. (x = i % size) ? n[c][x] = input[i] : n[++c] = [input[i]];
  496. }
  497. return n;
  498. };
  499. php.array_combine = function (keys, values) {
  500. // Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values
  501. //
  502. // version: 1103.1210
  503. // discuss at: http://phpjs.org/functions/array_combine
  504. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  505. // + improved by: Brett Zamir (http://brett-zamir.me)
  506. // * example 1: \php.array_combine([0,1,2], ['kevin','van','zonneveld']);
  507. // * returns 1: {0: 'kevin', 1: 'van', 2: 'zonneveld'}
  508. var new_array = {},
  509. keycount = keys && keys.length,
  510. i = 0;
  511. // input sanitation
  512. if (typeof keys !== 'object' || typeof values !== 'object' || // Only accept arrays or array-like objects
  513. typeof keycount !== 'number' || typeof values.length !== 'number' || !keycount) { // Require arrays to have a count
  514. return false;
  515. }
  516. // number of elements does not match
  517. if (keycount != values.length) {
  518. return false;
  519. }
  520. for (i = 0; i < keycount; i++) {
  521. new_array[keys[i]] = values[i];
  522. }
  523. return new_array;
  524. };
  525. php.array_diff = function () {
  526. // Returns the entries of arr1 that have values which are not present in any of the others arguments.
  527. //
  528. // version: 1103.1210
  529. // discuss at: http://phpjs.org/functions/array_diff
  530. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  531. // + improved by: Sanjoy Roy
  532. // + revised by: Brett Zamir (http://brett-zamir.me)
  533. // * example 1: \php.array_diff(['Kevin', 'van', 'Zonneveld'], ['van', 'Zonneveld']);
  534. // * returns 1: {0:'Kevin'}
  535. var arr1 = arguments[0],
  536. retArr = {};
  537. var k1 = '',
  538. i = 1,
  539. k = '',
  540. arr = {};
  541. arr1keys: for (k1 in arr1) {
  542. for (i = 1; i < arguments.length; i++) {
  543. arr = arguments[i];
  544. for (k in arr) {
  545. if (arr[k] === arr1[k1]) {
  546. // If it reaches here, it was found in at least one array, so try next value
  547. continue arr1keys;
  548. }
  549. }
  550. retArr[k1] = arr1[k1];
  551. }
  552. }
  553. return retArr;
  554. };
  555. php.array_fill = function (start_index, num, mixed_val) {
  556. // Create an array containing num elements starting with index start_key each initialized to val
  557. //
  558. // version: 1103.1210
  559. // discuss at: http://phpjs.org/functions/array_fill
  560. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  561. // + improved by: Waldo Malqui Silva
  562. // * example 1: \php.array_fill(5, 6, 'banana');
  563. // * returns 1: { 5: 'banana', 6: 'banana', 7: 'banana', 8: 'banana', 9: 'banana', 10: 'banana' }
  564. var key, tmp_arr = {};
  565. if (!isNaN(start_index) && !isNaN(num)) {
  566. for (key = 0; key < num; key++) {
  567. tmp_arr[(key + start_index)] = mixed_val;
  568. }
  569. }
  570. return tmp_arr;
  571. };
  572. php.array_fill_keys = function (keys, value) {
  573. // Create an array using the elements of the first parameter as keys each initialized to val
  574. //
  575. // version: 1103.1210
  576. // discuss at: http://phpjs.org/functions/array_fill_keys
  577. // + original by: Brett Zamir (http://brett-zamir.me)
  578. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  579. // * example 1: \php.keys = {'a': 'foo', 2: 5, 3: 10, 4: 'bar'}
  580. // * example 1: \php.array_fill_keys(keys, 'banana')
  581. // * returns 1: {"foo": "banana", 5: "banana", 10: "banana", "bar": "banana"}
  582. var retObj = {},
  583. key = '';
  584. for (key in keys) {
  585. retObj[keys[key]] = value;
  586. }
  587. return retObj;
  588. };
  589. php.array_filter = function (arr, func) {
  590. // Filters elements from the array via the callback.
  591. //
  592. // version: 1103.1210
  593. // discuss at: http://phpjs.org/functions/array_filter
  594. // + original by: Brett Zamir (http://brett-zamir.me)
  595. // % note 1: Takes a function as an argument, not a function's name
  596. // * example 1: \php.var odd = function (num) {return (num & 1);};
  597. // * example 1: \php.array_filter({"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}, odd);
  598. // * returns 1: {"a": 1, "c": 3, "e": 5}
  599. // * example 2: \php.var even = function (num) {return (!(num & 1));}
  600. // * example 2: \php.array_filter([6, 7, 8, 9, 10, 11, 12], even);
  601. // * returns 2: {0: 6, 2: 8, 4: 10, 6: 12}
  602. var retObj = {},
  603. k;
  604. for (k in arr) {
  605. if (func(arr[k])) {
  606. retObj[k] = arr[k];
  607. }
  608. }
  609. return retObj;
  610. };
  611. php.array_flip = function (trans) {
  612. // Return array with key <-> value flipped
  613. //
  614. // version: 1103.1210
  615. // discuss at: http://phpjs.org/functions/array_flip
  616. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  617. // * example 1: \php.array_flip( {a: 1, b: 1, c: 2} );
  618. // * returns 1: {1: 'b', 2: 'c'}
  619. var key, tmp_ar = {};
  620. for (key in trans) {
  621. tmp_ar[trans[key]] = key;
  622. }
  623. return tmp_ar;
  624. };
  625. php.array_intersect = function () {
  626. // Returns the entries of arr1 that have values which are present in all the other arguments
  627. //
  628. // version: 1103.1210
  629. // discuss at: http://phpjs.org/functions/array_intersect
  630. // + original by: Brett Zamir (http://brett-zamir.me)
  631. // % note 1: These only output associative arrays (would need to be
  632. // % note 1: all numeric and counting from zero to be numeric)
  633. // * example 1: $array1 = {'a' : 'green', 0:'red', 1: 'blue'};
  634. // * example 1: $array2 = {'b' : 'green', 0:'yellow', 1:'red'};
  635. // * example 1: $array3 = ['green', 'red'];
  636. // * example 1: $result = array_intersect($array1, $array2, $array3);
  637. // * returns 1: {0: 'red', a: 'green'}
  638. var arr1 = arguments[0],
  639. retArr = {};
  640. var k1 = '',
  641. arr = {},
  642. i = 0,
  643. k = '';
  644. arr1keys: for (k1 in arr1) {
  645. arrs: for (i = 1; i < arguments.length; i++) {
  646. arr = arguments[i];
  647. for (k in arr) {
  648. if (arr[k] === arr1[k1]) {
  649. if (i === arguments.length - 1) {
  650. retArr[k1] = arr1[k1];
  651. }
  652. // If the innermost loop always leads at least once to an equal value, continue the loop until done
  653. continue arrs;
  654. }
  655. }
  656. // If it reaches here, it wasn't found in at least one array, so try next value
  657. continue arr1keys;
  658. }
  659. }
  660. return retArr;
  661. };
  662. php.array_key_exists = function (key, search) {
  663. // Checks if the given key or index exists in the array
  664. //
  665. // version: 1103.1210
  666. // discuss at: http://phpjs.org/functions/array_key_exists
  667. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  668. // + improved by: Felix Geisendoerfer (http://www.debuggable.com/felix)
  669. // * example 1: \php.array_key_exists('kevin', {'kevin': 'van Zonneveld'});
  670. // * returns 1: true
  671. // input sanitation
  672. if (!search || (search.constructor !== Array && search.constructor !== Object)) {
  673. return false;
  674. }
  675. return key in search;
  676. };
  677. php.array_keys = function (input, search_value, argStrict) {
  678. // Return just the keys from the input array, optionally only for the specified search_value
  679. //
  680. // version: 1103.1210
  681. // discuss at: http://phpjs.org/functions/array_keys
  682. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  683. // + input by: Brett Zamir (http://brett-zamir.me)
  684. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  685. // + improved by: jd
  686. // + improved by: Brett Zamir (http://brett-zamir.me)
  687. // * example 1: \php.array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} );
  688. // * returns 1: {0: 'firstname', 1: 'surname'}
  689. var search = typeof search_value !== 'undefined',
  690. tmp_arr = [],
  691. strict = !!argStrict,
  692. include = true,
  693. key = '';
  694. for (key in input) {
  695. if (input.hasOwnProperty(key)) {
  696. include = true;
  697. if (search) {
  698. if (strict && input[key] !== search_value) {
  699. include = false;
  700. }
  701. else if (input[key] != search_value) {
  702. include = false;
  703. }
  704. }
  705. if (include) {
  706. tmp_arr[tmp_arr.length] = key;
  707. }
  708. }
  709. }
  710. return tmp_arr;
  711. };
  712. php.array_map = function (callback) {
  713. // Applies the callback to the elements in given arrays.
  714. //
  715. // version: 1103.1210
  716. // discuss at: http://phpjs.org/functions/array_map
  717. // + original by: Andrea Giammarchi (http://webreflection.blogspot.com)
  718. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  719. // + improved by: Brett Zamir (http://brett-zamir.me)
  720. // % note 1: Takes a function as an argument, not a function's name
  721. // % note 2: If the callback is a string, it can only work if the function name is in the global context
  722. // * example 1: \php.array_map( function (a){return (a * a * a)}, [1, 2, 3, 4, 5] );
  723. // * returns 1: [ 1, 8, 27, 64, 125 ]
  724. var argc = arguments.length,
  725. argv = arguments;
  726. var j = argv[1].length,
  727. i = 0,
  728. k = 1,
  729. m = 0;
  730. var tmp = [],
  731. tmp_ar = [];
  732. while (i < j) {
  733. while (k < argc) {
  734. tmp[m++] = argv[k++][i];
  735. }
  736. m = 0;
  737. k = 1;
  738. if (callback) {
  739. if (typeof callback === 'string') {
  740. callback = this.window[callback];
  741. }
  742. tmp_ar[i++] = callback.apply(null, tmp);
  743. } else {
  744. tmp_ar[i++] = tmp;
  745. }
  746. tmp = [];
  747. }
  748. return tmp_ar;
  749. };
  750. php.array_merge = function () {
  751. // Merges elements from passed arrays into one array
  752. //
  753. // version: 1103.1210
  754. // discuss at: http://phpjs.org/functions/array_merge
  755. // + original by: Brett Zamir (http://brett-zamir.me)
  756. // + bugfixed by: Nate
  757. // + input by: josh
  758. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  759. // * example 1: \php.arr1 = {"color": "red", 0: 2, 1: 4}
  760. // * example 1: \php.arr2 = {0: "a", 1: "b", "color": "green", "shape": "trapezoid", 2: 4}
  761. // * example 1: \php.array_merge(arr1, arr2)
  762. // * returns 1: {"color": "green", 0: 2, 1: 4, 2: "a", 3: "b", "shape": "trapezoid", 4: 4}
  763. // * example 2: \php.arr1 = []
  764. // * example 2: \php.arr2 = {1: "data"}
  765. // * example 2: \php.array_merge(arr1, arr2)
  766. // * returns 2: {0: "data"}
  767. var args = Array.prototype.slice.call(arguments),
  768. retObj = {},
  769. k, j = 0,
  770. i = 0,
  771. retArr = true;
  772. for (i = 0; i < args.length; i++) {
  773. if (!(args[i] instanceof Array)) {
  774. retArr = false;
  775. break;
  776. }
  777. }
  778. if (retArr) {
  779. retArr = [];
  780. for (i = 0; i < args.length; i++) {
  781. retArr = retArr.concat(args[i]);
  782. }
  783. return retArr;
  784. }
  785. var ct = 0;
  786. for (i = 0, ct = 0; i < args.length; i++) {
  787. if (args[i] instanceof Array) {
  788. for (j = 0; j < args[i].length; j++) {
  789. retObj[ct++] = args[i][j];
  790. }
  791. } else {
  792. for (k in args[i]) {
  793. if (args[i].hasOwnProperty(k)) {
  794. if (parseInt(k, 10) + '' === k) {
  795. retObj[ct++] = args[i][k];
  796. } else {
  797. retObj[k] = args[i][k];
  798. }
  799. }
  800. }
  801. }
  802. }
  803. return retObj;
  804. };
  805. php.array_merge_recursive = function (arr1, arr2) {
  806. // Recursively merges elements from passed arrays into one array
  807. //
  808. // version: 1103.1210
  809. // discuss at: http://phpjs.org/functions/array_merge_recursive
  810. // + original by: Subhasis Deb
  811. // + input by: Brett Zamir (http://brett-zamir.me)
  812. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  813. // - depends on: array_merge
  814. // * example 1: \php.arr1 = {'color': {'favourite': 'read'}, 0: 5}
  815. // * example 1: \php.arr2 = {0: 10, 'color': {'favorite': 'green', 0: 'blue'}}
  816. // * example 1: \php.array_merge_recursive(arr1, arr2)
  817. // * returns 1: {'color': {'favorite': {0: 'red', 1: 'green'}, 0: 'blue'}, 1: 5, 1: 10}
  818. var idx = '';
  819. if ((arr1 && (arr1 instanceof Array)) && (arr2 && (arr2 instanceof Array))) {
  820. for (idx in arr2) {
  821. arr1.push(arr2[idx]);
  822. }
  823. } else if ((arr1 && (arr1 instanceof Object)) && (arr2 && (arr2 instanceof Object))) {
  824. for (idx in arr2) {
  825. if (idx in arr1) {
  826. if (typeof arr1[idx] == 'object' && typeof arr2 == 'object') {
  827. arr1[idx] = this.array_merge(arr1[idx], arr2[idx]);
  828. } else {
  829. arr1[idx] = arr2[idx];
  830. }
  831. } else {
  832. arr1[idx] = arr2[idx];
  833. }
  834. }
  835. }
  836. return arr1;
  837. };
  838. php.array_pop = function (inputArr) {
  839. // Pops an element off the end of the array
  840. //
  841. // version: 1103.1210
  842. // discuss at: http://phpjs.org/functions/array_pop
  843. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  844. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  845. // + input by: Brett Zamir (http://brett-zamir.me)
  846. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  847. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  848. // + input by: Theriault
  849. // % note 1: While IE (and other browsers) support iterating an object's
  850. // % note 1: own properties in order, if one attempts to add back properties
  851. // % note 1: in IE, they may end up in their former position due to their position
  852. // % note 1: being retained. So use of this function with "associative arrays"
  853. // % note 1: (objects) may lead to unexpected behavior in an IE environment if
  854. // % note 1: you add back properties with the same keys that you removed
  855. // * example 1: \php.array_pop([0,1,2]);
  856. // * returns 1: 2
  857. // * example 2: \php.data = {firstName: 'Kevin', surName: 'van Zonneveld'};
  858. // * example 2: \php.lastElem = array_pop(data);
  859. // * returns 2: 'van Zonneveld'
  860. // * results 2: data == {firstName: 'Kevin'}
  861. var key = '',
  862. lastKey = '';
  863. if (inputArr.hasOwnProperty('length')) {
  864. // Indexed
  865. if (!inputArr.length) {
  866. // Done popping, are we?
  867. return null;
  868. }
  869. return inputArr.pop();
  870. } else {
  871. // Associative
  872. for (key in inputArr) {
  873. if (inputArr.hasOwnProperty(key)) {
  874. lastKey = key;
  875. }
  876. }
  877. if (lastKey) {
  878. var tmp = inputArr[lastKey];
  879. delete(inputArr[lastKey]);
  880. return tmp;
  881. } else {
  882. return null;
  883. }
  884. }
  885. };
  886. php.array_push = function (inputArr) {
  887. // Pushes elements onto the end of the array
  888. //
  889. // version: 1103.1210
  890. // discuss at: http://phpjs.org/functions/array_push
  891. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  892. // + improved by: Brett Zamir (http://brett-zamir.me)
  893. // % note 1: Note also that IE retains information about property position even
  894. // % note 1: after being supposedly deleted, so if you delete properties and then
  895. // % note 1: add back properties with the same keys (including numeric) that had
  896. // % note 1: been deleted, the order will be as before; thus, this function is not
  897. // % note 1: really recommended with associative arrays (objects) in IE environments
  898. // * example 1: \php.array_push(['kevin','van'], 'zonneveld');
  899. // * returns 1: 3
  900. var i = 0,
  901. pr = '',
  902. argv = arguments,
  903. argc = argv.length,
  904. allDigits = /^\d$/,
  905. size = 0,
  906. highestIdx = 0,
  907. len = 0;
  908. if (inputArr.hasOwnProperty('length')) {
  909. for (i = 1; i < argc; i++) {
  910. inputArr[inputArr.length] = argv[i];
  911. }
  912. return inputArr.length;
  913. }
  914. // Associative (object)
  915. for (pr in inputArr) {
  916. if (inputArr.hasOwnProperty(pr)) {
  917. ++len;
  918. if (pr.search(allDigits) !== -1) {
  919. size = parseInt(pr, 10);
  920. highestIdx = size > highestIdx ? size : highestIdx;
  921. }
  922. }
  923. }
  924. for (i = 1; i < argc; i++) {
  925. inputArr[++highestIdx] = argv[i];
  926. }
  927. return len + i - 1;
  928. };
  929. php.array_reduce = function (a_input, callback) {
  930. // Iteratively reduce the array to a single value via the callback.
  931. //
  932. // version: 1103.1210
  933. // discuss at: http://phpjs.org/functions/array_reduce
  934. // + original by: Alfonso Jimenez (http://www.alfonsojimenez.com)
  935. // % note 1: Takes a function as an argument, not a function's name
  936. // * example 1: \php.array_reduce([1, 2, 3, 4, 5], function (v, w){v += w;return v;});
  937. // * returns 1: 15
  938. var lon = a_input.length;
  939. var res = 0,
  940. i = 0;
  941. var tmp = [];
  942. for (i = 0; i < lon; i += 2) {
  943. tmp[0] = a_input[i];
  944. if (a_input[(i + 1)]) {
  945. tmp[1] = a_input[(i + 1)];
  946. } else {
  947. tmp[1] = 0;
  948. }
  949. res += callback.apply(null, tmp);
  950. tmp = [];
  951. }
  952. return res;
  953. };
  954. php.array_reverse = function (array, preserve_keys) {
  955. // Return input as a new array with the order of the entries reversed
  956. //
  957. // version: 1103.1210
  958. // discuss at: http://phpjs.org/functions/array_reverse
  959. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  960. // + improved by: Karol Kowalski
  961. // * example 1: \php.array_reverse( [ 'php', '4.0', ['green', 'red'] ], true);
  962. // * returns 1: { 2: ['green', 'red'], 1: 4, 0: 'php'}
  963. var arr_len = array.length,
  964. newkey = 0,
  965. tmp_arr = {},
  966. key = '';
  967. preserve_keys = !! preserve_keys;
  968. for (key in array) {
  969. newkey = arr_len - key - 1;
  970. tmp_arr[preserve_keys ? key : newkey] = array[key];
  971. }
  972. return tmp_arr;
  973. };
  974. php.array_shift = function (inputArr) {
  975. // Pops an element off the beginning of the array
  976. //
  977. // version: 1103.1210
  978. // discuss at: http://phpjs.org/functions/array_shift
  979. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  980. // + improved by: Martijn Wieringa
  981. // % note 1: Currently does not handle objects
  982. // * example 1: \php.array_shift(['Kevin', 'van', 'Zonneveld']);
  983. // * returns 1: 'Kevin'
  984. var props = false,
  985. shift = undefined,
  986. pr = '',
  987. allDigits = /^\d$/,
  988. int_ct = -1,
  989. _checkToUpIndices = function (arr, ct, key) {
  990. // Deal with situation, e.g., if encounter index 4 and try to set it to 0, but 0 exists later in loop (need to
  991. // increment all subsequent (skipping current key, since we need its value below) until find unused)
  992. if (arr[ct] !== undefined) {
  993. var tmp = ct;
  994. ct += 1;
  995. if (ct === key) {
  996. ct += 1;
  997. }
  998. ct = _checkToUpIndices(arr, ct, key);
  999. arr[ct] = arr[tmp];
  1000. delete arr[tmp];
  1001. }
  1002. return ct;
  1003. };
  1004. if (inputArr.length === 0) {
  1005. return null;
  1006. }
  1007. if (inputArr.length > 0) {
  1008. return inputArr.shift();
  1009. }
  1010. /*
  1011. UNFINISHED FOR HANDLING OBJECTS
  1012. for (pr in inputArr) {
  1013. if (inputArr.hasOwnProperty(pr)) {
  1014. props = true;
  1015. shift = inputArr[pr];
  1016. delete inputArr[pr];
  1017. break;
  1018. }
  1019. }
  1020. for (pr in inputArr) {
  1021. if (inputArr.hasOwnProperty(pr)) {
  1022. if (pr.search(allDigits) !== -1) {
  1023. int_ct += 1;
  1024. if (parseInt(pr, 10) === int_ct) { // Key is already numbered ok, so don't need to change key for value
  1025. continue;
  1026. }
  1027. _checkToUpIndices(inputArr, int_ct, pr);
  1028. arr[int_ct] = arr[pr];
  1029. delete arr[pr];
  1030. }
  1031. }
  1032. }
  1033. if (!props) {
  1034. return null;
  1035. }
  1036. return shift;
  1037. */
  1038. };
  1039. php.array_slice = function (arr, offst, lgth, preserve_keys) {
  1040. // Returns elements specified by offset and length
  1041. //
  1042. // version: 1103.1210
  1043. // discuss at: http://phpjs.org/functions/array_slice
  1044. // + original by: Brett Zamir (http://brett-zamir.me)
  1045. // - depends on: is_int
  1046. // + input by: Brett Zamir (http://brett-zamir.me)
  1047. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  1048. // % note: Relies on is_int because !isNaN accepts floats
  1049. // * example 1: \php.array_slice(["a", "b", "c", "d", "e"], 2, -1);
  1050. // * returns 1: {0: 'c', 1: 'd'}
  1051. // * example 2: \php.array_slice(["a", "b", "c", "d", "e"], 2, -1, true);
  1052. // * returns 2: {2: 'c', 3: 'd'}
  1053. /*
  1054. if ('callee' in arr && 'length' in arr) {
  1055. arr = Array.prototype.slice.call(arr);
  1056. }
  1057. */
  1058. var key = '';
  1059. if (!(arr instanceof Array) || (preserve_keys && offst !== 0)) { // Assoc. array as input or if required as output
  1060. var lgt = 0,
  1061. newAssoc = {};
  1062. for (key in arr) {
  1063. //if (key !== 'length') {
  1064. lgt += 1;
  1065. newAssoc[key] = arr[key];
  1066. //}
  1067. }
  1068. arr = newAssoc;
  1069. offst = (offst < 0) ? lgt + offst : offst;
  1070. lgth = lgth === undefined ? lgt : (lgth < 0) ? lgt + lgth - offst : lgth;
  1071. var assoc = {};
  1072. var start = false,
  1073. it = -1,
  1074. arrlgth = 0,
  1075. no_pk_idx = 0;
  1076. for (key in arr) {
  1077. ++it;
  1078. if (arrlgth >= lgth) {
  1079. break;
  1080. }
  1081. if (it == offst) {
  1082. start = true;
  1083. }
  1084. if (!start) {
  1085. continue;
  1086. }++arrlgth;
  1087. if (this.is_int(key) && !preserve_keys) {
  1088. assoc[no_pk_idx++] = arr[key];
  1089. } else {
  1090. assoc[key] = arr[key];
  1091. }
  1092. }
  1093. //assoc.length = arrlgth; // Make as array-like object (though length will not be dynamic)
  1094. return assoc;
  1095. }
  1096. if (lgth === undefined) {
  1097. return arr.slice(offst);
  1098. } else if (lgth >= 0) {
  1099. return arr.slice(offst, offst + lgth);
  1100. } else {
  1101. return arr.slice(offst, lgth);
  1102. }
  1103. };
  1104. php.array_splice = function (arr, offst, lgth, replacement) {
  1105. // Removes the elements designated by offset and length and replace them with supplied array
  1106. //
  1107. // version: 1103.1210
  1108. // discuss at: http://phpjs.org/functions/array_splice
  1109. // + original by: Brett Zamir (http://brett-zamir.me)
  1110. // + input by: Theriault
  1111. // % note 1: Order does get shifted in associative array input with numeric indices,
  1112. // % note 1: since PHP behavior doesn't preserve keys, but I understand order is
  1113. // % note 1: not reliable anyways
  1114. // % note 2: Note also that IE retains information about property position even
  1115. // % note 2: after being supposedly deleted, so use of this function may produce
  1116. // % note 2: unexpected results in IE if you later attempt to add back properties
  1117. // % note 2: with the same keys that had been deleted
  1118. // - depends on: is_int
  1119. // * example 1: \php.input = {4: "red", 'abc': "green", 2: "blue", 'dud': "yellow"};
  1120. // * example 1: \php.array_splice(input, 2);
  1121. // * returns 1: {0: "blue", 'dud': "yellow"}
  1122. // * results 1: input == {'abc':"green", 0:"red"}
  1123. // * example 2: \php.input = ["red", "green", "blue", "yellow"];
  1124. // …

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