FirePHP.class.php 48 KB

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