PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/application/libraries/FirePHPCore/FirePHP.class.php

https://github.com/ozhehkovski/Open-Ad-Server
PHP | 1527 lines | 818 code | 182 blank | 527 comment | 161 complexity | 7204170da9f959327d1cdf24f8bc6183 MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /**
  3. * *** BEGIN LICENSE BLOCK *****
  4. *
  5. * This file is part of FirePHP (http://www.firephp.org/).
  6. *
  7. * Software License Agreement (New BSD License)
  8. *
  9. * Copyright (c) 2006-2009, Christoph Dorn
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or without modification,
  13. * are permitted provided that the following conditions are met:
  14. *
  15. * this list of conditions and the following disclaimer.
  16. *
  17. * * Redistributions in binary form must reproduce the above copyright notice,
  18. * this list of conditions and the following disclaimer in the documentation
  19. * and/or other materials provided with the distribution.
  20. *
  21. * * Neither the name of Christoph Dorn nor the names of its
  22. * contributors may be used to endorse or promote products derived from this
  23. * software without specific prior written permission.
  24. *
  25. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  26. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  27. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  28. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  29. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  30. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  31. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  32. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  33. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  34. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  35. *
  36. * ***** END LICENSE BLOCK *****
  37. *
  38. * @copyright Copyright (C) 2007-2009 Christoph Dorn
  39. * @author Christoph Dorn <christoph@christophdorn.com>
  40. * @license http://www.opensource.org/licenses/bsd-license.php
  41. * @package FirePHP
  42. */
  43. /**
  44. * Sends the given data to the FirePHP Firefox Extension.
  45. * The data can be displayed in the Firebug Console or in the
  46. * "Server" request tab.
  47. *
  48. * For more information see: http://www.firephp.org/
  49. *
  50. * @copyright Copyright (C) 2007-2009 Christoph Dorn
  51. * @author Christoph Dorn <christoph@christophdorn.com>
  52. * @license http://www.opensource.org/licenses/bsd-license.php
  53. * @package FirePHP
  54. */
  55. class FirePHP {
  56. /**
  57. * FirePHP version
  58. *
  59. * @var string
  60. */
  61. const VERSION = '0.3';
  62. /**
  63. * Firebug LOG level
  64. *
  65. * Logs a message to firebug console.
  66. *
  67. * @var string
  68. */
  69. const LOG = 'LOG';
  70. /**
  71. * Firebug INFO level
  72. *
  73. * Logs a message to firebug console and displays an info icon before the message.
  74. *
  75. * @var string
  76. */
  77. const INFO = 'INFO';
  78. /**
  79. * Firebug WARN level
  80. *
  81. * Logs a message to firebug console, displays an warning icon before the message and colors the line turquoise.
  82. *
  83. * @var string
  84. */
  85. const WARN = 'WARN';
  86. /**
  87. * Firebug ERROR level
  88. *
  89. * Logs a message to firebug console, displays an error icon before the message and colors the line yellow. Also increments the firebug error count.
  90. *
  91. * @var string
  92. */
  93. const ERROR = 'ERROR';
  94. /**
  95. * Dumps a variable to firebug's server panel
  96. *
  97. * @var string
  98. */
  99. const DUMP = 'DUMP';
  100. /**
  101. * Displays a stack trace in firebug console
  102. *
  103. * @var string
  104. */
  105. const TRACE = 'TRACE';
  106. /**
  107. * Displays an exception in firebug console
  108. *
  109. * Increments the firebug error count.
  110. *
  111. * @var string
  112. */
  113. const EXCEPTION = 'EXCEPTION';
  114. /**
  115. * Displays an table in firebug console
  116. *
  117. * @var string
  118. */
  119. const TABLE = 'TABLE';
  120. /**
  121. * Starts a group in firebug console
  122. *
  123. * @var string
  124. */
  125. const GROUP_START = 'GROUP_START';
  126. /**
  127. * Ends a group in firebug console
  128. *
  129. * @var string
  130. */
  131. const GROUP_END = 'GROUP_END';
  132. /**
  133. * Singleton instance of FirePHP
  134. *
  135. * @var FirePHP
  136. */
  137. protected static $instance = null;
  138. /**
  139. * Flag whether we are logging from within the exception handler
  140. *
  141. * @var boolean
  142. */
  143. protected $inExceptionHandler = false;
  144. /**
  145. * Flag whether to throw PHP errors that have been converted to ErrorExceptions
  146. *
  147. * @var boolean
  148. */
  149. protected $throwErrorExceptions = true;
  150. /**
  151. * Flag whether to convert PHP assertion errors to Exceptions
  152. *
  153. * @var boolean
  154. */
  155. protected $convertAssertionErrorsToExceptions = true;
  156. /**
  157. * Flag whether to throw PHP assertion errors that have been converted to Exceptions
  158. *
  159. * @var boolean
  160. */
  161. protected $throwAssertionExceptions = false;
  162. /**
  163. * Wildfire protocol message index
  164. *
  165. * @var int
  166. */
  167. protected $messageIndex = 1;
  168. /**
  169. * Options for the library
  170. *
  171. * @var array
  172. */
  173. protected $options = array('maxObjectDepth' => 10,
  174. 'maxArrayDepth' => 20,
  175. 'useNativeJsonEncode' => true,
  176. 'includeLineNumbers' => true);
  177. /**
  178. * Filters used to exclude object members when encoding
  179. *
  180. * @var array
  181. */
  182. protected $objectFilters = array();
  183. /**
  184. * A stack of objects used to detect recursion during object encoding
  185. *
  186. * @var object
  187. */
  188. protected $objectStack = array();
  189. /**
  190. * Flag to enable/disable logging
  191. *
  192. * @var boolean
  193. */
  194. protected $enabled = true;
  195. /**
  196. * The object constructor
  197. */
  198. function __construct() {
  199. }
  200. /**
  201. * When the object gets serialized only include specific object members.
  202. *
  203. * @return array
  204. */
  205. public function __sleep() {
  206. return array('options','objectFilters','enabled');
  207. }
  208. /**
  209. * Gets singleton instance of FirePHP
  210. *
  211. * @param boolean $AutoCreate
  212. * @return FirePHP
  213. */
  214. public static function getInstance($AutoCreate=false) {
  215. if($AutoCreate===true && !self::$instance) {
  216. self::init();
  217. }
  218. return self::$instance;
  219. }
  220. /**
  221. * Creates FirePHP object and stores it for singleton access
  222. *
  223. * @return FirePHP
  224. */
  225. public static function init() {
  226. return self::$instance = new self();
  227. }
  228. /**
  229. * Enable and disable logging to Firebug
  230. *
  231. * @param boolean $Enabled TRUE to enable, FALSE to disable
  232. * @return void
  233. */
  234. public function setEnabled($Enabled) {
  235. $this->enabled = $Enabled;
  236. }
  237. /**
  238. * Check if logging is enabled
  239. *
  240. * @return boolean TRUE if enabled
  241. */
  242. public function getEnabled() {
  243. return $this->enabled;
  244. }
  245. /**
  246. * Specify a filter to be used when encoding an object
  247. *
  248. * Filters are used to exclude object members.
  249. *
  250. * @param string $Class The class name of the object
  251. * @param array $Filter An array of members to exclude
  252. * @return void
  253. */
  254. public function setObjectFilter($Class, $Filter) {
  255. $this->objectFilters[$Class] = $Filter;
  256. }
  257. /**
  258. * Set some options for the library
  259. *
  260. * Options:
  261. * - maxObjectDepth: The maximum depth to traverse objects (default: 10)
  262. * - maxArrayDepth: The maximum depth to traverse arrays (default: 20)
  263. * - useNativeJsonEncode: If true will use json_encode() (default: true)
  264. * - includeLineNumbers: If true will include line numbers and filenames (default: true)
  265. *
  266. * @param array $Options The options to be set
  267. * @return void
  268. */
  269. public function setOptions($Options) {
  270. $this->options = array_merge($this->options,$Options);
  271. }
  272. /**
  273. * Get options from the library
  274. *
  275. * @return array The currently set options
  276. */
  277. public function getOptions() {
  278. return $this->options;
  279. }
  280. /**
  281. * Register FirePHP as your error handler
  282. *
  283. * Will throw exceptions for each php error.
  284. *
  285. * @return mixed Returns a string containing the previously defined error handler (if any)
  286. */
  287. public function registerErrorHandler($throwErrorExceptions=true)
  288. {
  289. //NOTE: The following errors will not be caught by this error handler:
  290. // E_ERROR, E_PARSE, E_CORE_ERROR,
  291. // E_CORE_WARNING, E_COMPILE_ERROR,
  292. // E_COMPILE_WARNING, E_STRICT
  293. $this->throwErrorExceptions = $throwErrorExceptions;
  294. return set_error_handler(array($this,'errorHandler'));
  295. }
  296. /**
  297. * FirePHP's error handler
  298. *
  299. * Throws exception for each php error that will occur.
  300. *
  301. * @param int $errno
  302. * @param string $errstr
  303. * @param string $errfile
  304. * @param int $errline
  305. * @param array $errcontext
  306. */
  307. public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
  308. {
  309. // Don't throw exception if error reporting is switched off
  310. if (error_reporting() == 0) {
  311. return;
  312. }
  313. // Only throw exceptions for errors we are asking for
  314. if (error_reporting() & $errno) {
  315. $exception = new ErrorException($errstr, 0, $errno, $errfile, $errline);
  316. if($this->throwErrorExceptions) {
  317. throw $exception;
  318. } else {
  319. $this->fb($exception);
  320. }
  321. }
  322. }
  323. /**
  324. * Register FirePHP as your exception handler
  325. *
  326. * @return mixed Returns the name of the previously defined exception handler,
  327. * or NULL on error.
  328. * If no previous handler was defined, NULL is also returned.
  329. */
  330. public function registerExceptionHandler()
  331. {
  332. return set_exception_handler(array($this,'exceptionHandler'));
  333. }
  334. /**
  335. * FirePHP's exception handler
  336. *
  337. * Logs all exceptions to your firebug console and then stops the script.
  338. *
  339. * @param Exception $Exception
  340. * @throws Exception
  341. */
  342. function exceptionHandler($Exception) {
  343. $this->inExceptionHandler = true;
  344. header('HTTP/1.1 500 Internal Server Error');
  345. $this->fb($Exception);
  346. $this->inExceptionHandler = false;
  347. }
  348. /**
  349. * Register FirePHP driver as your assert callback
  350. *
  351. * @param boolean $convertAssertionErrorsToExceptions
  352. * @param boolean $throwAssertionExceptions
  353. * @return mixed Returns the original setting or FALSE on errors
  354. */
  355. public function registerAssertionHandler($convertAssertionErrorsToExceptions=true, $throwAssertionExceptions=false)
  356. {
  357. $this->convertAssertionErrorsToExceptions = $convertAssertionErrorsToExceptions;
  358. $this->throwAssertionExceptions = $throwAssertionExceptions;
  359. if($throwAssertionExceptions && !$convertAssertionErrorsToExceptions) {
  360. throw $this->newException('Cannot throw assertion exceptions as assertion errors are not being converted to exceptions!');
  361. }
  362. return assert_options(ASSERT_CALLBACK, array($this, 'assertionHandler'));
  363. }
  364. /**
  365. * FirePHP's assertion handler
  366. *
  367. * Logs all assertions to your firebug console and then stops the script.
  368. *
  369. * @param string $file File source of assertion
  370. * @param int $line Line source of assertion
  371. * @param mixed $code Assertion code
  372. */
  373. public function assertionHandler($file, $line, $code)
  374. {
  375. if($this->convertAssertionErrorsToExceptions) {
  376. $exception = new ErrorException('Assertion Failed - Code[ '.$code.' ]', 0, null, $file, $line);
  377. if($this->throwAssertionExceptions) {
  378. throw $exception;
  379. } else {
  380. $this->fb($exception);
  381. }
  382. } else {
  383. $this->fb($code, 'Assertion Failed', FirePHP::ERROR, array('File'=>$file,'Line'=>$line));
  384. }
  385. }
  386. /**
  387. * Set custom processor url for FirePHP
  388. *
  389. * @param string $URL
  390. */
  391. public function setProcessorUrl($URL)
  392. {
  393. $this->setHeader('X-FirePHP-ProcessorURL', $URL);
  394. }
  395. /**
  396. * Set custom renderer url for FirePHP
  397. *
  398. * @param string $URL
  399. */
  400. public function setRendererUrl($URL)
  401. {
  402. $this->setHeader('X-FirePHP-RendererURL', $URL);
  403. }
  404. /**
  405. * Start a group for following messages.
  406. *
  407. * Options:
  408. * Collapsed: [true|false]
  409. * Color: [#RRGGBB|ColorName]
  410. *
  411. * @param string $Name
  412. * @param array $Options OPTIONAL Instructions on how to log the group
  413. * @return true
  414. * @throws Exception
  415. */
  416. public function group($Name, $Options=null) {
  417. if(!$Name) {
  418. throw $this->newException('You must specify a label for the group!');
  419. }
  420. if($Options) {
  421. if(!is_array($Options)) {
  422. throw $this->newException('Options must be defined as an array!');
  423. }
  424. if(array_key_exists('Collapsed', $Options)) {
  425. $Options['Collapsed'] = ($Options['Collapsed'])?'true':'false';
  426. }
  427. }
  428. return $this->fb(null, $Name, FirePHP::GROUP_START, $Options);
  429. }
  430. /**
  431. * Ends a group you have started before
  432. *
  433. * @return true
  434. * @throws Exception
  435. */
  436. public function groupEnd() {
  437. return $this->fb(null, null, FirePHP::GROUP_END);
  438. }
  439. /**
  440. * Log object with label to firebug console
  441. *
  442. * @see FirePHP::LOG
  443. * @param mixes $Object
  444. * @param string $Label
  445. * @return true
  446. * @throws Exception
  447. */
  448. public function log($Object, $Label=null) {
  449. return $this->fb($Object, $Label, FirePHP::LOG);
  450. }
  451. /**
  452. * Log object with label to firebug console
  453. *
  454. * @see FirePHP::INFO
  455. * @param mixes $Object
  456. * @param string $Label
  457. * @return true
  458. * @throws Exception
  459. */
  460. public function info($Object, $Label=null) {
  461. return $this->fb($Object, $Label, FirePHP::INFO);
  462. }
  463. /**
  464. * Log object with label to firebug console
  465. *
  466. * @see FirePHP::WARN
  467. * @param mixes $Object
  468. * @param string $Label
  469. * @return true
  470. * @throws Exception
  471. */
  472. public function warn($Object, $Label=null) {
  473. return $this->fb($Object, $Label, FirePHP::WARN);
  474. }
  475. /**
  476. * Log object with label to firebug console
  477. *
  478. * @see FirePHP::ERROR
  479. * @param mixes $Object
  480. * @param string $Label
  481. * @return true
  482. * @throws Exception
  483. */
  484. public function error($Object, $Label=null) {
  485. return $this->fb($Object, $Label, FirePHP::ERROR);
  486. }
  487. /**
  488. * Dumps key and variable to firebug server panel
  489. *
  490. * @see FirePHP::DUMP
  491. * @param string $Key
  492. * @param mixed $Variable
  493. * @return true
  494. * @throws Exception
  495. */
  496. public function dump($Key, $Variable) {
  497. return $this->fb($Variable, $Key, FirePHP::DUMP);
  498. }
  499. /**
  500. * Log a trace in the firebug console
  501. *
  502. * @see FirePHP::TRACE
  503. * @param string $Label
  504. * @return true
  505. * @throws Exception
  506. */
  507. public function trace($Label) {
  508. return $this->fb($Label, FirePHP::TRACE);
  509. }
  510. /**
  511. * Log a table in the firebug console
  512. *
  513. * @see FirePHP::TABLE
  514. * @param string $Label
  515. * @param string $Table
  516. * @return true
  517. * @throws Exception
  518. */
  519. public function table($Label, $Table) {
  520. return $this->fb($Table, $Label, FirePHP::TABLE);
  521. }
  522. /**
  523. * Check if FirePHP is installed on client
  524. *
  525. * @return boolean
  526. */
  527. public function detectClientExtension() {
  528. /* Check if FirePHP is installed on client */
  529. if(!@preg_match_all('/\sFirePHP\/([\.|\d]*)\s?/si',$this->getUserAgent(),$m) ||
  530. !version_compare($m[1][0],'0.0.6','>=')) {
  531. return false;
  532. }
  533. return true;
  534. }
  535. /**
  536. * Log varible to Firebug
  537. *
  538. * @see http://www.firephp.org/Wiki/Reference/Fb
  539. * @param mixed $Object The variable to be logged
  540. * @return true Return TRUE if message was added to headers, FALSE otherwise
  541. * @throws Exception
  542. */
  543. public function fb($Object) {
  544. if(!$this->enabled) {
  545. return false;
  546. }
  547. if (headers_sent($filename, $linenum)) {
  548. // If we are logging from within the exception handler we cannot throw another exception
  549. if($this->inExceptionHandler) {
  550. // Simply echo the error out to the page
  551. echo '<div style="border: 2px solid red; font-family: Arial; font-size: 12px; background-color: lightgray; padding: 5px;"><span style="color: red; font-weight: bold;">FirePHP ERROR:</span> Headers already sent in <b>'.$filename.'</b> on line <b>'.$linenum.'</b>. Cannot send log data to FirePHP. You must have Output Buffering enabled via ob_start() or output_buffering ini directive.</div>';
  552. } else {
  553. throw $this->newException('Headers already sent in '.$filename.' on line '.$linenum.'. Cannot send log data to FirePHP. You must have Output Buffering enabled via ob_start() or output_buffering ini directive.');
  554. }
  555. }
  556. $Type = null;
  557. $Label = null;
  558. $Options = array();
  559. if(func_num_args()==1) {
  560. } else
  561. if(func_num_args()==2) {
  562. switch(func_get_arg(1)) {
  563. case self::LOG:
  564. case self::INFO:
  565. case self::WARN:
  566. case self::ERROR:
  567. case self::DUMP:
  568. case self::TRACE:
  569. case self::EXCEPTION:
  570. case self::TABLE:
  571. case self::GROUP_START:
  572. case self::GROUP_END:
  573. $Type = func_get_arg(1);
  574. break;
  575. default:
  576. $Label = func_get_arg(1);
  577. break;
  578. }
  579. } else
  580. if(func_num_args()==3) {
  581. $Type = func_get_arg(2);
  582. $Label = func_get_arg(1);
  583. } else
  584. if(func_num_args()==4) {
  585. $Type = func_get_arg(2);
  586. $Label = func_get_arg(1);
  587. $Options = func_get_arg(3);
  588. } else {
  589. throw $this->newException('Wrong number of arguments to fb() function!');
  590. }
  591. if(!$this->detectClientExtension()) {
  592. return false;
  593. }
  594. $meta = array();
  595. $skipFinalObjectEncode = false;
  596. if($Object instanceof Exception) {
  597. $meta['file'] = $this->_escapeTraceFile($Object->getFile());
  598. $meta['line'] = $Object->getLine();
  599. $trace = $Object->getTrace();
  600. if($Object instanceof ErrorException
  601. && isset($trace[0]['function'])
  602. && $trace[0]['function']=='errorHandler'
  603. && isset($trace[0]['class'])
  604. && $trace[0]['class']=='FirePHP') {
  605. $severity = false;
  606. switch($Object->getSeverity()) {
  607. case E_WARNING: $severity = 'E_WARNING'; break;
  608. case E_NOTICE: $severity = 'E_NOTICE'; break;
  609. case E_USER_ERROR: $severity = 'E_USER_ERROR'; break;
  610. case E_USER_WARNING: $severity = 'E_USER_WARNING'; break;
  611. case E_USER_NOTICE: $severity = 'E_USER_NOTICE'; break;
  612. case E_STRICT: $severity = 'E_STRICT'; break;
  613. case E_RECOVERABLE_ERROR: $severity = 'E_RECOVERABLE_ERROR'; break;
  614. case E_DEPRECATED: $severity = 'E_DEPRECATED'; break;
  615. case E_USER_DEPRECATED: $severity = 'E_USER_DEPRECATED'; break;
  616. }
  617. $Object = array('Class'=>get_class($Object),
  618. 'Message'=>$severity.': '.$Object->getMessage(),
  619. 'File'=>$this->_escapeTraceFile($Object->getFile()),
  620. 'Line'=>$Object->getLine(),
  621. 'Type'=>'trigger',
  622. 'Trace'=>$this->_escapeTrace(array_splice($trace,2)));
  623. $skipFinalObjectEncode = true;
  624. } else {
  625. $Object = array('Class'=>get_class($Object),
  626. 'Message'=>$Object->getMessage(),
  627. 'File'=>$this->_escapeTraceFile($Object->getFile()),
  628. 'Line'=>$Object->getLine(),
  629. 'Type'=>'throw',
  630. 'Trace'=>$this->_escapeTrace($trace));
  631. $skipFinalObjectEncode = true;
  632. }
  633. $Type = self::EXCEPTION;
  634. } else
  635. if($Type==self::TRACE) {
  636. $trace = debug_backtrace();
  637. if(!$trace) return false;
  638. for( $i=0 ; $i<sizeof($trace) ; $i++ ) {
  639. if(isset($trace[$i]['class'])
  640. && isset($trace[$i]['file'])
  641. && ($trace[$i]['class']=='FirePHP'
  642. || $trace[$i]['class']=='FB')
  643. && (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
  644. || substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
  645. /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
  646. } else
  647. if(isset($trace[$i]['class'])
  648. && isset($trace[$i+1]['file'])
  649. && $trace[$i]['class']=='FirePHP'
  650. && substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
  651. /* Skip fb() */
  652. } else
  653. if($trace[$i]['function']=='fb'
  654. || $trace[$i]['function']=='trace'
  655. || $trace[$i]['function']=='send') {
  656. $Object = array('Class'=>isset($trace[$i]['class'])?$trace[$i]['class']:'',
  657. 'Type'=>isset($trace[$i]['type'])?$trace[$i]['type']:'',
  658. 'Function'=>isset($trace[$i]['function'])?$trace[$i]['function']:'',
  659. 'Message'=>$trace[$i]['args'][0],
  660. 'File'=>isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'',
  661. 'Line'=>isset($trace[$i]['line'])?$trace[$i]['line']:'',
  662. 'Args'=>isset($trace[$i]['args'])?$this->encodeObject($trace[$i]['args']):'',
  663. 'Trace'=>$this->_escapeTrace(array_splice($trace,$i+1)));
  664. $skipFinalObjectEncode = true;
  665. $meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
  666. $meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
  667. break;
  668. }
  669. }
  670. } else
  671. if($Type==self::TABLE) {
  672. if(isset($Object[0]) && is_string($Object[0])) {
  673. $Object[1] = $this->encodeTable($Object[1]);
  674. } else {
  675. $Object = $this->encodeTable($Object);
  676. }
  677. $skipFinalObjectEncode = true;
  678. } else
  679. if($Type==self::GROUP_START) {
  680. if(!$Label) {
  681. throw $this->newException('You must specify a label for the group!');
  682. }
  683. } else {
  684. if($Type===null) {
  685. $Type = self::LOG;
  686. }
  687. }
  688. if($this->options['includeLineNumbers']) {
  689. if(!isset($meta['file']) || !isset($meta['line'])) {
  690. $trace = debug_backtrace();
  691. for( $i=0 ; $trace && $i<sizeof($trace) ; $i++ ) {
  692. if(isset($trace[$i]['class'])
  693. && isset($trace[$i]['file'])
  694. && ($trace[$i]['class']=='FirePHP'
  695. || $trace[$i]['class']=='FB')
  696. && (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
  697. || substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
  698. /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
  699. } else
  700. if(isset($trace[$i]['class'])
  701. && isset($trace[$i+1]['file'])
  702. && $trace[$i]['class']=='FirePHP'
  703. && substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
  704. /* Skip fb() */
  705. } else
  706. if(isset($trace[$i]['file'])
  707. && substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php') {
  708. /* Skip FB::fb() */
  709. } else {
  710. $meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
  711. $meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
  712. break;
  713. }
  714. }
  715. }
  716. } else {
  717. unset($meta['file']);
  718. unset($meta['line']);
  719. }
  720. $this->setHeader('X-Wf-Protocol-1','http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
  721. $this->setHeader('X-Wf-1-Plugin-1','http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/'.self::VERSION);
  722. $structure_index = 1;
  723. if($Type==self::DUMP) {
  724. $structure_index = 2;
  725. $this->setHeader('X-Wf-1-Structure-2','http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1');
  726. } else {
  727. $this->setHeader('X-Wf-1-Structure-1','http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1');
  728. }
  729. if($Type==self::DUMP) {
  730. $msg = '{"'.$Label.'":'.$this->jsonEncode($Object, $skipFinalObjectEncode).'}';
  731. } else {
  732. $msg_meta = $Options;
  733. $msg_meta['Type'] = $Type;
  734. if($Label!==null) {
  735. $msg_meta['Label'] = $Label;
  736. }
  737. if(isset($meta['file']) && !isset($msg_meta['File'])) {
  738. $msg_meta['File'] = $meta['file'];
  739. }
  740. if(isset($meta['line']) && !isset($msg_meta['Line'])) {
  741. $msg_meta['Line'] = $meta['line'];
  742. }
  743. $msg = '['.$this->jsonEncode($msg_meta).','.$this->jsonEncode($Object, $skipFinalObjectEncode).']';
  744. }
  745. $parts = explode("\n",chunk_split($msg, 5000, "\n"));
  746. for( $i=0 ; $i<count($parts) ; $i++) {
  747. $part = $parts[$i];
  748. if ($part) {
  749. if(count($parts)>2) {
  750. // Message needs to be split into multiple parts
  751. $this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
  752. (($i==0)?strlen($msg):'')
  753. . '|' . $part . '|'
  754. . (($i<count($parts)-2)?'\\':''));
  755. } else {
  756. $this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
  757. strlen($part) . '|' . $part . '|');
  758. }
  759. $this->messageIndex++;
  760. if ($this->messageIndex > 99999) {
  761. throw $this->newException('Maximum number (99,999) of messages reached!');
  762. }
  763. }
  764. }
  765. $this->setHeader('X-Wf-1-Index',$this->messageIndex-1);
  766. return true;
  767. }
  768. /**
  769. * Standardizes path for windows systems.
  770. *
  771. * @param string $Path
  772. * @return string
  773. */
  774. protected function _standardizePath($Path) {
  775. return preg_replace('/\\\\+/','/',$Path);
  776. }
  777. /**
  778. * Escape trace path for windows systems
  779. *
  780. * @param array $Trace
  781. * @return array
  782. */
  783. protected function _escapeTrace($Trace) {
  784. if(!$Trace) return $Trace;
  785. for( $i=0 ; $i<sizeof($Trace) ; $i++ ) {
  786. if(isset($Trace[$i]['file'])) {
  787. $Trace[$i]['file'] = $this->_escapeTraceFile($Trace[$i]['file']);
  788. }
  789. if(isset($Trace[$i]['args'])) {
  790. $Trace[$i]['args'] = $this->encodeObject($Trace[$i]['args']);
  791. }
  792. }
  793. return $Trace;
  794. }
  795. /**
  796. * Escape file information of trace for windows systems
  797. *
  798. * @param string $File
  799. * @return string
  800. */
  801. protected function _escapeTraceFile($File) {
  802. /* Check if we have a windows filepath */
  803. if(strpos($File,'\\')) {
  804. /* First strip down to single \ */
  805. $file = preg_replace('/\\\\+/','\\',$File);
  806. return $file;
  807. }
  808. return $File;
  809. }
  810. /**
  811. * Send header
  812. *
  813. * @param string $Name
  814. * @param string_type $Value
  815. */
  816. protected function setHeader($Name, $Value) {
  817. return header($Name.': '.$Value);
  818. }
  819. /**
  820. * Get user agent
  821. *
  822. * @return string|false
  823. */
  824. protected function getUserAgent() {
  825. if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
  826. return $_SERVER['HTTP_USER_AGENT'];
  827. }
  828. /**
  829. * Returns a new exception
  830. *
  831. * @param string $Message
  832. * @return Exception
  833. */
  834. protected function newException($Message) {
  835. return new Exception($Message);
  836. }
  837. /**
  838. * Encode an object into a JSON string
  839. *
  840. * Uses PHP's jeson_encode() if available
  841. *
  842. * @param object $Object The object to be encoded
  843. * @return string The JSON string
  844. */
  845. public function jsonEncode($Object, $skipObjectEncode=false)
  846. {
  847. if(!$skipObjectEncode) {
  848. $Object = $this->encodeObject($Object);
  849. }
  850. if(function_exists('json_encode')
  851. && $this->options['useNativeJsonEncode']!=false) {
  852. return json_encode($Object);
  853. } else {
  854. return $this->json_encode($Object);
  855. }
  856. }
  857. /**
  858. * Encodes a table by encoding each row and column with encodeObject()
  859. *
  860. * @param array $Table The table to be encoded
  861. * @return array
  862. */
  863. protected function encodeTable($Table) {
  864. if(!$Table) return $Table;
  865. $new_table = array();
  866. foreach($Table as $row) {
  867. if(is_array($row)) {
  868. $new_row = array();
  869. foreach($row as $item) {
  870. $new_row[] = $this->encodeObject($item);
  871. }
  872. $new_table[] = $new_row;
  873. }
  874. }
  875. return $new_table;
  876. }
  877. /**
  878. * Encodes an object including members with
  879. * protected and private visibility
  880. *
  881. * @param Object $Object The object to be encoded
  882. * @param int $Depth The current traversal depth
  883. * @return array All members of the object
  884. */
  885. protected function encodeObject($Object, $ObjectDepth = 1, $ArrayDepth = 1)
  886. {
  887. $return = array();
  888. if (is_resource($Object)) {
  889. return '** '.(string)$Object.' **';
  890. } else
  891. if (is_object($Object)) {
  892. if ($ObjectDepth > $this->options['maxObjectDepth']) {
  893. return '** Max Object Depth ('.$this->options['maxObjectDepth'].') **';
  894. }
  895. foreach ($this->objectStack as $refVal) {
  896. if ($refVal === $Object) {
  897. return '** Recursion ('.get_class($Object).') **';
  898. }
  899. }
  900. array_push($this->objectStack, $Object);
  901. $return['__className'] = $class = get_class($Object);
  902. $reflectionClass = new ReflectionClass($class);
  903. $properties = array();
  904. foreach( $reflectionClass->getProperties() as $property) {
  905. $properties[$property->getName()] = $property;
  906. }
  907. $members = (array)$Object;
  908. foreach( $properties as $raw_name => $property ) {
  909. $name = $raw_name;
  910. if($property->isStatic()) {
  911. $name = 'static:'.$name;
  912. }
  913. if($property->isPublic()) {
  914. $name = 'public:'.$name;
  915. } else
  916. if($property->isPrivate()) {
  917. $name = 'private:'.$name;
  918. $raw_name = "\0".$class."\0".$raw_name;
  919. } else
  920. if($property->isProtected()) {
  921. $name = 'protected:'.$name;
  922. $raw_name = "\0".'*'."\0".$raw_name;
  923. }
  924. if(!(isset($this->objectFilters[$class])
  925. && is_array($this->objectFilters[$class])
  926. && in_array($raw_name,$this->objectFilters[$class]))) {
  927. if(array_key_exists($raw_name,$members)
  928. && !$property->isStatic()) {
  929. $return[$name] = $this->encodeObject($members[$raw_name], $ObjectDepth + 1, 1);
  930. } else {
  931. if(method_exists($property,'setAccessible')) {
  932. $property->setAccessible(true);
  933. $return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1);
  934. } else
  935. if($property->isPublic()) {
  936. $return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1);
  937. } else {
  938. $return[$name] = '** Need PHP 5.3 to get value **';
  939. }
  940. }
  941. } else {
  942. $return[$name] = '** Excluded by Filter **';
  943. }
  944. }
  945. // Include all members that are not defined in the class
  946. // but exist in the object
  947. foreach( $members as $raw_name => $value ) {
  948. $name = $raw_name;
  949. if ($name{0} == "\0") {
  950. $parts = explode("\0", $name);
  951. $name = $parts[2];
  952. }
  953. if(!isset($properties[$name])) {
  954. $name = 'undeclared:'.$name;
  955. if(!(isset($this->objectFilters[$class])
  956. && is_array($this->objectFilters[$class])
  957. && in_array($raw_name,$this->objectFilters[$class]))) {
  958. $return[$name] = $this->encodeObject($value, $ObjectDepth + 1, 1);
  959. } else {
  960. $return[$name] = '** Excluded by Filter **';
  961. }
  962. }
  963. }
  964. array_pop($this->objectStack);
  965. } elseif (is_array($Object)) {
  966. if ($ArrayDepth > $this->options['maxArrayDepth']) {
  967. return '** Max Array Depth ('.$this->options['maxArrayDepth'].') **';
  968. }
  969. foreach ($Object as $key => $val) {
  970. // Encoding the $GLOBALS PHP array causes an infinite loop
  971. // if the recursion is not reset here as it contains
  972. // a reference to itself. This is the only way I have come up
  973. // with to stop infinite recursion in this case.
  974. if($key=='GLOBALS'
  975. && is_array($val)
  976. && array_key_exists('GLOBALS',$val)) {
  977. $val['GLOBALS'] = '** Recursion (GLOBALS) **';
  978. }
  979. $return[$key] = $this->encodeObject($val, 1, $ArrayDepth + 1);
  980. }
  981. } else {
  982. if(self::is_utf8($Object)) {
  983. return $Object;
  984. } else {
  985. return utf8_encode($Object);
  986. }
  987. }
  988. return $return;
  989. }
  990. /**
  991. * Returns true if $string is valid UTF-8 and false otherwise.
  992. *
  993. * @param mixed $str String to be tested
  994. * @return boolean
  995. */
  996. protected static function is_utf8($str) {
  997. $c=0; $b=0;
  998. $bits=0;
  999. $len=strlen($str);
  1000. for($i=0; $i<$len; $i++){
  1001. $c=ord($str[$i]);
  1002. if($c > 128){
  1003. if(($c >= 254)) return false;
  1004. elseif($c >= 252) $bits=6;
  1005. elseif($c >= 248) $bits=5;
  1006. elseif($c >= 240) $bits=4;
  1007. elseif($c >= 224) $bits=3;
  1008. elseif($c >= 192) $bits=2;
  1009. else return false;
  1010. if(($i+$bits) > $len) return false;
  1011. while($bits > 1){
  1012. $i++;
  1013. $b=ord($str[$i]);
  1014. if($b < 128 || $b > 191) return false;
  1015. $bits--;
  1016. }
  1017. }
  1018. }
  1019. return true;
  1020. }
  1021. /**
  1022. * Converts to and from JSON format.
  1023. *
  1024. * JSON (JavaScript Object Notation) is a lightweight data-interchange
  1025. * format. It is easy for humans to read and write. It is easy for machines
  1026. * to parse and generate. It is based on a subset of the JavaScript
  1027. * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
  1028. * This feature can also be found in Python. JSON is a text format that is
  1029. * completely language independent but uses conventions that are familiar
  1030. * to programmers of the C-family of languages, including C, C++, C#, Java,
  1031. * JavaScript, Perl, TCL, and many others. These properties make JSON an
  1032. * ideal data-interchange language.
  1033. *
  1034. * This package provides a simple encoder and decoder for JSON notation. It
  1035. * is intended for use with client-side Javascript applications that make
  1036. * use of HTTPRequest to perform server communication functions - data can
  1037. * be encoded into JSON notation for use in a client-side javascript, or
  1038. * decoded from incoming Javascript requests. JSON format is native to
  1039. * Javascript, and can be directly eval()'ed with no further parsing
  1040. * overhead
  1041. *
  1042. * All strings should be in ASCII or UTF-8 format!
  1043. *
  1044. * LICENSE: Redistribution and use in source and binary forms, with or
  1045. * without modification, are permitted provided that the following
  1046. * conditions are met: Redistributions of source code must retain the
  1047. * above copyright notice, this list of conditions and the following
  1048. * disclaimer. Redistributions in binary form must reproduce the above
  1049. * copyright notice, this list of conditions and the following disclaimer
  1050. * in the documentation and/or other materials provided with the
  1051. * distribution.
  1052. *
  1053. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  1054. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  1055. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
  1056. * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  1057. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  1058. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  1059. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  1060. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  1061. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  1062. * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  1063. * DAMAGE.
  1064. *
  1065. * @category
  1066. * @package Services_JSON
  1067. * @author Michal Migurski <mike-json@teczno.com>
  1068. * @author Matt Knapp <mdknapp[at]gmail[dot]com>
  1069. * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
  1070. * @author Christoph Dorn <christoph@christophdorn.com>
  1071. * @copyright 2005 Michal Migurski
  1072. * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
  1073. * @license http://www.opensource.org/licenses/bsd-license.php
  1074. * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
  1075. */
  1076. /**
  1077. * Keep a list of objects as we descend into the array so we can detect recursion.
  1078. */
  1079. private $json_objectStack = array();
  1080. /**
  1081. * convert a string from one UTF-8 char to one UTF-16 char
  1082. *
  1083. * Normally should be handled by mb_convert_encoding, but
  1084. * provides a slower PHP-only method for installations
  1085. * that lack the multibye string extension.
  1086. *
  1087. * @param string $utf8 UTF-8 character
  1088. * @return string UTF-16 character
  1089. * @access private
  1090. */
  1091. private function json_utf82utf16($utf8)
  1092. {
  1093. // oh please oh please oh please oh please oh please
  1094. if(function_exists('mb_convert_encoding')) {
  1095. return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
  1096. }
  1097. switch(strlen($utf8)) {
  1098. case 1:
  1099. // this case should never be reached, because we are in ASCII range
  1100. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1101. return $utf8;
  1102. case 2:
  1103. // return a UTF-16 character from a 2-byte UTF-8 char
  1104. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1105. return chr(0x07 & (ord($utf8{0}) >> 2))
  1106. . chr((0xC0 & (ord($utf8{0}) << 6))
  1107. | (0x3F & ord($utf8{1})));
  1108. case 3:
  1109. // return a UTF-16 character from a 3-byte UTF-8 char
  1110. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1111. return chr((0xF0 & (ord($utf8{0}) << 4))
  1112. | (0x0F & (ord($utf8{1}) >> 2)))
  1113. . chr((0xC0 & (ord($utf8{1}) << 6))
  1114. | (0x7F & ord($utf8{2})));
  1115. }
  1116. // ignoring UTF-32 for now, sorry
  1117. return '';
  1118. }
  1119. /**
  1120. * encodes an arbitrary variable into JSON format
  1121. *
  1122. * @param mixed $var any number, boolean, string, array, or object to be encoded.
  1123. * see argument 1 to Services_JSON() above for array-parsing behavior.
  1124. * if var is a strng, note that encode() always expects it
  1125. * to be in ASCII or UTF-8 format!
  1126. *
  1127. * @return mixed JSON string representation of input var or an error if a problem occurs
  1128. * @access public
  1129. */
  1130. private function json_encode($var)
  1131. {
  1132. if(is_object($var)) {
  1133. if(in_array($var,$this->json_objectStack)) {
  1134. return '"** Recursion **"';
  1135. }
  1136. }
  1137. switch (gettype($var)) {
  1138. case 'boolean':
  1139. return $var ? 'true' : 'false';
  1140. case 'NULL':
  1141. return 'null';
  1142. case 'integer':
  1143. return (int) $var;
  1144. case 'double':
  1145. case 'float':
  1146. return (float) $var;
  1147. case 'string':
  1148. // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  1149. $ascii = '';
  1150. $strlen_var = strlen($var);
  1151. /*
  1152. * Iterate over every character in the string,
  1153. * escaping with a slash or encoding to UTF-8 where necessary
  1154. */
  1155. for ($c = 0; $c < $strlen_var; ++$c) {
  1156. $ord_var_c = ord($var{$c});
  1157. switch (true) {
  1158. case $ord_var_c == 0x08:
  1159. $ascii .= '\b';
  1160. break;
  1161. case $ord_var_c == 0x09:
  1162. $ascii .= '\t';
  1163. break;
  1164. case $ord_var_c == 0x0A:
  1165. $ascii .= '\n';
  1166. break;
  1167. case $ord_var_c == 0x0C:
  1168. $ascii .= '\f';
  1169. break;
  1170. case $ord_var_c == 0x0D:
  1171. $ascii .= '\r';
  1172. break;
  1173. case $ord_var_c == 0x22:
  1174. case $ord_var_c == 0x2F:
  1175. case $ord_var_c == 0x5C:
  1176. // double quote, slash, slosh
  1177. $ascii .= '\\'.$var{$c};
  1178. break;
  1179. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  1180. // characters U-00000000 - U-0000007F (same as ASCII)
  1181. $ascii .= $var{$c};
  1182. break;
  1183. case (($ord_var_c & 0xE0) == 0xC0):
  1184. // characters U-00000080 - U-000007FF, mask 110XXXXX
  1185. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1186. $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
  1187. $c += 1;
  1188. $utf16 = $this->json_utf82utf16($char);
  1189. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1190. break;
  1191. case (($ord_var_c & 0xF0) == 0xE0):
  1192. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  1193. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1194. $char = pack('C*', $ord_var_c,
  1195. ord($var{$c + 1}),
  1196. ord($var{$c + 2}));
  1197. $c += 2;
  1198. $utf16 = $this->json_utf82utf16($char);
  1199. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1200. break;
  1201. case (($ord_var_c & 0xF8) == 0xF0):
  1202. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  1203. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1204. $char = pack('C*', $ord_var_c,
  1205. ord($var{$c + 1}),
  1206. ord($var{$c + 2}),
  1207. ord($var{$c + 3}));
  1208. $c += 3;
  1209. $utf16 = $this->json_utf82utf16($char);
  1210. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1211. break;
  1212. case (($ord_var_c & 0xFC) == 0xF8):
  1213. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  1214. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1215. $char = pack('C*', $ord_var_c,
  1216. ord($var{$c + 1}),
  1217. ord($var{$c + 2}),
  1218. ord($var{$c + 3}),
  1219. ord($var{$c + 4}));
  1220. $c += 4;
  1221. $utf16 = $this->json_utf82utf16($char);
  1222. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1223. break;
  1224. case (($ord_var_c & 0xFE) == 0xFC):
  1225. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  1226. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1227. $char = pack('C*', $ord_var_c,
  1228. ord($var{$c + 1}),
  1229. ord($var{$c + 2}),
  1230. ord($var{$c + 3}),
  1231. ord($var{$c + 4}),
  1232. ord($var{$c + 5}));
  1233. $c += 5;
  1234. $utf16 = $this->json_utf82utf16($char);
  1235. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1236. break;
  1237. }
  1238. }
  1239. return '"'.$ascii.'"';
  1240. case 'array':
  1241. /*
  1242. * As per JSON spec if any array key is not an integer
  1243. * we must treat the the whole array as an object. We
  1244. * also try to catch a sparsely populated associative
  1245. * array with numeric keys here because some JS engines
  1246. * will create an array with empty indexes up to
  1247. * max_index which can cause memory issues and because
  1248. * the keys, which may be relevant, will be remapped
  1249. * otherwise.
  1250. *
  1251. * As per the ECMA and JSON specification an object may
  1252. * have any string as a property. Unfortunately due to
  1253. * a hole in the ECMA specification if the key is a
  1254. * ECMA reserved word or starts with a digit the
  1255. * parameter is only accessible using ECMAScript's
  1256. * bracket notation.
  1257. */
  1258. // treat as a JSON object
  1259. if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
  1260. $this->json_objectStack[] = $var;
  1261. $properties = array_map(array($this, 'json_name_value'),
  1262. array_keys($var),
  1263. array_values($var));
  1264. array_pop($this->json_objectStack);
  1265. foreach($properties as $property) {
  1266. if($property instanceof Exception) {
  1267. return $property;
  1268. }
  1269. }
  1270. return '{' . join(',', $properties) . '}';
  1271. }
  1272. $this->json_objectStack[] = $var;
  1273. // treat it like a regular array
  1274. $elements = array_map(array($this, 'json_encode'), $var);
  1275. array_pop($this->json_objectStack);
  1276. foreach($elements as $element) {
  1277. if($element instanceof Exception) {
  1278. return $element;
  1279. }
  1280. }
  1281. return '[' . join(',', $elements) . ']';
  1282. case 'object':
  1283. $vars = self::encodeObject($var);
  1284. $this->json_objectStack[] = $var;
  1285. $properties = array_map(array($this, 'json_name_value'),
  1286. array_keys($vars),
  1287. array_values($vars));
  1288. array_pop($this->json_objectStack);
  1289. foreach($properties as $property) {
  1290. if($property instanceof Exception) {
  1291. return $property;
  1292. }
  1293. }
  1294. return '{' . join(',', $properties) . '}';
  1295. default:
  1296. return null;
  1297. }
  1298. }
  1299. /**
  1300. * array-walking function for use in generating JSON-formatted name-value pairs
  1301. *
  1302. * @param string $name name of key to use
  1303. * @param mixed $value reference to an array element to be encoded
  1304. *
  1305. * @return string JSON-formatted name-value pair, like '"name":value'
  1306. * @access private
  1307. */
  1308. private function json_name_value($name, $value)
  1309. {
  1310. // Encoding the $GLOBALS PHP array causes an infinite loop
  1311. // if the recursion is not reset here as it contains
  1312. // a reference to itself. This is the only way I have come up
  1313. // with to stop infinite recursion in this case.
  1314. if($name=='GLOBALS'
  1315. && is_array($value)
  1316. && array_key_exists('GLOBALS',$value)) {
  1317. $value['GLOBALS'] = '** Recursion **';
  1318. }
  1319. $encoded_value = $this->json_encode($value);
  1320. if($encoded_value instanceof Exception) {
  1321. return $encoded_value;
  1322. }
  1323. return $this->json_encode(strval($name)) . ':' . $encoded_value;
  1324. }
  1325. }