FirePHP.Class.php 61 KB

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