3 * *** BEGIN LICENSE BLOCK *****
5 * This file is part of FirePHP (http://www.firephp.org/).
7 * Software License Agreement (New BSD License)
9 * Copyright (c) 2006-2009, Christoph Dorn
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without modification,
13 * are permitted provided that the following conditions are met:
15 * * Redistributions of source code must retain the above copyright notice,
16 * this list of conditions and the following disclaimer.
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.
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.
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.
37 * ***** END LICENSE BLOCK *****
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
47 * Sends the given data to the FirePHP Firefox Extension.
48 * The data can be displayed in the Firebug Console or in the
49 * "Server" request tab.
51 * For more information see: http://www.firephp.org/
53 * @copyright Copyright (C) 2007-2009 Christoph Dorn
54 * @author Christoph Dorn <christoph@christophdorn.com>
55 * @license http://www.opensource.org/licenses/bsd-license.php
65 const VERSION = '0.3';
70 * Logs a message to firebug console.
79 * Logs a message to firebug console and displays an info icon before the message.
88 * Logs a message to firebug console, displays an warning icon before the message and colors the line turquoise.
97 * 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 const ERROR = 'ERROR';
104 * Dumps a variable to firebug's server panel
111 * Displays a stack trace in firebug console
115 const TRACE = 'TRACE';
118 * Displays an exception in firebug console
120 * Increments the firebug error count.
124 const EXCEPTION = 'EXCEPTION';
127 * Displays an table in firebug console
131 const TABLE = 'TABLE';
134 * Starts a group in firebug console
138 const GROUP_START = 'GROUP_START';
141 * Ends a group in firebug console
145 const GROUP_END = 'GROUP_END';
148 * Singleton instance of FirePHP
152 protected static $instance = null;
155 * Flag whether we are logging from within the exception handler
159 protected $inExceptionHandler = false;
162 * Flag whether to throw PHP errors that have been converted to ErrorExceptions
166 protected $throwErrorExceptions = true;
169 * Flag whether to convert PHP assertion errors to Exceptions
173 protected $convertAssertionErrorsToExceptions = true;
176 * Flag whether to throw PHP assertion errors that have been converted to Exceptions
180 protected $throwAssertionExceptions = false;
183 * Wildfire protocol message index
187 protected $messageIndex = 1;
190 * Options for the library
194 protected $options = array('maxObjectDepth' => 10,
195 'maxArrayDepth' => 20,
196 'useNativeJsonEncode' => true,
197 'includeLineNumbers' => true);
200 * Filters used to exclude object members when encoding
204 protected $objectFilters = array();
207 * A stack of objects used to detect recursion during object encoding
211 protected $objectStack = array();
214 * Flag to enable/disable logging
218 protected $enabled = true;
221 * The object constructor
223 function __construct() {
227 * When the object gets serialized only include specific object members.
231 public function __sleep() {
232 return array('options','objectFilters','enabled');
236 * Gets singleton instance of FirePHP
238 * @param boolean $AutoCreate
241 public static function getInstance($AutoCreate=false) {
242 if($AutoCreate===true && !self::$instance) {
245 return self::$instance;
249 * Creates FirePHP object and stores it for singleton access
253 public static function init() {
254 return self::$instance = new self();
258 * Enable and disable logging to Firebug
260 * @param boolean $Enabled TRUE to enable, FALSE to disable
263 public function setEnabled($Enabled) {
264 $this->enabled = $Enabled;
268 * Check if logging is enabled
270 * @return boolean TRUE if enabled
272 public function getEnabled() {
273 return $this->enabled;
277 * Specify a filter to be used when encoding an object
279 * Filters are used to exclude object members.
281 * @param string $Class The class name of the object
282 * @param array $Filter An array of members to exclude
285 public function setObjectFilter($Class, $Filter) {
286 $this->objectFilters[strtolower($Class)] = $Filter;
290 * Set some options for the library
293 * - maxObjectDepth: The maximum depth to traverse objects (default: 10)
294 * - maxArrayDepth: The maximum depth to traverse arrays (default: 20)
295 * - useNativeJsonEncode: If true will use json_encode() (default: true)
296 * - includeLineNumbers: If true will include line numbers and filenames (default: true)
298 * @param array $Options The options to be set
301 public function setOptions($Options) {
302 $this->options = array_merge($this->options,$Options);
306 * Get options from the library
308 * @return array The currently set options
310 public function getOptions() {
311 return $this->options;
315 * Register FirePHP as your error handler
317 * Will throw exceptions for each php error.
319 * @return mixed Returns a string containing the previously defined error handler (if any)
321 public function registerErrorHandler($throwErrorExceptions=true)
323 //NOTE: The following errors will not be caught by this error handler:
324 // E_ERROR, E_PARSE, E_CORE_ERROR,
325 // E_CORE_WARNING, E_COMPILE_ERROR,
326 // E_COMPILE_WARNING, E_STRICT
328 $this->throwErrorExceptions = $throwErrorExceptions;
330 return set_error_handler(array($this,'errorHandler'));
334 * FirePHP's error handler
336 * Throws exception for each php error that will occur.
339 * @param string $errstr
340 * @param string $errfile
341 * @param int $errline
342 * @param array $errcontext
344 public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
346 // Don't throw exception if error reporting is switched off
347 if (error_reporting() == 0) {
350 // Only throw exceptions for errors we are asking for
351 if (error_reporting() & $errno) {
353 $exception = new ErrorException($errstr, 0, $errno, $errfile, $errline);
354 if($this->throwErrorExceptions) {
357 $this->fb($exception);
363 * Register FirePHP as your exception handler
365 * @return mixed Returns the name of the previously defined exception handler,
367 * If no previous handler was defined, NULL is also returned.
369 public function registerExceptionHandler()
371 return set_exception_handler(array($this,'exceptionHandler'));
375 * FirePHP's exception handler
377 * Logs all exceptions to your firebug console and then stops the script.
379 * @param Exception $Exception
382 function exceptionHandler($Exception) {
384 $this->inExceptionHandler = true;
386 header('HTTP/1.1 500 Internal Server Error');
388 $this->fb($Exception);
390 $this->inExceptionHandler = false;
394 * Register FirePHP driver as your assert callback
396 * @param boolean $convertAssertionErrorsToExceptions
397 * @param boolean $throwAssertionExceptions
398 * @return mixed Returns the original setting or FALSE on errors
400 public function registerAssertionHandler($convertAssertionErrorsToExceptions=true, $throwAssertionExceptions=false)
402 $this->convertAssertionErrorsToExceptions = $convertAssertionErrorsToExceptions;
403 $this->throwAssertionExceptions = $throwAssertionExceptions;
405 if($throwAssertionExceptions && !$convertAssertionErrorsToExceptions) {
406 throw $this->newException('Cannot throw assertion exceptions as assertion errors are not being converted to exceptions!');
409 return assert_options(ASSERT_CALLBACK, array($this, 'assertionHandler'));
413 * FirePHP's assertion handler
415 * Logs all assertions to your firebug console and then stops the script.
417 * @param string $file File source of assertion
418 * @param int $line Line source of assertion
419 * @param mixed $code Assertion code
421 public function assertionHandler($file, $line, $code)
424 if($this->convertAssertionErrorsToExceptions) {
426 $exception = new ErrorException('Assertion Failed - Code[ '.$code.' ]', 0, null, $file, $line);
428 if($this->throwAssertionExceptions) {
431 $this->fb($exception);
436 $this->fb($code, 'Assertion Failed', FirePHP::ERROR, array('File'=>$file,'Line'=>$line));
442 * Set custom processor url for FirePHP
446 public function setProcessorUrl($URL)
448 $this->setHeader('X-FirePHP-ProcessorURL', $URL);
452 * Set custom renderer url for FirePHP
456 public function setRendererUrl($URL)
458 $this->setHeader('X-FirePHP-RendererURL', $URL);
462 * Start a group for following messages.
465 * Collapsed: [true|false]
466 * Color: [#RRGGBB|ColorName]
468 * @param string $Name
469 * @param array $Options OPTIONAL Instructions on how to log the group
473 public function group($Name, $Options=null) {
476 throw $this->newException('You must specify a label for the group!');
480 if(!is_array($Options)) {
481 throw $this->newException('Options must be defined as an array!');
483 if(array_key_exists('Collapsed', $Options)) {
484 $Options['Collapsed'] = ($Options['Collapsed'])?'true':'false';
488 return $this->fb(null, $Name, FirePHP::GROUP_START, $Options);
492 * Ends a group you have started before
497 public function groupEnd() {
498 return $this->fb(null, null, FirePHP::GROUP_END);
502 * Log object with label to firebug console
505 * @param mixes $Object
506 * @param string $Label
510 public function log($Object, $Label=null) {
511 return $this->fb($Object, $Label, FirePHP::LOG);
515 * Log object with label to firebug console
518 * @param mixes $Object
519 * @param string $Label
523 public function info($Object, $Label=null) {
524 return $this->fb($Object, $Label, FirePHP::INFO);
528 * Log object with label to firebug console
531 * @param mixes $Object
532 * @param string $Label
536 public function warn($Object, $Label=null) {
537 return $this->fb($Object, $Label, FirePHP::WARN);
541 * Log object with label to firebug console
543 * @see FirePHP::ERROR
544 * @param mixes $Object
545 * @param string $Label
549 public function error($Object, $Label=null) {
550 return $this->fb($Object, $Label, FirePHP::ERROR);
554 * Dumps key and variable to firebug server panel
558 * @param mixed $Variable
562 public function dump($Key, $Variable) {
563 return $this->fb($Variable, $Key, FirePHP::DUMP);
567 * Log a trace in the firebug console
569 * @see FirePHP::TRACE
570 * @param string $Label
574 public function trace($Label) {
575 return $this->fb($Label, FirePHP::TRACE);
579 * Log a table in the firebug console
581 * @see FirePHP::TABLE
582 * @param string $Label
583 * @param string $Table
587 public function table($Label, $Table) {
588 return $this->fb($Table, $Label, FirePHP::TABLE);
592 * Check if FirePHP is installed on client
596 public function detectClientExtension() {
597 /* Check if FirePHP is installed on client */
598 if(!@preg_match_all('/\sFirePHP\/([\.|\d]*)\s?/si',$this->getUserAgent(),$m) ||
599 !version_compare($m[1][0],'0.0.6','>=')) {
606 * Log varible to Firebug
608 * @see http://www.firephp.org/Wiki/Reference/Fb
609 * @param mixed $Object The variable to be logged
610 * @return true Return TRUE if message was added to headers, FALSE otherwise
613 public function fb($Object) {
615 if(!$this->enabled) {
619 if (headers_sent($filename, $linenum)) {
620 // If we are logging from within the exception handler we cannot throw another exception
621 if($this->inExceptionHandler) {
622 // Simply echo the error out to the page
623 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>';
625 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.');
633 if(func_num_args()==1) {
635 if(func_num_args()==2) {
636 switch(func_get_arg(1)) {
643 case self::EXCEPTION:
645 case self::GROUP_START:
646 case self::GROUP_END:
647 $Type = func_get_arg(1);
650 $Label = func_get_arg(1);
654 if(func_num_args()==3) {
655 $Type = func_get_arg(2);
656 $Label = func_get_arg(1);
658 if(func_num_args()==4) {
659 $Type = func_get_arg(2);
660 $Label = func_get_arg(1);
661 $Options = func_get_arg(3);
663 throw $this->newException('Wrong number of arguments to fb() function!');
667 if(!$this->detectClientExtension()) {
672 $skipFinalObjectEncode = false;
674 if($Object instanceof Exception) {
676 $meta['file'] = $this->_escapeTraceFile($Object->getFile());
677 $meta['line'] = $Object->getLine();
679 $trace = $Object->getTrace();
680 if($Object instanceof ErrorException
681 && isset($trace[0]['function'])
682 && $trace[0]['function']=='errorHandler'
683 && isset($trace[0]['class'])
684 && $trace[0]['class']=='FirePHP') {
687 switch($Object->getSeverity()) {
688 case E_WARNING: $severity = 'E_WARNING'; break;
689 case E_NOTICE: $severity = 'E_NOTICE'; break;
690 case E_USER_ERROR: $severity = 'E_USER_ERROR'; break;
691 case E_USER_WARNING: $severity = 'E_USER_WARNING'; break;
692 case E_USER_NOTICE: $severity = 'E_USER_NOTICE'; break;
693 case E_STRICT: $severity = 'E_STRICT'; break;
694 case E_RECOVERABLE_ERROR: $severity = 'E_RECOVERABLE_ERROR'; break;
695 case E_DEPRECATED: $severity = 'E_DEPRECATED'; break;
696 case E_USER_DEPRECATED: $severity = 'E_USER_DEPRECATED'; break;
699 $Object = array('Class'=>get_class($Object),
700 'Message'=>$severity.': '.$Object->getMessage(),
701 'File'=>$this->_escapeTraceFile($Object->getFile()),
702 'Line'=>$Object->getLine(),
704 'Trace'=>$this->_escapeTrace(array_splice($trace,2)));
705 $skipFinalObjectEncode = true;
707 $Object = array('Class'=>get_class($Object),
708 'Message'=>$Object->getMessage(),
709 'File'=>$this->_escapeTraceFile($Object->getFile()),
710 'Line'=>$Object->getLine(),
712 'Trace'=>$this->_escapeTrace($trace));
713 $skipFinalObjectEncode = true;
715 $Type = self::EXCEPTION;
718 if($Type==self::TRACE) {
720 $trace = debug_backtrace();
721 if(!$trace) return false;
722 for( $i=0 ; $i<sizeof($trace) ; $i++ ) {
724 if(isset($trace[$i]['class'])
725 && isset($trace[$i]['file'])
726 && ($trace[$i]['class']=='FirePHP'
727 || $trace[$i]['class']=='FB')
728 && (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
729 || substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
730 /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
732 if(isset($trace[$i]['class'])
733 && isset($trace[$i+1]['file'])
734 && $trace[$i]['class']=='FirePHP'
735 && substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
738 if($trace[$i]['function']=='fb'
739 || $trace[$i]['function']=='trace'
740 || $trace[$i]['function']=='send') {
741 $Object = array('Class'=>isset($trace[$i]['class'])?$trace[$i]['class']:'',
742 'Type'=>isset($trace[$i]['type'])?$trace[$i]['type']:'',
743 'Function'=>isset($trace[$i]['function'])?$trace[$i]['function']:'',
744 'Message'=>$trace[$i]['args'][0],
745 'File'=>isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'',
746 'Line'=>isset($trace[$i]['line'])?$trace[$i]['line']:'',
747 'Args'=>isset($trace[$i]['args'])?$this->encodeObject($trace[$i]['args']):'',
748 'Trace'=>$this->_escapeTrace(array_splice($trace,$i+1)));
750 $skipFinalObjectEncode = true;
751 $meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
752 $meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
758 if($Type==self::TABLE) {
760 if(isset($Object[0]) && is_string($Object[0])) {
761 $Object[1] = $this->encodeTable($Object[1]);
763 $Object = $this->encodeTable($Object);
766 $skipFinalObjectEncode = true;
769 if($Type==self::GROUP_START) {
772 throw $this->newException('You must specify a label for the group!');
781 if($this->options['includeLineNumbers']) {
782 if(!isset($meta['file']) || !isset($meta['line'])) {
784 $trace = debug_backtrace();
785 for( $i=0 ; $trace && $i<sizeof($trace) ; $i++ ) {
787 if(isset($trace[$i]['class'])
788 && isset($trace[$i]['file'])
789 && ($trace[$i]['class']=='FirePHP'
790 || $trace[$i]['class']=='FB')
791 && (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
792 || substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
793 /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
795 if(isset($trace[$i]['class'])
796 && isset($trace[$i+1]['file'])
797 && $trace[$i]['class']=='FirePHP'
798 && substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
801 if(isset($trace[$i]['file'])
802 && substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php') {
805 $meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
806 $meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
813 unset($meta['file']);
814 unset($meta['line']);
817 $this->setHeader('X-Wf-Protocol-1','http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
818 $this->setHeader('X-Wf-1-Plugin-1','http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/'.self::VERSION);
820 $structure_index = 1;
821 if($Type==self::DUMP) {
822 $structure_index = 2;
823 $this->setHeader('X-Wf-1-Structure-2','http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1');
825 $this->setHeader('X-Wf-1-Structure-1','http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1');
828 if($Type==self::DUMP) {
829 $msg = '{"'.$Label.'":'.$this->jsonEncode($Object, $skipFinalObjectEncode).'}';
831 $msg_meta = $Options;
832 $msg_meta['Type'] = $Type;
834 $msg_meta['Label'] = $Label;
836 if(isset($meta['file']) && !isset($msg_meta['File'])) {
837 $msg_meta['File'] = $meta['file'];
839 if(isset($meta['line']) && !isset($msg_meta['Line'])) {
840 $msg_meta['Line'] = $meta['line'];
842 $msg = '['.$this->jsonEncode($msg_meta).','.$this->jsonEncode($Object, $skipFinalObjectEncode).']';
845 $parts = explode("\n",chunk_split($msg, 5000, "\n"));
847 for( $i=0 ; $i<count($parts) ; $i++) {
852 if(count($parts)>2) {
853 // Message needs to be split into multiple parts
854 $this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
855 (($i==0)?strlen($msg):'')
857 . (($i<count($parts)-2)?'\\':''));
859 $this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
860 strlen($part) . '|' . $part . '|');
863 $this->messageIndex++;
865 if ($this->messageIndex > 99999) {
866 throw $this->newException('Maximum number (99,999) of messages reached!');
871 $this->setHeader('X-Wf-1-Index',$this->messageIndex-1);
877 * Standardizes path for windows systems.
879 * @param string $Path
882 protected function _standardizePath($Path) {
883 return preg_replace('/\\\\+/','/',$Path);
887 * Escape trace path for windows systems
889 * @param array $Trace
892 protected function _escapeTrace($Trace) {
893 if(!$Trace) return $Trace;
894 for( $i=0 ; $i<sizeof($Trace) ; $i++ ) {
895 if(isset($Trace[$i]['file'])) {
896 $Trace[$i]['file'] = $this->_escapeTraceFile($Trace[$i]['file']);
898 if(isset($Trace[$i]['args'])) {
899 $Trace[$i]['args'] = $this->encodeObject($Trace[$i]['args']);
906 * Escape file information of trace for windows systems
908 * @param string $File
911 protected function _escapeTraceFile($File) {
912 /* Check if we have a windows filepath */
913 if(strpos($File,'\\')) {
914 /* First strip down to single \ */
916 $file = preg_replace('/\\\\+/','\\',$File);
926 * @param string $Name
927 * @param string_type $Value
929 protected function setHeader($Name, $Value) {
930 return header($Name.': '.$Value);
936 * @return string|false
938 protected function getUserAgent() {
939 if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
940 return $_SERVER['HTTP_USER_AGENT'];
944 * Returns a new exception
946 * @param string $Message
949 protected function newException($Message) {
950 return new Exception($Message);
954 * Encode an object into a JSON string
956 * Uses PHP's jeson_encode() if available
958 * @param object $Object The object to be encoded
959 * @return string The JSON string
961 public function jsonEncode($Object, $skipObjectEncode=false)
963 if(!$skipObjectEncode) {
964 $Object = $this->encodeObject($Object);
967 if(function_exists('json_encode')
968 && $this->options['useNativeJsonEncode']!=false) {
970 return json_encode($Object);
972 return $this->json_encode($Object);
977 * Encodes a table by encoding each row and column with encodeObject()
979 * @param array $Table The table to be encoded
982 protected function encodeTable($Table) {
984 if(!$Table) return $Table;
986 $new_table = array();
987 foreach($Table as $row) {
992 foreach($row as $item) {
993 $new_row[] = $this->encodeObject($item);
996 $new_table[] = $new_row;
1004 * Encodes an object including members with
1005 * protected and private visibility
1007 * @param Object $Object The object to be encoded
1008 * @param int $Depth The current traversal depth
1009 * @return array All members of the object
1011 protected function encodeObject($Object, $ObjectDepth = 1, $ArrayDepth = 1)
1015 if (is_resource($Object)) {
1017 return '** '.(string)$Object.' **';
1020 if (is_object($Object)) {
1022 if ($ObjectDepth > $this->options['maxObjectDepth']) {
1023 return '** Max Object Depth ('.$this->options['maxObjectDepth'].') **';
1026 foreach ($this->objectStack as $refVal) {
1027 if ($refVal === $Object) {
1028 return '** Recursion ('.get_class($Object).') **';
1031 array_push($this->objectStack, $Object);
1033 $return['__className'] = $class = get_class($Object);
1034 $class_lower = strtolower($class);
1036 $reflectionClass = new ReflectionClass($class);
1037 $properties = array();
1038 foreach( $reflectionClass->getProperties() as $property) {
1039 $properties[$property->getName()] = $property;
1042 $members = (array)$Object;
1044 foreach( $properties as $raw_name => $property ) {
1047 if($property->isStatic()) {
1048 $name = 'static:'.$name;
1050 if($property->isPublic()) {
1051 $name = 'public:'.$name;
1053 if($property->isPrivate()) {
1054 $name = 'private:'.$name;
1055 $raw_name = "\0".$class."\0".$raw_name;
1057 if($property->isProtected()) {
1058 $name = 'protected:'.$name;
1059 $raw_name = "\0".'*'."\0".$raw_name;
1062 if(!(isset($this->objectFilters[$class_lower])
1063 && is_array($this->objectFilters[$class_lower])
1064 && in_array($raw_name,$this->objectFilters[$class_lower]))) {
1066 if(array_key_exists($raw_name,$members)
1067 && !$property->isStatic()) {
1069 $return[$name] = $this->encodeObject($members[$raw_name], $ObjectDepth + 1, 1);
1072 if(method_exists($property,'setAccessible')) {
1073 $property->setAccessible(true);
1074 $return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1);
1076 if($property->isPublic()) {
1077 $return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1);
1079 $return[$name] = '** Need PHP 5.3 to get value **';
1083 $return[$name] = '** Excluded by Filter **';
1087 // Include all members that are not defined in the class
1088 // but exist in the object
1089 foreach( $members as $raw_name => $value ) {
1093 if ($name{0} == "\0") {
1094 $parts = explode("\0", $name);
1098 if(!isset($properties[$name])) {
1099 $name = 'undeclared:'.$name;
1101 if(!(isset($this->objectFilters[$class_lower])
1102 && is_array($this->objectFilters[$class_lower])
1103 && in_array($raw_name,$this->objectFilters[$class_lower]))) {
1105 $return[$name] = $this->encodeObject($value, $ObjectDepth + 1, 1);
1107 $return[$name] = '** Excluded by Filter **';
1112 array_pop($this->objectStack);
1114 } elseif (is_array($Object)) {
1116 if ($ArrayDepth > $this->options['maxArrayDepth']) {
1117 return '** Max Array Depth ('.$this->options['maxArrayDepth'].') **';
1120 foreach ($Object as $key => $val) {
1122 // Encoding the $GLOBALS PHP array causes an infinite loop
1123 // if the recursion is not reset here as it contains
1124 // a reference to itself. This is the only way I have come up
1125 // with to stop infinite recursion in this case.
1128 && array_key_exists('GLOBALS',$val)) {
1129 $val['GLOBALS'] = '** Recursion (GLOBALS) **';
1132 $return[$key] = $this->encodeObject($val, 1, $ArrayDepth + 1);
1135 if(self::is_utf8($Object)) {
1138 return utf8_encode($Object);
1145 * Returns true if $string is valid UTF-8 and false otherwise.
1147 * @param mixed $str String to be tested
1150 protected static function is_utf8($str) {
1154 for($i=0; $i<$len; $i++){
1157 if(($c >= 254)) return false;
1158 elseif($c >= 252) $bits=6;
1159 elseif($c >= 248) $bits=5;
1160 elseif($c >= 240) $bits=4;
1161 elseif($c >= 224) $bits=3;
1162 elseif($c >= 192) $bits=2;
1164 if(($i+$bits) > $len) return false;
1168 if($b < 128 || $b > 191) return false;
1177 * Converts to and from JSON format.
1179 * JSON (JavaScript Object Notation) is a lightweight data-interchange
1180 * format. It is easy for humans to read and write. It is easy for machines
1181 * to parse and generate. It is based on a subset of the JavaScript
1182 * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
1183 * This feature can also be found in Python. JSON is a text format that is
1184 * completely language independent but uses conventions that are familiar
1185 * to programmers of the C-family of languages, including C, C++, C#, Java,
1186 * JavaScript, Perl, TCL, and many others. These properties make JSON an
1187 * ideal data-interchange language.
1189 * This package provides a simple encoder and decoder for JSON notation. It
1190 * is intended for use with client-side Javascript applications that make
1191 * use of HTTPRequest to perform server communication functions - data can
1192 * be encoded into JSON notation for use in a client-side javascript, or
1193 * decoded from incoming Javascript requests. JSON format is native to
1194 * Javascript, and can be directly eval()'ed with no further parsing
1197 * All strings should be in ASCII or UTF-8 format!
1199 * LICENSE: Redistribution and use in source and binary forms, with or
1200 * without modification, are permitted provided that the following
1201 * conditions are met: Redistributions of source code must retain the
1202 * above copyright notice, this list of conditions and the following
1203 * disclaimer. Redistributions in binary form must reproduce the above
1204 * copyright notice, this list of conditions and the following disclaimer
1205 * in the documentation and/or other materials provided with the
1208 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
1209 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
1210 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
1211 * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
1212 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
1213 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
1214 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
1215 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
1216 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
1217 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
1221 * @package Services_JSON
1222 * @author Michal Migurski <mike-json@teczno.com>
1223 * @author Matt Knapp <mdknapp[at]gmail[dot]com>
1224 * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
1225 * @author Christoph Dorn <christoph@christophdorn.com>
1226 * @copyright 2005 Michal Migurski
1227 * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
1228 * @license http://www.opensource.org/licenses/bsd-license.php
1229 * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
1234 * Keep a list of objects as we descend into the array so we can detect recursion.
1236 private $json_objectStack = array();
1240 * convert a string from one UTF-8 char to one UTF-16 char
1242 * Normally should be handled by mb_convert_encoding, but
1243 * provides a slower PHP-only method for installations
1244 * that lack the multibye string extension.
1246 * @param string $utf8 UTF-8 character
1247 * @return string UTF-16 character
1250 private function json_utf82utf16($utf8)
1252 // oh please oh please oh please oh please oh please
1253 if(function_exists('mb_convert_encoding')) {
1254 return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
1257 switch(strlen($utf8)) {
1259 // this case should never be reached, because we are in ASCII range
1260 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1264 // return a UTF-16 character from a 2-byte UTF-8 char
1265 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1266 return chr(0x07 & (ord($utf8{0}) >> 2))
1267 . chr((0xC0 & (ord($utf8{0}) << 6))
1268 | (0x3F & ord($utf8{1})));
1271 // return a UTF-16 character from a 3-byte UTF-8 char
1272 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1273 return chr((0xF0 & (ord($utf8{0}) << 4))
1274 | (0x0F & (ord($utf8{1}) >> 2)))
1275 . chr((0xC0 & (ord($utf8{1}) << 6))
1276 | (0x7F & ord($utf8{2})));
1279 // ignoring UTF-32 for now, sorry
1284 * encodes an arbitrary variable into JSON format
1286 * @param mixed $var any number, boolean, string, array, or object to be encoded.
1287 * see argument 1 to Services_JSON() above for array-parsing behavior.
1288 * if var is a strng, note that encode() always expects it
1289 * to be in ASCII or UTF-8 format!
1291 * @return mixed JSON string representation of input var or an error if a problem occurs
1294 private function json_encode($var)
1297 if(is_object($var)) {
1298 if(in_array($var,$this->json_objectStack)) {
1299 return '"** Recursion **"';
1303 switch (gettype($var)) {
1305 return $var ? 'true' : 'false';
1315 return (float) $var;
1318 // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
1320 $strlen_var = strlen($var);
1323 * Iterate over every character in the string,
1324 * escaping with a slash or encoding to UTF-8 where necessary
1326 for ($c = 0; $c < $strlen_var; ++$c) {
1328 $ord_var_c = ord($var{$c});
1331 case $ord_var_c == 0x08:
1334 case $ord_var_c == 0x09:
1337 case $ord_var_c == 0x0A:
1340 case $ord_var_c == 0x0C:
1343 case $ord_var_c == 0x0D:
1347 case $ord_var_c == 0x22:
1348 case $ord_var_c == 0x2F:
1349 case $ord_var_c == 0x5C:
1350 // double quote, slash, slosh
1351 $ascii .= '\\'.$var{$c};
1354 case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
1355 // characters U-00000000 - U-0000007F (same as ASCII)
1359 case (($ord_var_c & 0xE0) == 0xC0):
1360 // characters U-00000080 - U-000007FF, mask 110XXXXX
1361 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1362 $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
1364 $utf16 = $this->json_utf82utf16($char);
1365 $ascii .= sprintf('\u%04s', bin2hex($utf16));
1368 case (($ord_var_c & 0xF0) == 0xE0):
1369 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
1370 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1371 $char = pack('C*', $ord_var_c,
1375 $utf16 = $this->json_utf82utf16($char);
1376 $ascii .= sprintf('\u%04s', bin2hex($utf16));
1379 case (($ord_var_c & 0xF8) == 0xF0):
1380 // characters U-00010000 - U-001FFFFF, mask 11110XXX
1381 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1382 $char = pack('C*', $ord_var_c,
1387 $utf16 = $this->json_utf82utf16($char);
1388 $ascii .= sprintf('\u%04s', bin2hex($utf16));
1391 case (($ord_var_c & 0xFC) == 0xF8):
1392 // characters U-00200000 - U-03FFFFFF, mask 111110XX
1393 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1394 $char = pack('C*', $ord_var_c,
1400 $utf16 = $this->json_utf82utf16($char);
1401 $ascii .= sprintf('\u%04s', bin2hex($utf16));
1404 case (($ord_var_c & 0xFE) == 0xFC):
1405 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
1406 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1407 $char = pack('C*', $ord_var_c,
1414 $utf16 = $this->json_utf82utf16($char);
1415 $ascii .= sprintf('\u%04s', bin2hex($utf16));
1420 return '"'.$ascii.'"';
1424 * As per JSON spec if any array key is not an integer
1425 * we must treat the the whole array as an object. We
1426 * also try to catch a sparsely populated associative
1427 * array with numeric keys here because some JS engines
1428 * will create an array with empty indexes up to
1429 * max_index which can cause memory issues and because
1430 * the keys, which may be relevant, will be remapped
1433 * As per the ECMA and JSON specification an object may
1434 * have any string as a property. Unfortunately due to
1435 * a hole in the ECMA specification if the key is a
1436 * ECMA reserved word or starts with a digit the
1437 * parameter is only accessible using ECMAScript's
1441 // treat as a JSON object
1442 if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
1444 $this->json_objectStack[] = $var;
1446 $properties = array_map(array($this, 'json_name_value'),
1448 array_values($var));
1450 array_pop($this->json_objectStack);
1452 foreach($properties as $property) {
1453 if($property instanceof Exception) {
1458 return '{' . join(',', $properties) . '}';
1461 $this->json_objectStack[] = $var;
1463 // treat it like a regular array
1464 $elements = array_map(array($this, 'json_encode'), $var);
1466 array_pop($this->json_objectStack);
1468 foreach($elements as $element) {
1469 if($element instanceof Exception) {
1474 return '[' . join(',', $elements) . ']';
1477 $vars = self::encodeObject($var);
1479 $this->json_objectStack[] = $var;
1481 $properties = array_map(array($this, 'json_name_value'),
1483 array_values($vars));
1485 array_pop($this->json_objectStack);
1487 foreach($properties as $property) {
1488 if($property instanceof Exception) {
1493 return '{' . join(',', $properties) . '}';
1501 * array-walking function for use in generating JSON-formatted name-value pairs
1503 * @param string $name name of key to use
1504 * @param mixed $value reference to an array element to be encoded
1506 * @return string JSON-formatted name-value pair, like '"name":value'
1509 private function json_name_value($name, $value)
1511 // Encoding the $GLOBALS PHP array causes an infinite loop
1512 // if the recursion is not reset here as it contains
1513 // a reference to itself. This is the only way I have come up
1514 // with to stop infinite recursion in this case.
1517 && array_key_exists('GLOBALS',$value)) {
1518 $value['GLOBALS'] = '** Recursion **';
1521 $encoded_value = $this->json_encode($value);
1523 if($encoded_value instanceof Exception) {
1524 return $encoded_value;
1527 return $this->json_encode(strval($name)) . ':' . $encoded_value;