PageRenderTime 1658ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/joomla/administrator/components/com_joomlapack/assets/scripts/croninclude.php

https://github.com/joomla-example/joomla-repo
PHP | 1195 lines | 695 code | 151 blank | 349 comment | 130 complexity | d6360126c660c45556ffadd0f7f14f42 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * @project JoomlaPack
  4. * @author Nicholas K. Dionysopoulos
  5. * @license GPL 2.0 or any later version
  6. * @since 2.3
  7. *
  8. * LEGAL NOTICE:
  9. * ========================================
  10. * JoomlaPack JSON CRON Helper
  11. * Copyright (C) 2009 Nicholas K. Dionysopoulos / JoomlaPack Developers
  12. *
  13. * This program is free software; you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License as published by
  15. * the Free Software Foundation; either version 2 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with this program; if not, write to the Free Software
  25. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  26. *
  27. * PLEASE DO NOT MODIFY THIS SCRIPT DIRECTLY!
  28. * @todo Implement a "mail as attachment" function
  29. */
  30. // Make sure we are being called from the command line
  31. if( array_key_exists('REQUEST_METHOD', $_SERVER) ) die("Access Forbidden\n");
  32. // ============================================================================
  33. // JSON decoding, if PHP-native JSON support is not present
  34. // ============================================================================
  35. /**
  36. * Converts to and from JSON format.
  37. *
  38. * JSON (JavaScript Object Notation) is a lightweight data-interchange
  39. * format. It is easy for humans to read and write. It is easy for machines
  40. * to parse and generate. It is based on a subset of the JavaScript
  41. * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
  42. * This feature can also be found in Python. JSON is a text format that is
  43. * completely language independent but uses conventions that are familiar
  44. * to programmers of the C-family of languages, including C, C++, C#, Java,
  45. * JavaScript, Perl, TCL, and many others. These properties make JSON an
  46. * ideal data-interchange language.
  47. *
  48. * This package provides a simple encoder and decoder for JSON notation. It
  49. * is intended for use with client-side Javascript applications that make
  50. * use of HTTPRequest to perform server communication functions - data can
  51. * be encoded into JSON notation for use in a client-side javascript, or
  52. * decoded from incoming Javascript requests. JSON format is native to
  53. * Javascript, and can be directly eval()'ed with no further parsing
  54. * overhead
  55. *
  56. * All strings should be in ASCII or UTF-8 format!
  57. *
  58. * LICENSE: Redistribution and use in source and binary forms, with or
  59. * without modification, are permitted provided that the following
  60. * conditions are met: Redistributions of source code must retain the
  61. * above copyright notice, this list of conditions and the following
  62. * disclaimer. Redistributions in binary form must reproduce the above
  63. * copyright notice, this list of conditions and the following disclaimer
  64. * in the documentation and/or other materials provided with the
  65. * distribution.
  66. *
  67. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  68. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  69. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
  70. * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  71. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  72. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  73. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  74. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  75. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  76. * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  77. * DAMAGE.
  78. *
  79. * @category
  80. * @package Services_JSON
  81. * @author Michal Migurski <mike-json@teczno.com>
  82. * @author Matt Knapp <mdknapp[at]gmail[dot]com>
  83. * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
  84. * @copyright 2005 Michal Migurski
  85. * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
  86. * @license http://www.opensource.org/licenses/bsd-license.php
  87. * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
  88. */
  89. /**
  90. * Marker constant for Services_JSON::decode(), used to flag stack state
  91. */
  92. define('SERVICES_JSON_SLICE', 1);
  93. /**
  94. * Marker constant for Services_JSON::decode(), used to flag stack state
  95. */
  96. define('SERVICES_JSON_IN_STR', 2);
  97. /**
  98. * Marker constant for Services_JSON::decode(), used to flag stack state
  99. */
  100. define('SERVICES_JSON_IN_ARR', 3);
  101. /**
  102. * Marker constant for Services_JSON::decode(), used to flag stack state
  103. */
  104. define('SERVICES_JSON_IN_OBJ', 4);
  105. /**
  106. * Marker constant for Services_JSON::decode(), used to flag stack state
  107. */
  108. define('SERVICES_JSON_IN_CMT', 5);
  109. /**
  110. * Behavior switch for Services_JSON::decode()
  111. */
  112. define('SERVICES_JSON_LOOSE_TYPE', 16);
  113. /**
  114. * Behavior switch for Services_JSON::decode()
  115. */
  116. define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
  117. /**
  118. * Converts to and from JSON format.
  119. *
  120. * Brief example of use:
  121. *
  122. * <code>
  123. * // create a new instance of Services_JSON
  124. * $json = new Services_JSON();
  125. *
  126. * // convert a complexe value to JSON notation, and send it to the browser
  127. * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
  128. * $output = $json->encode($value);
  129. *
  130. * print($output);
  131. * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
  132. *
  133. * // accept incoming POST data, assumed to be in JSON notation
  134. * $input = file_get_contents('php://input', 1000000);
  135. * $value = $json->decode($input);
  136. * </code>
  137. */
  138. class Services_JSON
  139. {
  140. /**
  141. * constructs a new JSON instance
  142. *
  143. * @param int $use object behavior flags; combine with boolean-OR
  144. *
  145. * possible values:
  146. * - SERVICES_JSON_LOOSE_TYPE: loose typing.
  147. * "{...}" syntax creates associative arrays
  148. * instead of objects in decode().
  149. * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
  150. * Values which can't be encoded (e.g. resources)
  151. * appear as NULL instead of throwing errors.
  152. * By default, a deeply-nested resource will
  153. * bubble up with an error, so all return values
  154. * from encode() should be checked with isError()
  155. */
  156. function Services_JSON($use = 0)
  157. {
  158. $this->use = $use;
  159. }
  160. /**
  161. * convert a string from one UTF-16 char to one UTF-8 char
  162. *
  163. * Normally should be handled by mb_convert_encoding, but
  164. * provides a slower PHP-only method for installations
  165. * that lack the multibye string extension.
  166. *
  167. * @param string $utf16 UTF-16 character
  168. * @return string UTF-8 character
  169. * @access private
  170. */
  171. function utf162utf8($utf16)
  172. {
  173. // oh please oh please oh please oh please oh please
  174. if(function_exists('mb_convert_encoding')) {
  175. return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
  176. }
  177. $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
  178. switch(true) {
  179. case ((0x7F & $bytes) == $bytes):
  180. // this case should never be reached, because we are in ASCII range
  181. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  182. return chr(0x7F & $bytes);
  183. case (0x07FF & $bytes) == $bytes:
  184. // return a 2-byte UTF-8 character
  185. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  186. return chr(0xC0 | (($bytes >> 6) & 0x1F))
  187. . chr(0x80 | ($bytes & 0x3F));
  188. case (0xFFFF & $bytes) == $bytes:
  189. // return a 3-byte UTF-8 character
  190. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  191. return chr(0xE0 | (($bytes >> 12) & 0x0F))
  192. . chr(0x80 | (($bytes >> 6) & 0x3F))
  193. . chr(0x80 | ($bytes & 0x3F));
  194. }
  195. // ignoring UTF-32 for now, sorry
  196. return '';
  197. }
  198. /**
  199. * convert a string from one UTF-8 char to one UTF-16 char
  200. *
  201. * Normally should be handled by mb_convert_encoding, but
  202. * provides a slower PHP-only method for installations
  203. * that lack the multibye string extension.
  204. *
  205. * @param string $utf8 UTF-8 character
  206. * @return string UTF-16 character
  207. * @access private
  208. */
  209. function utf82utf16($utf8)
  210. {
  211. // oh please oh please oh please oh please oh please
  212. if(function_exists('mb_convert_encoding')) {
  213. return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
  214. }
  215. switch(strlen($utf8)) {
  216. case 1:
  217. // this case should never be reached, because we are in ASCII range
  218. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  219. return $utf8;
  220. case 2:
  221. // return a UTF-16 character from a 2-byte UTF-8 char
  222. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  223. return chr(0x07 & (ord($utf8{0}) >> 2))
  224. . chr((0xC0 & (ord($utf8{0}) << 6))
  225. | (0x3F & ord($utf8{1})));
  226. case 3:
  227. // return a UTF-16 character from a 3-byte UTF-8 char
  228. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  229. return chr((0xF0 & (ord($utf8{0}) << 4))
  230. | (0x0F & (ord($utf8{1}) >> 2)))
  231. . chr((0xC0 & (ord($utf8{1}) << 6))
  232. | (0x7F & ord($utf8{2})));
  233. }
  234. // ignoring UTF-32 for now, sorry
  235. return '';
  236. }
  237. /**
  238. * encodes an arbitrary variable into JSON format
  239. *
  240. * @param mixed $var any number, boolean, string, array, or object to be encoded.
  241. * see argument 1 to Services_JSON() above for array-parsing behavior.
  242. * if var is a strng, note that encode() always expects it
  243. * to be in ASCII or UTF-8 format!
  244. *
  245. * @return mixed JSON string representation of input var or an error if a problem occurs
  246. * @access public
  247. */
  248. function encode($var)
  249. {
  250. switch (gettype($var)) {
  251. case 'boolean':
  252. return $var ? 'true' : 'false';
  253. case 'NULL':
  254. return 'null';
  255. case 'integer':
  256. return (int) $var;
  257. case 'double':
  258. case 'float':
  259. return (float) $var;
  260. case 'string':
  261. // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  262. $ascii = '';
  263. $strlen_var = strlen($var);
  264. /*
  265. * Iterate over every character in the string,
  266. * escaping with a slash or encoding to UTF-8 where necessary
  267. */
  268. for ($c = 0; $c < $strlen_var; ++$c) {
  269. $ord_var_c = ord($var{$c});
  270. switch (true) {
  271. case $ord_var_c == 0x08:
  272. $ascii .= '\b';
  273. break;
  274. case $ord_var_c == 0x09:
  275. $ascii .= '\t';
  276. break;
  277. case $ord_var_c == 0x0A:
  278. $ascii .= '\n';
  279. break;
  280. case $ord_var_c == 0x0C:
  281. $ascii .= '\f';
  282. break;
  283. case $ord_var_c == 0x0D:
  284. $ascii .= '\r';
  285. break;
  286. case $ord_var_c == 0x22:
  287. case $ord_var_c == 0x2F:
  288. case $ord_var_c == 0x5C:
  289. // double quote, slash, slosh
  290. $ascii .= '\\'.$var{$c};
  291. break;
  292. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  293. // characters U-00000000 - U-0000007F (same as ASCII)
  294. $ascii .= $var{$c};
  295. break;
  296. case (($ord_var_c & 0xE0) == 0xC0):
  297. // characters U-00000080 - U-000007FF, mask 110XXXXX
  298. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  299. $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
  300. $c += 1;
  301. $utf16 = $this->utf82utf16($char);
  302. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  303. break;
  304. case (($ord_var_c & 0xF0) == 0xE0):
  305. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  306. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  307. $char = pack('C*', $ord_var_c,
  308. ord($var{$c + 1}),
  309. ord($var{$c + 2}));
  310. $c += 2;
  311. $utf16 = $this->utf82utf16($char);
  312. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  313. break;
  314. case (($ord_var_c & 0xF8) == 0xF0):
  315. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  316. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  317. $char = pack('C*', $ord_var_c,
  318. ord($var{$c + 1}),
  319. ord($var{$c + 2}),
  320. ord($var{$c + 3}));
  321. $c += 3;
  322. $utf16 = $this->utf82utf16($char);
  323. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  324. break;
  325. case (($ord_var_c & 0xFC) == 0xF8):
  326. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  327. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  328. $char = pack('C*', $ord_var_c,
  329. ord($var{$c + 1}),
  330. ord($var{$c + 2}),
  331. ord($var{$c + 3}),
  332. ord($var{$c + 4}));
  333. $c += 4;
  334. $utf16 = $this->utf82utf16($char);
  335. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  336. break;
  337. case (($ord_var_c & 0xFE) == 0xFC):
  338. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  339. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  340. $char = pack('C*', $ord_var_c,
  341. ord($var{$c + 1}),
  342. ord($var{$c + 2}),
  343. ord($var{$c + 3}),
  344. ord($var{$c + 4}),
  345. ord($var{$c + 5}));
  346. $c += 5;
  347. $utf16 = $this->utf82utf16($char);
  348. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  349. break;
  350. }
  351. }
  352. return '"'.$ascii.'"';
  353. case 'array':
  354. /*
  355. * As per JSON spec if any array key is not an integer
  356. * we must treat the the whole array as an object. We
  357. * also try to catch a sparsely populated associative
  358. * array with numeric keys here because some JS engines
  359. * will create an array with empty indexes up to
  360. * max_index which can cause memory issues and because
  361. * the keys, which may be relevant, will be remapped
  362. * otherwise.
  363. *
  364. * As per the ECMA and JSON specification an object may
  365. * have any string as a property. Unfortunately due to
  366. * a hole in the ECMA specification if the key is a
  367. * ECMA reserved word or starts with a digit the
  368. * parameter is only accessible using ECMAScript's
  369. * bracket notation.
  370. */
  371. // treat as a JSON object
  372. if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
  373. $properties = array_map(array($this, 'name_value'),
  374. array_keys($var),
  375. array_values($var));
  376. foreach($properties as $property) {
  377. if(Services_JSON::isError($property)) {
  378. return $property;
  379. }
  380. }
  381. return '{' . join(',', $properties) . '}';
  382. }
  383. // treat it like a regular array
  384. $elements = array_map(array($this, 'encode'), $var);
  385. foreach($elements as $element) {
  386. if(Services_JSON::isError($element)) {
  387. return $element;
  388. }
  389. }
  390. return '[' . join(',', $elements) . ']';
  391. case 'object':
  392. $vars = get_object_vars($var);
  393. $properties = array_map(array($this, 'name_value'),
  394. array_keys($vars),
  395. array_values($vars));
  396. foreach($properties as $property) {
  397. if(Services_JSON::isError($property)) {
  398. return $property;
  399. }
  400. }
  401. return '{' . join(',', $properties) . '}';
  402. default:
  403. return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
  404. ? 'null'
  405. : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
  406. }
  407. }
  408. /**
  409. * array-walking function for use in generating JSON-formatted name-value pairs
  410. *
  411. * @param string $name name of key to use
  412. * @param mixed $value reference to an array element to be encoded
  413. *
  414. * @return string JSON-formatted name-value pair, like '"name":value'
  415. * @access private
  416. */
  417. function name_value($name, $value)
  418. {
  419. $encoded_value = $this->encode($value);
  420. if(Services_JSON::isError($encoded_value)) {
  421. return $encoded_value;
  422. }
  423. return $this->encode(strval($name)) . ':' . $encoded_value;
  424. }
  425. /**
  426. * reduce a string by removing leading and trailing comments and whitespace
  427. *
  428. * @param $str string string value to strip of comments and whitespace
  429. *
  430. * @return string string value stripped of comments and whitespace
  431. * @access private
  432. */
  433. function reduce_string($str)
  434. {
  435. $str = preg_replace(array(
  436. // eliminate single line comments in '// ...' form
  437. '#^\s*//(.+)$#m',
  438. // eliminate multi-line comments in '/* ... */' form, at start of string
  439. '#^\s*/\*(.+)\*/#Us',
  440. // eliminate multi-line comments in '/* ... */' form, at end of string
  441. '#/\*(.+)\*/\s*$#Us'
  442. ), '', $str);
  443. // eliminate extraneous space
  444. return trim($str);
  445. }
  446. /**
  447. * decodes a JSON string into appropriate variable
  448. *
  449. * @param string $str JSON-formatted string
  450. *
  451. * @return mixed number, boolean, string, array, or object
  452. * corresponding to given JSON input string.
  453. * See argument 1 to Services_JSON() above for object-output behavior.
  454. * Note that decode() always returns strings
  455. * in ASCII or UTF-8 format!
  456. * @access public
  457. */
  458. function decode($str)
  459. {
  460. $str = $this->reduce_string($str);
  461. switch (strtolower($str)) {
  462. case 'true':
  463. return true;
  464. case 'false':
  465. return false;
  466. case 'null':
  467. return null;
  468. default:
  469. $m = array();
  470. if (is_numeric($str)) {
  471. // Lookie-loo, it's a number
  472. // This would work on its own, but I'm trying to be
  473. // good about returning integers where appropriate:
  474. // return (float)$str;
  475. // Return float or int, as appropriate
  476. return ((float)$str == (integer)$str)
  477. ? (integer)$str
  478. : (float)$str;
  479. } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
  480. // STRINGS RETURNED IN UTF-8 FORMAT
  481. $delim = substr($str, 0, 1);
  482. $chrs = substr($str, 1, -1);
  483. $utf8 = '';
  484. $strlen_chrs = strlen($chrs);
  485. for ($c = 0; $c < $strlen_chrs; ++$c) {
  486. $substr_chrs_c_2 = substr($chrs, $c, 2);
  487. $ord_chrs_c = ord($chrs{$c});
  488. switch (true) {
  489. case $substr_chrs_c_2 == '\b':
  490. $utf8 .= chr(0x08);
  491. ++$c;
  492. break;
  493. case $substr_chrs_c_2 == '\t':
  494. $utf8 .= chr(0x09);
  495. ++$c;
  496. break;
  497. case $substr_chrs_c_2 == '\n':
  498. $utf8 .= chr(0x0A);
  499. ++$c;
  500. break;
  501. case $substr_chrs_c_2 == '\f':
  502. $utf8 .= chr(0x0C);
  503. ++$c;
  504. break;
  505. case $substr_chrs_c_2 == '\r':
  506. $utf8 .= chr(0x0D);
  507. ++$c;
  508. break;
  509. case $substr_chrs_c_2 == '\\"':
  510. case $substr_chrs_c_2 == '\\\'':
  511. case $substr_chrs_c_2 == '\\\\':
  512. case $substr_chrs_c_2 == '\\/':
  513. if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
  514. ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
  515. $utf8 .= $chrs{++$c};
  516. }
  517. break;
  518. case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
  519. // single, escaped unicode character
  520. $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
  521. . chr(hexdec(substr($chrs, ($c + 4), 2)));
  522. $utf8 .= $this->utf162utf8($utf16);
  523. $c += 5;
  524. break;
  525. case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
  526. $utf8 .= $chrs{$c};
  527. break;
  528. case ($ord_chrs_c & 0xE0) == 0xC0:
  529. // characters U-00000080 - U-000007FF, mask 110XXXXX
  530. //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  531. $utf8 .= substr($chrs, $c, 2);
  532. ++$c;
  533. break;
  534. case ($ord_chrs_c & 0xF0) == 0xE0:
  535. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  536. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  537. $utf8 .= substr($chrs, $c, 3);
  538. $c += 2;
  539. break;
  540. case ($ord_chrs_c & 0xF8) == 0xF0:
  541. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  542. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  543. $utf8 .= substr($chrs, $c, 4);
  544. $c += 3;
  545. break;
  546. case ($ord_chrs_c & 0xFC) == 0xF8:
  547. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  548. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  549. $utf8 .= substr($chrs, $c, 5);
  550. $c += 4;
  551. break;
  552. case ($ord_chrs_c & 0xFE) == 0xFC:
  553. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  554. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  555. $utf8 .= substr($chrs, $c, 6);
  556. $c += 5;
  557. break;
  558. }
  559. }
  560. return $utf8;
  561. } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
  562. // array, or object notation
  563. if ($str{0} == '[') {
  564. $stk = array(SERVICES_JSON_IN_ARR);
  565. $arr = array();
  566. } else {
  567. if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
  568. $stk = array(SERVICES_JSON_IN_OBJ);
  569. $obj = array();
  570. } else {
  571. $stk = array(SERVICES_JSON_IN_OBJ);
  572. $obj = new stdClass();
  573. }
  574. }
  575. array_push($stk, array('what' => SERVICES_JSON_SLICE,
  576. 'where' => 0,
  577. 'delim' => false));
  578. $chrs = substr($str, 1, -1);
  579. $chrs = $this->reduce_string($chrs);
  580. if ($chrs == '') {
  581. if (reset($stk) == SERVICES_JSON_IN_ARR) {
  582. return $arr;
  583. } else {
  584. return $obj;
  585. }
  586. }
  587. //print("\nparsing {$chrs}\n");
  588. $strlen_chrs = strlen($chrs);
  589. for ($c = 0; $c <= $strlen_chrs; ++$c) {
  590. $top = end($stk);
  591. $substr_chrs_c_2 = substr($chrs, $c, 2);
  592. if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
  593. // found a comma that is not inside a string, array, etc.,
  594. // OR we've reached the end of the character list
  595. $slice = substr($chrs, $top['where'], ($c - $top['where']));
  596. array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
  597. //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  598. if (reset($stk) == SERVICES_JSON_IN_ARR) {
  599. // we are in an array, so just push an element onto the stack
  600. array_push($arr, $this->decode($slice));
  601. } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
  602. // we are in an object, so figure
  603. // out the property name and set an
  604. // element in an associative array,
  605. // for now
  606. $parts = array();
  607. if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  608. // "name":value pair
  609. $key = $this->decode($parts[1]);
  610. $val = $this->decode($parts[2]);
  611. if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
  612. $obj[$key] = $val;
  613. } else {
  614. $obj->$key = $val;
  615. }
  616. } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  617. // name:value pair, where name is unquoted
  618. $key = $parts[1];
  619. $val = $this->decode($parts[2]);
  620. if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
  621. $obj[$key] = $val;
  622. } else {
  623. $obj->$key = $val;
  624. }
  625. }
  626. }
  627. } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
  628. // found a quote, and we are not inside a string
  629. array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
  630. //print("Found start of string at {$c}\n");
  631. } elseif (($chrs{$c} == $top['delim']) &&
  632. ($top['what'] == SERVICES_JSON_IN_STR) &&
  633. ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
  634. // found a quote, we're in a string, and it's not escaped
  635. // we know that it's not escaped becase there is _not_ an
  636. // odd number of backslashes at the end of the string so far
  637. array_pop($stk);
  638. //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
  639. } elseif (($chrs{$c} == '[') &&
  640. in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
  641. // found a left-bracket, and we are in an array, object, or slice
  642. array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
  643. //print("Found start of array at {$c}\n");
  644. } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
  645. // found a right-bracket, and we're in an array
  646. array_pop($stk);
  647. //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  648. } elseif (($chrs{$c} == '{') &&
  649. in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
  650. // found a left-brace, and we are in an array, object, or slice
  651. array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
  652. //print("Found start of object at {$c}\n");
  653. } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
  654. // found a right-brace, and we're in an object
  655. array_pop($stk);
  656. //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  657. } elseif (($substr_chrs_c_2 == '/*') &&
  658. in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
  659. // found a comment start, and we are in an array, object, or slice
  660. array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
  661. $c++;
  662. //print("Found start of comment at {$c}\n");
  663. } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
  664. // found a comment end, and we're in one now
  665. array_pop($stk);
  666. $c++;
  667. for ($i = $top['where']; $i <= $c; ++$i)
  668. $chrs = substr_replace($chrs, ' ', $i, 1);
  669. //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  670. }
  671. }
  672. if (reset($stk) == SERVICES_JSON_IN_ARR) {
  673. return $arr;
  674. } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
  675. return $obj;
  676. }
  677. }
  678. }
  679. }
  680. /**
  681. * @todo Ultimately, this should just call PEAR::isError()
  682. */
  683. function isError($data, $code = null)
  684. {
  685. if (class_exists('pear')) {
  686. return PEAR::isError($data, $code);
  687. } elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
  688. is_subclass_of($data, 'services_json_error'))) {
  689. return true;
  690. }
  691. return false;
  692. }
  693. }
  694. if (class_exists('PEAR_Error')) {
  695. class Services_JSON_Error extends PEAR_Error
  696. {
  697. function Services_JSON_Error($message = 'unknown error', $code = null,
  698. $mode = null, $options = null, $userinfo = null)
  699. {
  700. parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
  701. }
  702. }
  703. } else {
  704. /**
  705. * @todo Ultimately, this class shall be descended from PEAR_Error
  706. */
  707. class Services_JSON_Error
  708. {
  709. function Services_JSON_Error($message = 'unknown error', $code = null,
  710. $mode = null, $options = null, $userinfo = null)
  711. {
  712. }
  713. }
  714. }
  715. // ============================================================================
  716. // Site Backup Functions
  717. // ============================================================================
  718. /**
  719. * Generates a random string which can be sent as part of the URL
  720. * @return string
  721. * @param int $length[optional] The length of the random string, defaults to 8 characters
  722. */
  723. function genRandomPassword($length = 8)
  724. {
  725. $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  726. $len = strlen($salt);
  727. $makepass = '';
  728. $stat = @stat(__FILE__);
  729. if(empty($stat) || !is_array($stat)) $stat = array(php_uname());
  730. mt_srand(crc32(microtime() . implode('|', $stat)));
  731. for ($i = 0; $i < $length; $i ++) {
  732. $makepass .= $salt[mt_rand(0, $len -1)];
  733. }
  734. return $makepass;
  735. }
  736. /**
  737. * Gets the URL for asking JSON output
  738. * @return string
  739. * @param string $task The task to perform
  740. */
  741. function getURL($task)
  742. {
  743. global $config;
  744. // Build the base URL
  745. $url = rtrim($config['siteurl'],'/').'/';
  746. $url .= 'index2.php?option=com_joomlapack&view=json';
  747. // Add the task
  748. if(!empty($task)) $url.='&task='.$task;
  749. // Add encrypted key
  750. $salt = genRandomPassword(32);
  751. $url .= '&keyhash='.md5($config['secret'].$salt).':'.$salt;
  752. // Add profile, or 1 if it doesn't exist
  753. $profile = !(empty($config['profile'])) ? $config['profile'] : '1';
  754. $url .= '&profile='.$profile;
  755. // Raw output
  756. $url .= '&format=raw';
  757. return $url;
  758. }
  759. /**
  760. * Accesses the given URL and returns the server's response
  761. * @return string|bool The server response, or FALSE if it failed
  762. * @param string $url The URL to access
  763. */
  764. function getServerResponse($url)
  765. {
  766. $curl_handle=curl_init();
  767. curl_setopt($curl_handle,CURLOPT_URL,$url);
  768. curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
  769. $buffer = curl_exec($curl_handle);
  770. curl_close($curl_handle);
  771. if (empty($buffer))
  772. return false;
  773. else
  774. return $buffer;
  775. }
  776. /**
  777. * Decodes a JSON result string
  778. * @return mixed
  779. * @param string $json
  780. */
  781. function decodeJSON($json)
  782. {
  783. if(function_exists('json_decode'))
  784. {
  785. return json_decode($json, true);
  786. }
  787. else
  788. {
  789. $processor = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
  790. return $processor->decode($json);
  791. }
  792. }
  793. function parseCUBE($result)
  794. {
  795. global $config;
  796. if(!is_array($result))
  797. {
  798. if($config['verbose'])
  799. echo "Unknown server response type\n";
  800. return 0;
  801. }
  802. if(!empty($result['Error']))
  803. {
  804. if($config['verbose'])
  805. echo "An error occured during backup:\n".$result['Error'];
  806. return 0;
  807. }
  808. if($result['HasRun'] == 1)
  809. {
  810. // Backup just finished
  811. global $archive;
  812. $archive = $result['Archive'];
  813. return 2;
  814. }
  815. else
  816. {
  817. // We have more work to do
  818. global $count;
  819. $count++;
  820. if($config['verbose'])
  821. {
  822. echo "\t========== Step $count ==========\n";
  823. echo "\tDomain : ".$result['Domain']."\n";
  824. echo "\tStep : ".$result['Step']."\n";
  825. echo "\tSubstep : ".$result['Substep']."\n";
  826. }
  827. return 1;
  828. }
  829. }
  830. /**
  831. * Starts or continues the backup
  832. * @return int Status (0 fail, 1 continue)
  833. */
  834. function doBackup($task)
  835. {
  836. global $config;
  837. $url = getURL($task);
  838. $result = getServerResponse($url);
  839. if($result === false)
  840. {
  841. if($config['verbose'])
  842. echo "Could not retrieve a response from the server\n";
  843. return 0;
  844. }
  845. else
  846. {
  847. $original = $result;
  848. $result = decodeJSON($result);
  849. if(is_null($result))
  850. {
  851. echo $original."\n";
  852. }
  853. return parseCUBE($result);
  854. }
  855. }
  856. // ============================================================================
  857. // FTP Functions
  858. // ============================================================================
  859. /**
  860. * Uploads the backup file to a remote server using FTP
  861. * @param string $filename The name of the backup file
  862. * @return bool True on success
  863. */
  864. function upload($filename)
  865. {
  866. echo "Uploading $filename\n";
  867. global $config;
  868. // Connect to server
  869. if($config['verbose']) echo "\tConnecting to FTP server\n";
  870. $ftp = ftp_connect($config['ftphost'], $config['ftpport']);
  871. if($ftp === false)
  872. {
  873. if($config['verbose']) echo "Invalid FTP host or port\n";
  874. return false;
  875. }
  876. // Login user
  877. if($config['verbose']) echo "\tLogging in\n";
  878. if(@ftp_login($ftp, $config['ftpuser'], $config['ftppass']) === false)
  879. {
  880. if($config['verbose']) echo "Invalid FTP username or password\n";
  881. @ftp_close($ftp);
  882. return false;
  883. }
  884. // Use PASV
  885. if($config['verbose']) echo "\tSetting PASV mode\n";
  886. if(@ftp_pasv($ftp, true) === false)
  887. {
  888. if($config['verbose']) echo "Could not change PASV mode\n";
  889. @ftp_close($ftp);
  890. return false;
  891. }
  892. // Change to requested directory
  893. if($config['verbose']) echo "\tChanging to directory\n";
  894. if(@ftp_chdir($ftp, $config['ftpdir']) === false)
  895. {
  896. if($config['verbose']) echo "Invalid FTP directory\n";
  897. @ftp_close($ftp);
  898. return false;
  899. }
  900. // Get the file
  901. if($config['verbose']) echo "\tUploading file\n";
  902. if(@ftp_put($ftp, basename($filename), $filename, FTP_BINARY) === false)
  903. {
  904. if($config['verbose']) echo "Could not PUT file to the FTP server\n";
  905. @ftp_close($ftp);
  906. return false;
  907. }
  908. @ftp_close($ftp);
  909. return true;
  910. }
  911. function send_by_email($filename)
  912. {
  913. global $config;
  914. //define the receiver of the email
  915. $to = $config['email'];
  916. //define the subject of the email
  917. $subject = 'JoomlaPack Backup-to-Email Gateway';
  918. //create a boundary string. It must be unique
  919. //so we use the MD5 algorithm to generate a random hash
  920. $random_hash1 = md5(date('r', time())).'a';
  921. $random_hash2 = md5(date('r', time())).'b';
  922. $random_hash3 = md5(date('r', time())).'c';
  923. //define the headers we want passed. Note that they are separated with \r\n
  924. $headers = "From: $to";
  925. //add boundary string and mime type specification
  926. $headers .= "\nContent-Type: multipart/mixed; boundary=".$random_hash1;
  927. //read the atachment file contents into a string,
  928. //encode it with MIME base64,
  929. //and split it into smaller chunks
  930. $attachment = chunk_split(base64_encode(file_get_contents($filename)));
  931. //define the body of the message.
  932. $basename = basename($filename);
  933. $message = <<<ENDBODY
  934. --$random_hash1
  935. Content-Type: multipart/alternative; boundary=$random_hash2
  936. --$random_hash2
  937. Content-Type: text/plain; charset=ISO-8859-1
  938. Content-Transfer-Encoding: 7bit
  939. JoomlaPack has taken a new backup.
  940. Please find attached the backup archive.
  941. --$random_hash2
  942. Content-Type: text/html; charset=ISO-8859-1
  943. Content-Transfer-Encoding: 7bit
  944. <h2>JoomlaPack has taken a new backup</h2>
  945. <p>Please find attached the backup archive.</p>
  946. --$random_hash2--
  947. --$random_hash1
  948. Content-Type: application/zip; name="$basename"
  949. Content-Transfer-Encoding: base64
  950. Content-Disposition: attachment; filename="$basename"
  951. $attachment
  952. --$random_hash1--
  953. ENDBODY;
  954. //send the email
  955. return @mail( $to, $subject, $message, $headers );
  956. }
  957. // ============================================================================
  958. // Main Loop
  959. // ============================================================================
  960. global $config, $archive;
  961. @set_time_limit(0);
  962. // ============================================================================
  963. // Startup
  964. // ============================================================================
  965. echo "JoomlaPack JSON CRON Helper\n";
  966. if(!isset($config))
  967. {
  968. echo "You can't call this script directly, or configuration is missing\n";
  969. die();
  970. }
  971. // Get the output Directory
  972. $url = getURL('getdirectory');
  973. $result = getServerResponse($url);
  974. if($result === false)
  975. {
  976. echo "Could not get output directory\n";
  977. die();
  978. }
  979. $directory = decodeJSON($result);
  980. // ============================================================================
  981. // Site backup
  982. // ============================================================================
  983. $flag = true;
  984. $count = 0;
  985. if($config['verbose']) echo "Starting backup\n";
  986. $result = doBackup('start');
  987. while( ($result !== 0) && $flag )
  988. {
  989. $result = doBackup('step');
  990. if($result == 2) $flag = false;
  991. }
  992. if($result === 0)
  993. {
  994. echo "Last operation has failed.\n";
  995. die();
  996. }
  997. else
  998. {
  999. echo "Done backing up in $count steps.\n";
  1000. }
  1001. if( ($archive === false) || empty($archive) )
  1002. {
  1003. echo "Error getting backup filename!\n";
  1004. die();
  1005. }
  1006. // ============================================================================
  1007. // Handle FTP options
  1008. // ============================================================================
  1009. switch(strtolower($config['postop']))
  1010. {
  1011. case 'upload':
  1012. echo "Uploading backup file to remote server\n";
  1013. if(!upload($directory.'/'.$archive)) die();
  1014. echo "Upload finished successfully\n";
  1015. break;
  1016. case 'email':
  1017. echo "Sending the backup archive by email\n";
  1018. if(!send_by_email($directory.'/'.$archive)) die("Oops! Email could not be sent\n");
  1019. echo "Email completed successfully\n";
  1020. break;
  1021. default:
  1022. break;
  1023. }
  1024. echo "JoomlaPack JSON CRON Helper has finished successfully!\n";