PageRenderTime 55ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/min/lib/FirePHP.php

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