PageRenderTime 69ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/application/libraries/Firephp.php

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