FirePHP.class.php 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831
  1. <?php
  2. namespace KIF\Debug;
  3. use ErrorException, Exception, ReflectionClass;
  4. // Authors:
  5. // - cadorn, Christoph Dorn <christoph@christophdorn.com>, Copyright 2007, New BSD License
  6. // - qbbr, Sokolov Innokenty <sokolov.innokenty@gmail.com>, Copyright 2011, New BSD License
  7. // - cadorn, Christoph Dorn <christoph@christophdorn.com>, Copyright 2011, MIT License
  8. /**
  9. * *** BEGIN LICENSE BLOCK *****
  10. *
  11. * [MIT License](http://www.opensource.org/licenses/mit-license.php)
  12. *
  13. * Copyright (c) 2007+ [Christoph Dorn](http://www.christophdorn.com/)
  14. *
  15. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16. * of this software and associated documentation files (the "Software"), to deal
  17. * in the Software without restriction, including without limitation the rights
  18. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19. * copies of the Software, and to permit persons to whom the Software is
  20. * furnished to do so, subject to the following conditions:
  21. *
  22. * The above copyright notice and this permission notice shall be included in
  23. * all copies or substantial portions of the Software.
  24. *
  25. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  26. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  27. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  28. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  30. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  31. * THE SOFTWARE.
  32. *
  33. * ***** END LICENSE BLOCK *****
  34. *
  35. * @copyright Copyright (C) 2007+ Christoph Dorn
  36. * @author Christoph Dorn <christoph@christophdorn.com>
  37. * @license [MIT License](http://www.opensource.org/licenses/mit-license.php)
  38. * @package FirePHPCore
  39. */
  40. /**
  41. * @see http://code.google.com/p/firephp/issues/detail?id=112
  42. */
  43. if (!defined('E_STRICT')) {
  44. define('E_STRICT', 2048);
  45. }
  46. if (!defined('E_RECOVERABLE_ERROR')) {
  47. define('E_RECOVERABLE_ERROR', 4096);
  48. }
  49. if (!defined('E_DEPRECATED')) {
  50. define('E_DEPRECATED', 8192);
  51. }
  52. if (!defined('E_USER_DEPRECATED')) {
  53. define('E_USER_DEPRECATED', 16384);
  54. }
  55. /**
  56. * Sends the given data to the FirePHP Firefox Extension.
  57. * The data can be displayed in the Firebug Console or in the
  58. * "Server" request tab.
  59. *
  60. * For more information see: http://www.firephp.org/
  61. *
  62. * @copyright Copyright (C) 2007+ Christoph Dorn
  63. * @author Christoph Dorn <christoph@christophdorn.com>
  64. * @license [MIT License](http://www.opensource.org/licenses/mit-license.php)
  65. * @package FirePHPCore
  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 (!$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. if ($this->logToInsightConsole !== null && (get_class($this) == 'FirePHP_Insight' || is_subclass_of($this, 'FirePHP_Insight'))) {
  717. $trace = debug_backtrace();
  718. if (!$trace) return false;
  719. for ($i = 0; $i < sizeof($trace); $i++) {
  720. if (isset($trace[$i]['class'])) {
  721. if ($trace[$i]['class'] == 'FirePHP' || $trace[$i]['class'] == 'FB') {
  722. continue;
  723. }
  724. }
  725. if (isset($trace[$i]['file'])) {
  726. $path = $this->_standardizePath($trace[$i]['file']);
  727. if (substr($path, -18, 18) == 'FirePHPCore/fb.php' || substr($path, -29, 29) == 'FirePHPCore/FirePHP.class.php') {
  728. continue;
  729. }
  730. }
  731. if (isset($trace[$i]['function']) && $trace[$i]['function'] == 'fb' &&
  732. isset($trace[$i - 1]['file']) && substr($this->_standardizePath($trace[$i - 1]['file']), -18, 18) == 'FirePHPCore/fb.php') {
  733. continue;
  734. }
  735. if (isset($trace[$i]['class']) && $trace[$i]['class'] == 'FB' &&
  736. isset($trace[$i - 1]['file']) && substr($this->_standardizePath($trace[$i - 1]['file']), -18, 18) == 'FirePHPCore/fb.php') {
  737. continue;
  738. }
  739. break;
  740. }
  741. // adjust trace offset
  742. $msg = $this->logToInsightConsole->option('encoder.trace.offsetAdjustment', $i);
  743. if ($object instanceof Exception) {
  744. $type = self::EXCEPTION;
  745. }
  746. if ($label && $type != self::TABLE && $type != self::GROUP_START) {
  747. $msg = $msg->label($label);
  748. }
  749. switch ($type) {
  750. case self::DUMP:
  751. case self::LOG:
  752. return $msg->log($object);
  753. case self::INFO:
  754. return $msg->info($object);
  755. case self::WARN:
  756. return $msg->warn($object);
  757. case self::ERROR:
  758. return $msg->error($object);
  759. case self::TRACE:
  760. return $msg->trace($object);
  761. case self::EXCEPTION:
  762. return $this->plugin('error')->handleException($object, $msg);
  763. case self::TABLE:
  764. if (isset($object[0]) && !is_string($object[0]) && $label) {
  765. $object = array($label, $object);
  766. }
  767. return $msg->table($object[0], array_slice($object[1], 1), $object[1][0]);
  768. case self::GROUP_START:
  769. $insightGroupStack[] = $msg->group(md5($label))->open();
  770. return $msg->log($label);
  771. case self::GROUP_END:
  772. if (count($insightGroupStack) == 0) {
  773. throw new ErrorException('Too many groupEnd() as opposed to group() calls!');
  774. }
  775. $group = array_pop($insightGroupStack);
  776. return $group->close();
  777. default:
  778. return $msg->log($object);
  779. }
  780. }
  781. if (!$this->detectClientExtension()) {
  782. return false;
  783. }
  784. $meta = array();
  785. $skipFinalObjectEncode = false;
  786. if ($object instanceof Exception) {
  787. $meta['file'] = $this->_escapeTraceFile($object->getFile());
  788. $meta['line'] = $object->getLine();
  789. $trace = $object->getTrace();
  790. if ($object instanceof ErrorException
  791. && isset($trace[0]['function'])
  792. && $trace[0]['function'] == 'errorHandler'
  793. && isset($trace[0]['class'])
  794. && $trace[0]['class'] == 'FirePHP') {
  795. $severity = false;
  796. switch ($object->getSeverity()) {
  797. case E_WARNING:
  798. $severity = 'E_WARNING';
  799. break;
  800. case E_NOTICE:
  801. $severity = 'E_NOTICE';
  802. break;
  803. case E_USER_ERROR:
  804. $severity = 'E_USER_ERROR';
  805. break;
  806. case E_USER_WARNING:
  807. $severity = 'E_USER_WARNING';
  808. break;
  809. case E_USER_NOTICE:
  810. $severity = 'E_USER_NOTICE';
  811. break;
  812. case E_STRICT:
  813. $severity = 'E_STRICT';
  814. break;
  815. case E_RECOVERABLE_ERROR:
  816. $severity = 'E_RECOVERABLE_ERROR';
  817. break;
  818. case E_DEPRECATED:
  819. $severity = 'E_DEPRECATED';
  820. break;
  821. case E_USER_DEPRECATED:
  822. $severity = 'E_USER_DEPRECATED';
  823. break;
  824. }
  825. $object = array('Class' => get_class($object),
  826. 'Message' => $severity . ': ' . $object->getMessage(),
  827. 'File' => $this->_escapeTraceFile($object->getFile()),
  828. 'Line' => $object->getLine(),
  829. 'Type' => 'trigger',
  830. 'Trace' => $this->_escapeTrace(array_splice($trace, 2)));
  831. $skipFinalObjectEncode = true;
  832. } else {
  833. $object = array('Class' => get_class($object),
  834. 'Message' => $object->getMessage(),
  835. 'File' => $this->_escapeTraceFile($object->getFile()),
  836. 'Line' => $object->getLine(),
  837. 'Type' => 'throw',
  838. 'Trace' => $this->_escapeTrace($trace));
  839. $skipFinalObjectEncode = true;
  840. }
  841. $type = self::EXCEPTION;
  842. } else if ($type == self::TRACE) {
  843. $trace = debug_backtrace();
  844. if (!$trace) return false;
  845. for ($i = 0; $i < sizeof($trace); $i++) {
  846. if (isset($trace[$i]['class'])
  847. && isset($trace[$i]['file'])
  848. && ($trace[$i]['class'] == 'FirePHP'
  849. || $trace[$i]['class'] == 'FB')
  850. && (substr($this->_standardizePath($trace[$i]['file']), -18, 18) == 'FirePHPCore/fb.php'
  851. || substr($this->_standardizePath($trace[$i]['file']), -29, 29) == 'FirePHPCore/FirePHP.class.php')) {
  852. /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
  853. } else
  854. if (isset($trace[$i]['class'])
  855. && isset($trace[$i+1]['file'])
  856. && $trace[$i]['class'] == 'FirePHP'
  857. && substr($this->_standardizePath($trace[$i + 1]['file']), -18, 18) == 'FirePHPCore/fb.php') {
  858. /* Skip fb() */
  859. } else
  860. if ($trace[$i]['function'] == 'fb'
  861. || $trace[$i]['function'] == 'trace'
  862. || $trace[$i]['function'] == 'send') {
  863. $object = array('Class' => isset($trace[$i]['class']) ? $trace[$i]['class'] : '',
  864. 'Type' => isset($trace[$i]['type']) ? $trace[$i]['type'] : '',
  865. 'Function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : '',
  866. 'Message' => $trace[$i]['args'][0],
  867. 'File' => isset($trace[$i]['file']) ? $this->_escapeTraceFile($trace[$i]['file']) : '',
  868. 'Line' => isset($trace[$i]['line']) ? $trace[$i]['line'] : '',
  869. 'Args' => isset($trace[$i]['args']) ? $this->encodeObject($trace[$i]['args']) : '',
  870. 'Trace' => $this->_escapeTrace(array_splice($trace, $i + 1)));
  871. $skipFinalObjectEncode = true;
  872. $meta['file'] = isset($trace[$i]['file']) ? $this->_escapeTraceFile($trace[$i]['file']) : '';
  873. $meta['line'] = isset($trace[$i]['line']) ? $trace[$i]['line'] : '';
  874. break;
  875. }
  876. }
  877. } else
  878. if ($type == self::TABLE) {
  879. if (isset($object[0]) && is_string($object[0])) {
  880. $object[1] = $this->encodeTable($object[1]);
  881. } else {
  882. $object = $this->encodeTable($object);
  883. }
  884. $skipFinalObjectEncode = true;
  885. } else if ($type == self::GROUP_START) {
  886. if (!$label) {
  887. throw $this->newException('You must specify a label for the group!');
  888. }
  889. } else {
  890. if ($type === null) {
  891. $type = self::LOG;
  892. }
  893. }
  894. if ($this->options['includeLineNumbers']) {
  895. if (!isset($meta['file']) || !isset($meta['line'])) {
  896. $trace = debug_backtrace();
  897. for ($i = 0; $trace && $i < sizeof($trace); $i++) {
  898. if (isset($trace[$i]['class'])
  899. && isset($trace[$i]['file'])
  900. && ($trace[$i]['class'] == 'FirePHP'
  901. || $trace[$i]['class'] == 'FB')
  902. && (substr($this->_standardizePath($trace[$i]['file']), -18, 18) == 'FirePHPCore/fb.php'
  903. || substr($this->_standardizePath($trace[$i]['file']), -29, 29) == 'FirePHPCore/FirePHP.class.php')) {
  904. /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
  905. } else
  906. if (isset($trace[$i]['class'])
  907. && isset($trace[$i + 1]['file'])
  908. && $trace[$i]['class'] == 'FirePHP'
  909. && substr($this->_standardizePath($trace[$i + 1]['file']), -18, 18) == 'FirePHPCore/fb.php') {
  910. /* Skip fb() */
  911. } else
  912. if (isset($trace[$i]['file'])
  913. && substr($this->_standardizePath($trace[$i]['file']), -18, 18) == 'FirePHPCore/fb.php') {
  914. /* Skip FB::fb() */
  915. } else {
  916. $meta['file'] = isset($trace[$i]['file']) ? $this->_escapeTraceFile($trace[$i]['file']) : '';
  917. $meta['line'] = isset($trace[$i]['line']) ? $trace[$i]['line'] : '';
  918. break;
  919. }
  920. }
  921. }
  922. } else {
  923. unset($meta['file']);
  924. unset($meta['line']);
  925. }
  926. $this->setHeader('X-Wf-Protocol-1', 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
  927. $this->setHeader('X-Wf-1-Plugin-1', 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/' . self::VERSION);
  928. $structureIndex = 1;
  929. if ($type == self::DUMP) {
  930. $structureIndex = 2;
  931. $this->setHeader('X-Wf-1-Structure-2', 'http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1');
  932. } else {
  933. $this->setHeader('X-Wf-1-Structure-1', 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1');
  934. }
  935. if ($type == self::DUMP) {
  936. $msg = '{"' . $label . '":' . $this->jsonEncode($object, $skipFinalObjectEncode) . '}';
  937. } else {
  938. $msgMeta = $options;
  939. $msgMeta['Type'] = $type;
  940. if ($label !== null) {
  941. $msgMeta['Label'] = $label;
  942. }
  943. if (isset($meta['file']) && !isset($msgMeta['File'])) {
  944. $msgMeta['File'] = $meta['file'];
  945. }
  946. if (isset($meta['line']) && !isset($msgMeta['Line'])) {
  947. $msgMeta['Line'] = $meta['line'];
  948. }
  949. $msg = '[' . $this->jsonEncode($msgMeta) . ',' . $this->jsonEncode($object, $skipFinalObjectEncode) . ']';
  950. }
  951. $parts = explode("\n", chunk_split($msg, 5000, "\n"));
  952. for ($i = 0; $i < count($parts); $i++) {
  953. $part = $parts[$i];
  954. if ($part) {
  955. if (count($parts) > 2) {
  956. // Message needs to be split into multiple parts
  957. $this->setHeader('X-Wf-1-' . $structureIndex . '-' . '1-' . $this->messageIndex,
  958. (($i == 0) ? strlen($msg) : '')
  959. . '|' . $part . '|'
  960. . (($i < count($parts) - 2) ? '\\' : ''));
  961. } else {
  962. $this->setHeader('X-Wf-1-' . $structureIndex . '-' . '1-' . $this->messageIndex,
  963. strlen($part) . '|' . $part . '|');
  964. }
  965. $this->messageIndex++;
  966. if ($this->messageIndex > 99999) {
  967. throw $this->newException('Maximum number (99,999) of messages reached!');
  968. }
  969. }
  970. }
  971. $this->setHeader('X-Wf-1-Index', $this->messageIndex - 1);
  972. return true;
  973. }
  974. /**
  975. * Standardizes path for windows systems.
  976. *
  977. * @param string $path
  978. * @return string
  979. */
  980. protected function _standardizePath($path)
  981. {
  982. return preg_replace('/\\\\+/', '/', $path);
  983. }
  984. /**
  985. * Escape trace path for windows systems
  986. *
  987. * @param array $trace
  988. * @return array
  989. */
  990. protected function _escapeTrace($trace)
  991. {
  992. if (!$trace) return $trace;
  993. for ($i = 0; $i < sizeof($trace); $i++) {
  994. if (isset($trace[$i]['file'])) {
  995. $trace[$i]['file'] = $this->_escapeTraceFile($trace[$i]['file']);
  996. }
  997. if (isset($trace[$i]['args'])) {
  998. $trace[$i]['args'] = $this->encodeObject($trace[$i]['args']);
  999. }
  1000. }
  1001. return $trace;
  1002. }
  1003. /**
  1004. * Escape file information of trace for windows systems
  1005. *
  1006. * @param string $file
  1007. * @return string
  1008. */
  1009. protected function _escapeTraceFile($file)
  1010. {
  1011. /* Check if we have a windows filepath */
  1012. if (strpos($file, '\\')) {
  1013. /* First strip down to single \ */
  1014. $file = preg_replace('/\\\\+/', '\\', $file);
  1015. return $file;
  1016. }
  1017. return $file;
  1018. }
  1019. /**
  1020. * Check if headers have already been sent
  1021. *
  1022. * @param string $filename
  1023. * @param integer $linenum
  1024. */
  1025. protected function headersSent(&$filename, &$linenum)
  1026. {
  1027. return headers_sent($filename, $linenum);
  1028. }
  1029. /**
  1030. * Send header
  1031. *
  1032. * @param string $name
  1033. * @param string $value
  1034. */
  1035. protected function setHeader($name, $value)
  1036. {
  1037. return header($name . ': ' . $value);
  1038. }
  1039. /**
  1040. * Get user agent
  1041. *
  1042. * @return string|false
  1043. */
  1044. protected function getUserAgent()
  1045. {
  1046. if (!isset($_SERVER['HTTP_USER_AGENT'])) return false;
  1047. return $_SERVER['HTTP_USER_AGENT'];
  1048. }
  1049. /**
  1050. * Get all request headers
  1051. *
  1052. * @return array
  1053. */
  1054. public static function getAllRequestHeaders()
  1055. {
  1056. static $_cachedHeaders = false;
  1057. if ($_cachedHeaders !== false) {
  1058. return $_cachedHeaders;
  1059. }
  1060. $headers = array();
  1061. if (function_exists('getallheaders')) {
  1062. foreach (getallheaders() as $name => $value) {
  1063. $headers[strtolower($name)] = $value;
  1064. }
  1065. } else {
  1066. foreach ($_SERVER as $name => $value) {
  1067. if (substr($name, 0, 5) == 'HTTP_') {
  1068. $headers[strtolower(str_replace(' ', '-', str_replace('_', ' ', substr($name, 5))))] = $value;
  1069. }
  1070. }
  1071. }
  1072. return $_cachedHeaders = $headers;
  1073. }
  1074. /**
  1075. * Get a request header
  1076. *
  1077. * @return string|false
  1078. */
  1079. protected function getRequestHeader($name)
  1080. {
  1081. $headers = self::getAllRequestHeaders();
  1082. if (isset($headers[strtolower($name)])) {
  1083. return $headers[strtolower($name)];
  1084. }
  1085. return false;
  1086. }
  1087. /**
  1088. * Returns a new exception
  1089. *
  1090. * @param string $message
  1091. * @return Exception
  1092. */
  1093. protected function newException($message)
  1094. {
  1095. return new Exception($message);
  1096. }
  1097. /**
  1098. * Encode an object into a JSON string
  1099. *
  1100. * Uses PHP's jeson_encode() if available
  1101. *
  1102. * @param object $object The object to be encoded
  1103. * @param boolean $skipObjectEncode
  1104. * @return string The JSON string
  1105. */
  1106. public function jsonEncode($object, $skipObjectEncode = false)
  1107. {
  1108. if (!$skipObjectEncode) {
  1109. $object = $this->encodeObject($object);
  1110. }
  1111. if (function_exists('json_encode')
  1112. && $this->options['useNativeJsonEncode'] != false) {
  1113. return json_encode($object);
  1114. } else {
  1115. return $this->json_encode($object);
  1116. }
  1117. }
  1118. /**
  1119. * Encodes a table by encoding each row and column with encodeObject()
  1120. *
  1121. * @param array $table The table to be encoded
  1122. * @return array
  1123. */
  1124. protected function encodeTable($table)
  1125. {
  1126. if (!$table) return $table;
  1127. $newTable = array();
  1128. foreach ($table as $row) {
  1129. if (is_array($row)) {
  1130. $newRow = array();
  1131. foreach ($row as $item) {
  1132. $newRow[] = $this->encodeObject($item);
  1133. }
  1134. $newTable[] = $newRow;
  1135. }
  1136. }
  1137. return $newTable;
  1138. }
  1139. /**
  1140. * Encodes an object including members with
  1141. * protected and private visibility
  1142. *
  1143. * @param object $object The object to be encoded
  1144. * @param integer $Depth The current traversal depth
  1145. * @return array All members of the object
  1146. */
  1147. protected function encodeObject($object, $objectDepth = 1, $arrayDepth = 1, $maxDepth = 1)
  1148. {
  1149. if ($maxDepth > $this->options['maxDepth']) {
  1150. return '** Max Depth (' . $this->options['maxDepth'] . ') **';
  1151. }
  1152. $return = array();
  1153. if (is_resource($object)) {
  1154. return '** ' . (string) $object . ' **';
  1155. } else if (is_object($object)) {
  1156. if ($objectDepth > $this->options['maxObjectDepth']) {
  1157. return '** Max Object Depth (' . $this->options['maxObjectDepth'] . ') **';
  1158. }
  1159. foreach ($this->objectStack as $refVal) {
  1160. if ($refVal === $object) {
  1161. return '** Recursion (' . get_class($object) . ') **';
  1162. }
  1163. }
  1164. array_push($this->objectStack, $object);
  1165. $return['__className'] = $class = get_class($object);
  1166. $classLower = strtolower($class);
  1167. $reflectionClass = new ReflectionClass($class);
  1168. $properties = array();
  1169. foreach ($reflectionClass->getProperties() as $property) {
  1170. $properties[$property->getName()] = $property;
  1171. }
  1172. $members = (array)$object;
  1173. foreach ($properties as $plainName => $property) {
  1174. $name = $rawName = $plainName;
  1175. if ($property->isStatic()) {
  1176. $name = 'static:' . $name;
  1177. }
  1178. if ($property->isPublic()) {
  1179. $name = 'public:' . $name;
  1180. } else if ($property->isPrivate()) {
  1181. $name = 'private:' . $name;
  1182. $rawName = "\0" . $class . "\0" . $rawName;
  1183. } else if ($property->isProtected()) {
  1184. $name = 'protected:' . $name;
  1185. $rawName = "\0" . '*' . "\0" . $rawName;
  1186. }
  1187. if (!(isset($this->objectFilters[$classLower])
  1188. && is_array($this->objectFilters[$classLower])
  1189. && in_array($plainName, $this->objectFilters[$classLower]))) {
  1190. if (array_key_exists($rawName, $members) && !$property->isStatic()) {
  1191. $return[$name] = $this->encodeObject($members[$rawName], $objectDepth + 1, 1, $maxDepth + 1);
  1192. } else {
  1193. if (method_exists($property, 'setAccessible')) {
  1194. $property->setAccessible(true);
  1195. $return[$name] = $this->encodeObject($property->getValue($object), $objectDepth + 1, 1, $maxDepth + 1);
  1196. } else
  1197. if ($property->isPublic()) {
  1198. $return[$name] = $this->encodeObject($property->getValue($object), $objectDepth + 1, 1, $maxDepth + 1);
  1199. } else {
  1200. $return[$name] = '** Need PHP 5.3 to get value **';
  1201. }
  1202. }
  1203. } else {
  1204. $return[$name] = '** Excluded by Filter **';
  1205. }
  1206. }
  1207. // Include all members that are not defined in the class
  1208. // but exist in the object
  1209. foreach ($members as $rawName => $value) {
  1210. $name = $rawName;
  1211. if ($name{0} == "\0") {
  1212. $parts = explode("\0", $name);
  1213. $name = $parts[2];
  1214. }
  1215. $plainName = $name;
  1216. if (!isset($properties[$name])) {
  1217. $name = 'undeclared:' . $name;
  1218. if (!(isset($this->objectFilters[$classLower])
  1219. && is_array($this->objectFilters[$classLower])
  1220. && in_array($plainName, $this->objectFilters[$classLower]))) {
  1221. $return[$name] = $this->encodeObject($value, $objectDepth + 1, 1, $maxDepth + 1);
  1222. } else {
  1223. $return[$name] = '** Excluded by Filter **';
  1224. }
  1225. }
  1226. }
  1227. array_pop($this->objectStack);
  1228. } elseif (is_array($object)) {
  1229. if ($arrayDepth > $this->options['maxArrayDepth']) {
  1230. return '** Max Array Depth (' . $this->options['maxArrayDepth'] . ') **';
  1231. }
  1232. foreach ($object as $key => $val) {
  1233. // Encoding the $GLOBALS PHP array causes an infinite loop
  1234. // if the recursion is not reset here as it contains
  1235. // a reference to itself. This is the only way I have come up
  1236. // with to stop infinite recursion in this case.
  1237. if ($key == 'GLOBALS'
  1238. && is_array($val)
  1239. && array_key_exists('GLOBALS', $val)) {
  1240. $val['GLOBALS'] = '** Recursion (GLOBALS) **';
  1241. }
  1242. if (!$this->is_utf8($key)) {
  1243. $key = utf8_encode($key);
  1244. }
  1245. $return[$key] = $this->encodeObject($val, 1, $arrayDepth + 1, $maxDepth + 1);
  1246. }
  1247. } else {
  1248. if ($this->is_utf8($object)) {
  1249. return $object;
  1250. } else {
  1251. return utf8_encode($object);
  1252. }
  1253. }
  1254. return $return;
  1255. }
  1256. /**
  1257. * Returns true if $string is valid UTF-8 and false otherwise.
  1258. *
  1259. * @param mixed $str String to be tested
  1260. * @return boolean
  1261. */
  1262. protected function is_utf8($str)
  1263. {
  1264. if (function_exists('mb_detect_encoding')) {
  1265. return (
  1266. mb_detect_encoding($str, 'UTF-8', true) == 'UTF-8' &&
  1267. ($str === null || $this->jsonEncode($str, true) !== 'null')
  1268. );
  1269. }
  1270. $c = 0;
  1271. $b = 0;
  1272. $bits = 0;
  1273. $len = strlen($str);
  1274. for ($i = 0; $i < $len; $i++) {
  1275. $c = ord($str[$i]);
  1276. if ($c > 128) {
  1277. if (($c >= 254)) return false;
  1278. elseif ($c >= 252) $bits = 6;
  1279. elseif ($c >= 248) $bits = 5;
  1280. elseif ($c >= 240) $bits = 4;
  1281. elseif ($c >= 224) $bits = 3;
  1282. elseif ($c >= 192) $bits = 2;
  1283. else return false;
  1284. if (($i + $bits) > $len) return false;
  1285. while($bits > 1) {
  1286. $i++;
  1287. $b = ord($str[$i]);
  1288. if ($b < 128 || $b > 191) return false;
  1289. $bits--;
  1290. }
  1291. }
  1292. }
  1293. return ($str === null || $this->jsonEncode($str, true) !== 'null');
  1294. }
  1295. /**
  1296. * Converts to and from JSON format.
  1297. *
  1298. * JSON (JavaScript Object Notation) is a lightweight data-interchange
  1299. * format. It is easy for humans to read and write. It is easy for machines
  1300. * to parse and generate. It is based on a subset of the JavaScript
  1301. * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
  1302. * This feature can also be found in Python. JSON is a text format that is
  1303. * completely language independent but uses conventions that are familiar
  1304. * to programmers of the C-family of languages, including C, C++, C#, Java,
  1305. * JavaScript, Perl, TCL, and many others. These properties make JSON an
  1306. * ideal data-interchange language.
  1307. *
  1308. * This package provides a simple encoder and decoder for JSON notation. It
  1309. * is intended for use with client-side Javascript applications that make
  1310. * use of HTTPRequest to perform server communication functions - data can
  1311. * be encoded into JSON notation for use in a client-side javascript, or
  1312. * decoded from incoming Javascript requests. JSON format is native to
  1313. * Javascript, and can be directly eval()'ed with no further parsing
  1314. * overhead
  1315. *
  1316. * All strings should be in ASCII or UTF-8 format!
  1317. *
  1318. * LICENSE: Redistribution and use in source and binary forms, with or
  1319. * without modification, are permitted provided that the following
  1320. * conditions are met: Redistributions of source code must retain the
  1321. * above copyright notice, this list of conditions and the following
  1322. * disclaimer. Redistributions in binary form must reproduce the above
  1323. * copyright notice, this list of conditions and the following disclaimer
  1324. * in the documentation and/or other materials provided with the
  1325. * distribution.
  1326. *
  1327. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  1328. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  1329. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
  1330. * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  1331. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  1332. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  1333. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  1334. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  1335. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  1336. * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  1337. * DAMAGE.
  1338. *
  1339. * @category
  1340. * @package Services_JSON
  1341. * @author Michal Migurski <mike-json@teczno.com>
  1342. * @author Matt Knapp <mdknapp[at]gmail[dot]com>
  1343. * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
  1344. * @author Christoph Dorn <christoph@christophdorn.com>
  1345. * @copyright 2005 Michal Migurski
  1346. * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
  1347. * @license http://www.opensource.org/licenses/bsd-license.php
  1348. * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
  1349. */
  1350. /**
  1351. * Keep a list of objects as we descend into the array so we can detect recursion.
  1352. */
  1353. private $json_objectStack = array();
  1354. /**
  1355. * convert a string from one UTF-8 char to one UTF-16 char
  1356. *
  1357. * Normally should be handled by mb_convert_encoding, but
  1358. * provides a slower PHP-only method for installations
  1359. * that lack the multibye string extension.
  1360. *
  1361. * @param string $utf8 UTF-8 character
  1362. * @return string UTF-16 character
  1363. * @access private
  1364. */
  1365. private function json_utf82utf16($utf8)
  1366. {
  1367. // oh please oh please oh please oh please oh please
  1368. if (function_exists('mb_convert_encoding')) {
  1369. return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
  1370. }
  1371. switch (strlen($utf8)) {
  1372. case 1:
  1373. // this case should never be reached, because we are in ASCII range
  1374. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1375. return $utf8;
  1376. case 2:
  1377. // return a UTF-16 character from a 2-byte UTF-8 char
  1378. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1379. return chr(0x07 & (ord($utf8{0}) >> 2))
  1380. . chr((0xC0 & (ord($utf8{0}) << 6))
  1381. | (0x3F & ord($utf8{1})));
  1382. case 3:
  1383. // return a UTF-16 character from a 3-byte UTF-8 char
  1384. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1385. return chr((0xF0 & (ord($utf8{0}) << 4))
  1386. | (0x0F & (ord($utf8{1}) >> 2)))
  1387. . chr((0xC0 & (ord($utf8{1}) << 6))
  1388. | (0x7F & ord($utf8{2})));
  1389. }
  1390. // ignoring UTF-32 for now, sorry
  1391. return '';
  1392. }
  1393. /**
  1394. * encodes an arbitrary variable into JSON format
  1395. *
  1396. * @param mixed $var any number, boolean, string, array, or object to be encoded.
  1397. * see argument 1 to Services_JSON() above for array-parsing behavior.
  1398. * if var is a strng, note that encode() always expects it
  1399. * to be in ASCII or UTF-8 format!
  1400. *
  1401. * @return mixed JSON string representation of input var or an error if a problem occurs
  1402. * @access public
  1403. */
  1404. private function json_encode($var)
  1405. {
  1406. if (is_object($var)) {
  1407. if (in_array($var, $this->json_objectStack)) {
  1408. return '"** Recursion **"';
  1409. }
  1410. }
  1411. switch (gettype($var)) {
  1412. case 'boolean':
  1413. return $var ? 'true' : 'false';
  1414. case 'NULL':
  1415. return 'null';
  1416. case 'integer':
  1417. return (int) $var;
  1418. case 'double':
  1419. case 'float':
  1420. return (float) $var;
  1421. case 'string':
  1422. // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  1423. $ascii = '';
  1424. $strlen_var = strlen($var);
  1425. /*
  1426. * Iterate over every character in the string,
  1427. * escaping with a slash or encoding to UTF-8 where necessary
  1428. */
  1429. for ($c = 0; $c < $strlen_var; ++$c) {
  1430. $ord_var_c = ord($var{$c});
  1431. switch (true) {
  1432. case $ord_var_c == 0x08:
  1433. $ascii .= '\b';
  1434. break;
  1435. case $ord_var_c == 0x09:
  1436. $ascii .= '\t';
  1437. break;
  1438. case $ord_var_c == 0x0A:
  1439. $ascii .= '\n';
  1440. break;
  1441. case $ord_var_c == 0x0C:
  1442. $ascii .= '\f';
  1443. break;
  1444. case $ord_var_c == 0x0D:
  1445. $ascii .= '\r';
  1446. break;
  1447. case $ord_var_c == 0x22:
  1448. case $ord_var_c == 0x2F:
  1449. case $ord_var_c == 0x5C:
  1450. // double quote, slash, slosh
  1451. $ascii .= '\\' . $var{$c};
  1452. break;
  1453. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  1454. // characters U-00000000 - U-0000007F (same as ASCII)
  1455. $ascii .= $var{$c};
  1456. break;
  1457. case (($ord_var_c & 0xE0) == 0xC0):
  1458. // characters U-00000080 - U-000007FF, mask 110XXXXX
  1459. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1460. $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
  1461. $c += 1;
  1462. $utf16 = $this->json_utf82utf16($char);
  1463. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1464. break;
  1465. case (($ord_var_c & 0xF0) == 0xE0):
  1466. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  1467. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1468. $char = pack('C*', $ord_var_c,
  1469. ord($var{$c + 1}),
  1470. ord($var{$c + 2}));
  1471. $c += 2;
  1472. $utf16 = $this->json_utf82utf16($char);
  1473. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1474. break;
  1475. case (($ord_var_c & 0xF8) == 0xF0):
  1476. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  1477. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1478. $char = pack('C*', $ord_var_c,
  1479. ord($var{$c + 1}),
  1480. ord($var{$c + 2}),
  1481. ord($var{$c + 3}));
  1482. $c += 3;
  1483. $utf16 = $this->json_utf82utf16($char);
  1484. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1485. break;
  1486. case (($ord_var_c & 0xFC) == 0xF8):
  1487. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  1488. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  1489. $char = pack('C*', $ord_var_c,
  1490. ord($var{$c + 1}),
  1491. ord($var{$c + 2}),
  1492. ord($var{$c + 3}),
  1493. ord($var{$c + 4}));
  1494. $c += 4;
  1495. $utf16 = $this->json_utf82utf16($char);
  1496. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1497. break;
  1498. case (($ord_var_c & 0xFE) == 0xFC):
  1499. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  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. ord($var{$c + 5}));
  1507. $c += 5;
  1508. $utf16 = $this->json_utf82utf16($char);
  1509. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  1510. break;
  1511. }
  1512. }
  1513. return '"' . $ascii . '"';
  1514. case 'array':
  1515. /*
  1516. * As per JSON spec if any array key is not an integer
  1517. * we must treat the the whole array as an object. We
  1518. * also try to catch a sparsely populated associative
  1519. * array with numeric keys here because some JS engines
  1520. * will create an array with empty indexes up to
  1521. * max_index which can cause memory issues and because
  1522. * the keys, which may be relevant, will be remapped
  1523. * otherwise.
  1524. *
  1525. * As per the ECMA and JSON specification an object may
  1526. * have any string as a property. Unfortunately due to
  1527. * a hole in the ECMA specification if the key is a
  1528. * ECMA reserved word or starts with a digit the
  1529. * parameter is only accessible using ECMAScript's
  1530. * bracket notation.
  1531. */
  1532. // treat as a JSON object
  1533. if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
  1534. $this->json_objectStack[] = $var;
  1535. $properties = array_map(array($this, 'json_name_value'),
  1536. array_keys($var),
  1537. array_values($var));
  1538. array_pop($this->json_objectStack);
  1539. foreach ($properties as $property) {
  1540. if ($property instanceof Exception) {
  1541. return $property;
  1542. }
  1543. }
  1544. return '{' . join(',', $properties) . '}';
  1545. }
  1546. $this->json_objectStack[] = $var;
  1547. // treat it like a regular array
  1548. $elements = array_map(array($this, 'json_encode'), $var);
  1549. array_pop($this->json_objectStack);
  1550. foreach ($elements as $element) {
  1551. if ($element instanceof Exception) {
  1552. return $element;
  1553. }
  1554. }
  1555. return '[' . join(',', $elements) . ']';
  1556. case 'object':
  1557. $vars = self::encodeObject($var);
  1558. $this->json_objectStack[] = $var;
  1559. $properties = array_map(array($this, 'json_name_value'),
  1560. array_keys($vars),
  1561. array_values($vars));
  1562. array_pop($this->json_objectStack);
  1563. foreach ($properties as $property) {
  1564. if ($property instanceof Exception) {
  1565. return $property;
  1566. }
  1567. }
  1568. return '{' . join(',', $properties) . '}';
  1569. default:
  1570. return null;
  1571. }
  1572. }
  1573. /**
  1574. * array-walking function for use in generating JSON-formatted name-value pairs
  1575. *
  1576. * @param string $name name of key to use
  1577. * @param mixed $value reference to an array element to be encoded
  1578. *
  1579. * @return string JSON-formatted name-value pair, like '"name":value'
  1580. * @access private
  1581. */
  1582. private function json_name_value($name, $value)
  1583. {
  1584. // Encoding the $GLOBALS PHP array causes an infinite loop
  1585. // if the recursion is not reset here as it contains
  1586. // a reference to itself. This is the only way I have come up
  1587. // with to stop infinite recursion in this case.
  1588. if ($name == 'GLOBALS'
  1589. && is_array($value)
  1590. && array_key_exists('GLOBALS', $value)) {
  1591. $value['GLOBALS'] = '** Recursion **';
  1592. }
  1593. $encodedValue = $this->json_encode($value);
  1594. if ($encodedValue instanceof Exception) {
  1595. return $encodedValue;
  1596. }
  1597. return $this->json_encode(strval($name)) . ':' . $encodedValue;
  1598. }
  1599. /**
  1600. * @deprecated
  1601. */
  1602. public function setProcessorUrl($URL)
  1603. {
  1604. trigger_error('The FirePHP::setProcessorUrl() method is no longer supported', E_USER_DEPRECATED);
  1605. }
  1606. /**
  1607. * @deprecated
  1608. */
  1609. public function setRendererUrl($URL)
  1610. {
  1611. trigger_error('The FirePHP::setRendererUrl() method is no longer supported', E_USER_DEPRECATED);
  1612. }
  1613. }