You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1784 lines
60 KiB

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