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 * This verion of FirePHPCore is for use with PHP4. If you do not require PHP4
40 * compatibility, it is suggested you use FirePHPCore.class.php instead.
42 * @copyright Copyright (C) 2007-2009 Christoph Dorn
43 * @author Christoph Dorn <christoph@christophdorn.com>
44 * @author Michael Day <manveru.alma@gmail.com>
45 * @license http://www.opensource.org/licenses/bsd-license.php
54 define('FirePHP_VERSION', '0.3');
59 * Logs a message to firebug console
63 define('FirePHP_LOG', 'LOG');
68 * Logs a message to firebug console and displays an info icon before the message
72 define('FirePHP_INFO', 'INFO');
77 * Logs a message to firebug console, displays a warning icon before the message and colors the line turquoise
81 define('FirePHP_WARN', 'WARN');
86 * Logs a message to firebug console, displays an error icon before the message and colors the line yellow. Also increments the firebug error count.
90 define('FirePHP_ERROR', 'ERROR');
93 * Dumps a variable to firebug's server panel
97 define('FirePHP_DUMP', 'DUMP');
100 * Displays a stack trace in firebug console
104 define('FirePHP_TRACE', 'TRACE');
107 * Displays a table in firebug console
111 define('FirePHP_TABLE', 'TABLE');
114 * Starts a group in firebug console
118 define('FirePHP_GROUP_START', 'GROUP_START');
121 * Ends a group in firebug console
125 define('FirePHP_GROUP_END', 'GROUP_END');
128 * Sends the given data to the FirePHP Firefox Extension.
129 * The data can be displayed in the Firebug Console or in the
130 * "Server" request tab.
132 * For more information see: http://www.firephp.org/
134 * @copyright Copyright (C) 2007-2009 Christoph Dorn
135 * @author Christoph Dorn <christoph@christophdorn.com>
136 * @author Michael Day <manveru.alma@gmail.com>
137 * @license http://www.opensource.org/licenses/bsd-license.php
142 * Wildfire protocol message index
146 var $messageIndex = 1;
149 * Options for the library
153 var $options = array('maxObjectDepth' => 10,
154 'maxArrayDepth' => 20,
155 'useNativeJsonEncode' => true,
156 'includeLineNumbers' => true);
159 * Filters used to exclude object members when encoding
163 var $objectFilters = array();
166 * A stack of objects used to detect recursion during object encoding
170 var $objectStack = array();
173 * Flag to enable/disable logging
180 * The object constructor
187 * When the object gets serialized only include specific object members.
192 return array('options','objectFilters','enabled');
196 * Gets singleton instance of FirePHP
198 * @param boolean $AutoCreate
201 function &getInstance($AutoCreate=false) {
202 global $FirePHP_Instance;
204 if($AutoCreate===true && !$FirePHP_Instance) {
205 $FirePHP_Instance = new FirePHP();
208 return $FirePHP_Instance;
212 * Enable and disable logging to Firebug
214 * @param boolean $Enabled TRUE to enable, FALSE to disable
217 function setEnabled($Enabled) {
218 $this->enabled = $Enabled;
222 * Check if logging is enabled
224 * @return boolean TRUE if enabled
226 function getEnabled() {
227 return $this->enabled;
231 * Specify a filter to be used when encoding an object
233 * Filters are used to exclude object members.
235 * @param string $Class The class name of the object
236 * @param array $Filter An array of members to exclude
239 function setObjectFilter($Class, $Filter) {
240 $this->objectFilters[strtolower($Class)] = $Filter;
244 * Set some options for the library
247 * - maxObjectDepth: The maximum depth to traverse objects (default: 10)
248 * - maxArrayDepth: The maximum depth to traverse arrays (default: 20)
249 * - useNativeJsonEncode: If true will use json_encode() (default: true)
250 * - includeLineNumbers: If true will include line numbers and filenames (default: true)
252 * @param array $Options The options to be set
255 function setOptions($Options) {
256 $this->options = array_merge($this->options,$Options);
260 * Get options from the library
262 * @return array The currently set options
264 function getOptions() {
265 return $this->options;
269 * Register FirePHP as your error handler
271 * Will use FirePHP to log each php error.
273 * @return mixed Returns a string containing the previously defined error handler (if any)
275 function registerErrorHandler()
277 //NOTE: The following errors will not be caught by this error handler:
278 // E_ERROR, E_PARSE, E_CORE_ERROR,
279 // E_CORE_WARNING, E_COMPILE_ERROR,
280 // E_COMPILE_WARNING, E_STRICT
282 return set_error_handler(array($this,'errorHandler'));
286 * FirePHP's error handler
288 * Logs each php error that will occur.
291 * @param string $errstr
292 * @param string $errfile
293 * @param int $errline
294 * @param array $errcontext
296 function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
298 global $FirePHP_Instance;
299 // Don't log error if error reporting is switched off
300 if (error_reporting() == 0) {
303 // Only log error for errors we are asking for
304 if (error_reporting() & $errno) {
305 $FirePHP_Instance->group($errstr);
306 $FirePHP_Instance->error("{$errfile}, line $errline");
307 $FirePHP_Instance->groupEnd();
312 * Register FirePHP driver as your assert callback
314 * @return mixed Returns the original setting
316 function registerAssertionHandler()
318 return assert_options(ASSERT_CALLBACK, array($this, 'assertionHandler'));
322 * FirePHP's assertion handler
324 * Logs all assertions to your firebug console and then stops the script.
326 * @param string $file File source of assertion
327 * @param int $line Line source of assertion
328 * @param mixed $code Assertion code
330 function assertionHandler($file, $line, $code)
332 $this->fb($code, 'Assertion Failed', FirePHP_ERROR, array('File'=>$file,'Line'=>$line));
336 * Set custom processor url for FirePHP
340 function setProcessorUrl($URL)
342 $this->setHeader('X-FirePHP-ProcessorURL', $URL);
346 * Set custom renderer url for FirePHP
350 function setRendererUrl($URL)
352 $this->setHeader('X-FirePHP-RendererURL', $URL);
356 * Start a group for following messages.
359 * Collapsed: [true|false]
360 * Color: [#RRGGBB|ColorName]
362 * @param string $Name
363 * @param array $Options OPTIONAL Instructions on how to log the group
367 function group($Name, $Options=null) {
370 trigger_error('You must specify a label for the group!');
374 if(!is_array($Options)) {
375 trigger_error('Options must be defined as an array!');
377 if(array_key_exists('Collapsed', $Options)) {
378 $Options['Collapsed'] = ($Options['Collapsed'])?'true':'false';
382 return $this->fb(null, $Name, FirePHP_GROUP_START, $Options);
386 * Ends a group you have started before
391 function groupEnd() {
392 return $this->fb(null, null, FirePHP_GROUP_END);
396 * Log object with label to firebug console
399 * @param mixes $Object
400 * @param string $Label
404 function log($Object, $Label=null) {
405 return $this->fb($Object, $Label, FirePHP_LOG);
409 * Log object with label to firebug console
412 * @param mixes $Object
413 * @param string $Label
417 function info($Object, $Label=null) {
418 return $this->fb($Object, $Label, FirePHP_INFO);
422 * Log object with label to firebug console
425 * @param mixes $Object
426 * @param string $Label
430 function warn($Object, $Label=null) {
431 return $this->fb($Object, $Label, FirePHP_WARN);
435 * Log object with label to firebug console
437 * @see FirePHP::ERROR
438 * @param mixes $Object
439 * @param string $Label
443 function error($Object, $Label=null) {
444 return $this->fb($Object, $Label, FirePHP_ERROR);
448 * Dumps key and variable to firebug server panel
452 * @param mixed $Variable
456 function dump($Key, $Variable) {
457 return $this->fb($Variable, $Key, FirePHP_DUMP);
461 * Log a trace in the firebug console
463 * @see FirePHP::TRACE
464 * @param string $Label
468 function trace($Label) {
469 return $this->fb($Label, FirePHP_TRACE);
473 * Log a table in the firebug console
475 * @see FirePHP::TABLE
476 * @param string $Label
477 * @param string $Table
481 function table($Label, $Table) {
482 return $this->fb($Table, $Label, FirePHP_TABLE);
486 * Check if FirePHP is installed on client
490 function detectClientExtension() {
491 /* Check if FirePHP is installed on client */
492 if(!@preg_match_all('/\sFirePHP\/([\.|\d]*)\s?/si',$this->getUserAgent(),$m) ||
493 !version_compare($m[1][0],'0.0.6','>=')) {
500 * Log varible to Firebug
502 * @see http://www.firephp.org/Wiki/Reference/Fb
503 * @param mixed $Object The variable to be logged
504 * @return true Return TRUE if message was added to headers, FALSE otherwise
507 function fb($Object) {
509 if(!$this->enabled) {
513 if (headers_sent($filename, $linenum)) {
514 trigger_error('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.');
521 if(func_num_args()==1) {
523 if(func_num_args()==2) {
524 switch(func_get_arg(1)) {
532 case FirePHP_GROUP_START:
533 case FirePHP_GROUP_END:
534 $Type = func_get_arg(1);
537 $Label = func_get_arg(1);
541 if(func_num_args()==3) {
542 $Type = func_get_arg(2);
543 $Label = func_get_arg(1);
545 if(func_num_args()==4) {
546 $Type = func_get_arg(2);
547 $Label = func_get_arg(1);
548 $Options = func_get_arg(3);
550 trigger_error('Wrong number of arguments to fb() function!');
554 if(!$this->detectClientExtension()) {
559 $skipFinalObjectEncode = false;
561 if($Type==FirePHP_TRACE) {
563 $trace = debug_backtrace();
564 if(!$trace) return false;
565 for( $i=0 ; $i<sizeof($trace) ; $i++ ) {
567 if(isset($trace[$i]['class'])
568 && isset($trace[$i]['file'])
569 && ($trace[$i]['class']=='FirePHP'
570 || $trace[$i]['class']=='FB')
571 && (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
572 || substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
573 /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
575 if(isset($trace[$i]['class'])
576 && isset($trace[$i+1]['file'])
577 && $trace[$i]['class']=='FirePHP'
578 && substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
581 if($trace[$i]['function']=='fb'
582 || $trace[$i]['function']=='trace'
583 || $trace[$i]['function']=='send') {
584 $Object = array('Class'=>isset($trace[$i]['class'])?$trace[$i]['class']:'',
585 'Type'=>isset($trace[$i]['type'])?$trace[$i]['type']:'',
586 'Function'=>isset($trace[$i]['function'])?$trace[$i]['function']:'',
587 'Message'=>$trace[$i]['args'][0],
588 'File'=>isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'',
589 'Line'=>isset($trace[$i]['line'])?$trace[$i]['line']:'',
590 'Args'=>isset($trace[$i]['args'])?$this->encodeObject($trace[$i]['args']):'',
591 'Trace'=>$this->_escapeTrace(array_splice($trace,$i+1)));
593 $skipFinalObjectEncode = true;
594 $meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
595 $meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
601 if($Type==FirePHP_TABLE) {
603 if(isset($Object[0]) && is_string($Object[0])) {
604 $Object[1] = $this->encodeTable($Object[1]);
606 $Object = $this->encodeTable($Object);
609 $skipFinalObjectEncode = true;
612 if($Type==FirePHP_GROUP_START) {
615 trigger_error('You must specify a label for the group!');
623 if($this->options['includeLineNumbers']) {
624 if(!isset($meta['file']) || !isset($meta['line'])) {
626 $trace = debug_backtrace();
627 for( $i=0 ; $trace && $i<sizeof($trace) ; $i++ ) {
629 if(isset($trace[$i]['class'])
630 && isset($trace[$i]['file'])
631 && ($trace[$i]['class']=='FirePHP'
632 || $trace[$i]['class']=='FB')
633 && (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
634 || substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
635 /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
637 if(isset($trace[$i]['class'])
638 && isset($trace[$i+1]['file'])
639 && $trace[$i]['class']=='FirePHP'
640 && substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
643 if(isset($trace[$i]['file'])
644 && substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php') {
647 $meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
648 $meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
655 unset($meta['file']);
656 unset($meta['line']);
659 $this->setHeader('X-Wf-Protocol-1','http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
660 $this->setHeader('X-Wf-1-Plugin-1','http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/'.FirePHP_VERSION);
662 $structure_index = 1;
663 if($Type==FirePHP_DUMP) {
664 $structure_index = 2;
665 $this->setHeader('X-Wf-1-Structure-2','http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1');
667 $this->setHeader('X-Wf-1-Structure-1','http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1');
670 if($Type==FirePHP_DUMP) {
671 $msg = '{"'.$Label.'":'.$this->jsonEncode($Object, $skipFinalObjectEncode).'}';
673 $msg_meta = $Options;
674 $msg_meta['Type'] = $Type;
676 $msg_meta['Label'] = $Label;
678 if(isset($meta['file']) && !isset($msg_meta['File'])) {
679 $msg_meta['File'] = $meta['file'];
681 if(isset($meta['line']) && !isset($msg_meta['Line'])) {
682 $msg_meta['Line'] = $meta['line'];
684 $msg = '['.$this->jsonEncode($msg_meta).','.$this->jsonEncode($Object, $skipFinalObjectEncode).']';
687 $parts = explode("\n",chunk_split($msg, 5000, "\n"));
689 for( $i=0 ; $i<count($parts) ; $i++) {
694 if(count($parts)>2) {
695 // Message needs to be split into multiple parts
696 $this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
697 (($i==0)?strlen($msg):'')
699 . (($i<count($parts)-2)?'\\':''));
701 $this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
702 strlen($part) . '|' . $part . '|');
705 $this->messageIndex++;
707 if ($this->messageIndex > 99999) {
708 trigger_error('Maximum number (99,999) of messages reached!');
713 $this->setHeader('X-Wf-1-Index',$this->messageIndex-1);
720 * Standardizes path for windows systems.
722 * @param string $Path
725 function _standardizePath($Path) {
726 return preg_replace('/\\\\+/','/',$Path);
730 * Escape trace path for windows systems
732 * @param array $Trace
735 function _escapeTrace($Trace) {
736 if(!$Trace) return $Trace;
737 for( $i=0 ; $i<sizeof($Trace) ; $i++ ) {
738 if(isset($Trace[$i]['file'])) {
739 $Trace[$i]['file'] = $this->_escapeTraceFile($Trace[$i]['file']);
741 if(isset($Trace[$i]['args'])) {
742 $Trace[$i]['args'] = $this->encodeObject($Trace[$i]['args']);
749 * Escape file information of trace for windows systems
751 * @param string $File
754 function _escapeTraceFile($File) {
755 /* Check if we have a windows filepath */
756 if(strpos($File,'\\')) {
757 /* First strip down to single \ */
759 $file = preg_replace('/\\\\+/','\\',$File);
769 * @param string $Name
770 * @param string_type $Value
772 function setHeader($Name, $Value) {
773 return header($Name.': '.$Value);
779 * @return string|false
781 function getUserAgent() {
782 if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
783 return $_SERVER['HTTP_USER_AGENT'];
787 * Encode an object into a JSON string
789 * Uses PHP's jeson_encode() if available
791 * @param object $Object The object to be encoded
792 * @return string The JSON string
794 function jsonEncode($Object, $skipObjectEncode=false)
796 if(!$skipObjectEncode) {
797 $Object = $this->encodeObject($Object);
800 if(function_exists('json_encode')
801 && $this->options['useNativeJsonEncode']!=false) {
803 return json_encode($Object);
805 return $this->json_encode($Object);
810 * Encodes a table by encoding each row and column with encodeObject()
812 * @param array $Table The table to be encoded
815 function encodeTable($Table) {
817 if(!$Table) return $Table;
819 $new_table = array();
820 foreach($Table as $row) {
825 foreach($row as $item) {
826 $new_row[] = $this->encodeObject($item);
829 $new_table[] = $new_row;
839 * @param Object $Object The object to be encoded
840 * @param int $Depth The current traversal depth
841 * @return array All members of the object
843 function encodeObject($Object, $ObjectDepth = 1, $ArrayDepth = 1)
847 if (is_resource($Object)) {
849 return '** '.(string)$Object.' **';
852 if (is_object($Object)) {
854 if ($ObjectDepth > $this->options['maxObjectDepth']) {
855 return '** Max Object Depth ('.$this->options['maxObjectDepth'].') **';
858 foreach ($this->objectStack as $refVal) {
859 if ($refVal === $Object) {
860 return '** Recursion ('.get_class($Object).') **';
863 array_push($this->objectStack, $Object);
865 $return['__className'] = $class = get_class($Object);
866 $class_lower = strtolower($class);
868 $members = (array)$Object;
870 // Include all members that are not defined in the class
871 // but exist in the object
872 foreach( $members as $raw_name => $value ) {
876 if ($name{0} == "\0") {
877 $parts = explode("\0", $name);
881 if(!isset($properties[$name])) {
882 $name = 'undeclared:'.$name;
884 if(!(isset($this->objectFilters[$class_lower])
885 && is_array($this->objectFilters[$class_lower])
886 && in_array($raw_name,$this->objectFilters[$class_lower]))) {
888 $return[$name] = $this->encodeObject($value, $ObjectDepth + 1, 1);
890 $return[$name] = '** Excluded by Filter **';
895 array_pop($this->objectStack);
897 } elseif (is_array($Object)) {
899 if ($ArrayDepth > $this->options['maxArrayDepth']) {
900 return '** Max Array Depth ('.$this->options['maxArrayDepth'].') **';
903 foreach ($Object as $key => $val) {
905 // Encoding the $GLOBALS PHP array causes an infinite loop
906 // if the recursion is not reset here as it contains
907 // a reference to itself. This is the only way I have come up
908 // with to stop infinite recursion in this case.
911 && array_key_exists('GLOBALS',$val)) {
912 $val['GLOBALS'] = '** Recursion (GLOBALS) **';
915 $return[$key] = $this->encodeObject($val, 1, $ArrayDepth + 1);
918 if($this->is_utf8($Object)) {
921 return utf8_encode($Object);
929 * Returns true if $string is valid UTF-8 and false otherwise.
931 * @param mixed $str String to be tested
934 function is_utf8($str) {
938 for($i=0; $i<$len; $i++){
941 if(($c >= 254)) return false;
942 elseif($c >= 252) $bits=6;
943 elseif($c >= 248) $bits=5;
944 elseif($c >= 240) $bits=4;
945 elseif($c >= 224) $bits=3;
946 elseif($c >= 192) $bits=2;
948 if(($i+$bits) > $len) return false;
952 if($b < 128 || $b > 191) return false;
961 * Converts to and from JSON format.
963 * JSON (JavaScript Object Notation) is a lightweight data-interchange
964 * format. It is easy for humans to read and write. It is easy for machines
965 * to parse and generate. It is based on a subset of the JavaScript
966 * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
967 * This feature can also be found in Python. JSON is a text format that is
968 * completely language independent but uses conventions that are familiar
969 * to programmers of the C-family of languages, including C, C++, C#, Java,
970 * JavaScript, Perl, TCL, and many others. These properties make JSON an
971 * ideal data-interchange language.
973 * This package provides a simple encoder and decoder for JSON notation. It
974 * is intended for use with client-side Javascript applications that make
975 * use of HTTPRequest to perform server communication functions - data can
976 * be encoded into JSON notation for use in a client-side javascript, or
977 * decoded from incoming Javascript requests. JSON format is native to
978 * Javascript, and can be directly eval()'ed with no further parsing
981 * All strings should be in ASCII or UTF-8 format!
983 * LICENSE: Redistribution and use in source and binary forms, with or
984 * without modification, are permitted provided that the following
985 * conditions are met: Redistributions of source code must retain the
986 * above copyright notice, this list of conditions and the following
987 * disclaimer. Redistributions in binary form must reproduce the above
988 * copyright notice, this list of conditions and the following disclaimer
989 * in the documentation and/or other materials provided with the
992 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
993 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
994 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
995 * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
996 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
997 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
998 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
999 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
1000 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
1001 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
1005 * @package Services_JSON
1006 * @author Michal Migurski <mike-json@teczno.com>
1007 * @author Matt Knapp <mdknapp[at]gmail[dot]com>
1008 * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
1009 * @author Christoph Dorn <christoph@christophdorn.com>
1010 * @copyright 2005 Michal Migurski
1011 * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
1012 * @license http://www.opensource.org/licenses/bsd-license.php
1013 * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
1018 * Keep a list of objects as we descend into the array so we can detect recursion.
1020 var $json_objectStack = array();
1024 * convert a string from one UTF-8 char to one UTF-16 char
1026 * Normally should be handled by mb_convert_encoding, but
1027 * provides a slower PHP-only method for installations
1028 * that lack the multibye string extension.
1030 * @param string $utf8 UTF-8 character
1031 * @return string UTF-16 character
1034 function json_utf82utf16($utf8)
1036 // oh please oh please oh please oh please oh please
1037 if(function_exists('mb_convert_encoding')) {
1038 return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
1041 switch(strlen($utf8)) {
1043 // this case should never be reached, because we are in ASCII range
1044 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1048 // return a UTF-16 character from a 2-byte UTF-8 char
1049 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1050 return chr(0x07 & (ord($utf8{0}) >> 2))
1051 . chr((0xC0 & (ord($utf8{0}) << 6))
1052 | (0x3F & ord($utf8{1})));
1055 // return a UTF-16 character from a 3-byte UTF-8 char
1056 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1057 return chr((0xF0 & (ord($utf8{0}) << 4))
1058 | (0x0F & (ord($utf8{1}) >> 2)))
1059 . chr((0xC0 & (ord($utf8{1}) << 6))
1060 | (0x7F & ord($utf8{2})));
1063 // ignoring UTF-32 for now, sorry
1068 * encodes an arbitrary variable into JSON format
1070 * @param mixed $var any number, boolean, string, array, or object to be encoded.
1071 * see argument 1 to Services_JSON() above for array-parsing behavior.
1072 * if var is a strng, note that encode() always expects it
1073 * to be in ASCII or UTF-8 format!
1075 * @return mixed JSON string representation of input var or an error if a problem occurs
1078 function json_encode($var)
1081 if(is_object($var)) {
1082 if(in_array($var,$this->json_objectStack)) {
1083 return '"** Recursion **"';
1087 switch (gettype($var)) {
1089 return $var ? 'true' : 'false';
1099 return (float) $var;
1102 // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
1104 $strlen_var = strlen($var);
1107 * Iterate over every character in the string,
1108 * escaping with a slash or encoding to UTF-8 where necessary
1110 for ($c = 0; $c < $strlen_var; ++$c) {
1112 $ord_var_c = ord($var{$c});
1115 case $ord_var_c == 0x08:
1118 case $ord_var_c == 0x09:
1121 case $ord_var_c == 0x0A:
1124 case $ord_var_c == 0x0C:
1127 case $ord_var_c == 0x0D:
1131 case $ord_var_c == 0x22:
1132 case $ord_var_c == 0x2F:
1133 case $ord_var_c == 0x5C:
1134 // double quote, slash, slosh
1135 $ascii .= '\\'.$var{$c};
1138 case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
1139 // characters U-00000000 - U-0000007F (same as ASCII)
1143 case (($ord_var_c & 0xE0) == 0xC0):
1144 // characters U-00000080 - U-000007FF, mask 110XXXXX
1145 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1146 $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
1148 $utf16 = $this->json_utf82utf16($char);
1149 $ascii .= sprintf('\u%04s', bin2hex($utf16));
1152 case (($ord_var_c & 0xF0) == 0xE0):
1153 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
1154 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1155 $char = pack('C*', $ord_var_c,
1159 $utf16 = $this->json_utf82utf16($char);
1160 $ascii .= sprintf('\u%04s', bin2hex($utf16));
1163 case (($ord_var_c & 0xF8) == 0xF0):
1164 // characters U-00010000 - U-001FFFFF, mask 11110XXX
1165 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1166 $char = pack('C*', $ord_var_c,
1171 $utf16 = $this->json_utf82utf16($char);
1172 $ascii .= sprintf('\u%04s', bin2hex($utf16));
1175 case (($ord_var_c & 0xFC) == 0xF8):
1176 // characters U-00200000 - U-03FFFFFF, mask 111110XX
1177 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1178 $char = pack('C*', $ord_var_c,
1184 $utf16 = $this->json_utf82utf16($char);
1185 $ascii .= sprintf('\u%04s', bin2hex($utf16));
1188 case (($ord_var_c & 0xFE) == 0xFC):
1189 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
1190 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
1191 $char = pack('C*', $ord_var_c,
1198 $utf16 = $this->json_utf82utf16($char);
1199 $ascii .= sprintf('\u%04s', bin2hex($utf16));
1204 return '"'.$ascii.'"';
1208 * As per JSON spec if any array key is not an integer
1209 * we must treat the the whole array as an object. We
1210 * also try to catch a sparsely populated associative
1211 * array with numeric keys here because some JS engines
1212 * will create an array with empty indexes up to
1213 * max_index which can cause memory issues and because
1214 * the keys, which may be relevant, will be remapped
1217 * As per the ECMA and JSON specification an object may
1218 * have any string as a property. Unfortunately due to
1219 * a hole in the ECMA specification if the key is a
1220 * ECMA reserved word or starts with a digit the
1221 * parameter is only accessible using ECMAScript's
1225 // treat as a JSON object
1226 if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
1228 $this->json_objectStack[] = $var;
1230 $properties = array_map(array($this, 'json_name_value'),
1232 array_values($var));
1234 array_pop($this->json_objectStack);
1236 return '{' . join(',', $properties) . '}';
1239 $this->json_objectStack[] = $var;
1241 // treat it like a regular array
1242 $elements = array_map(array($this, 'json_encode'), $var);
1244 array_pop($this->json_objectStack);
1246 return '[' . join(',', $elements) . ']';
1249 $vars = FirePHP::encodeObject($var);
1251 $this->json_objectStack[] = $var;
1253 $properties = array_map(array($this, 'json_name_value'),
1255 array_values($vars));
1257 array_pop($this->json_objectStack);
1259 return '{' . join(',', $properties) . '}';
1267 * array-walking function for use in generating JSON-formatted name-value pairs
1269 * @param string $name name of key to use
1270 * @param mixed $value reference to an array element to be encoded
1272 * @return string JSON-formatted name-value pair, like '"name":value'
1275 function json_name_value($name, $value)
1277 // Encoding the $GLOBALS PHP array causes an infinite loop
1278 // if the recursion is not reset here as it contains
1279 // a reference to itself. This is the only way I have come up
1280 // with to stop infinite recursion in this case.
1283 && array_key_exists('GLOBALS',$value)) {
1284 $value['GLOBALS'] = '** Recursion **';
1287 $encoded_value = $this->json_encode($value);
1289 return $this->json_encode(strval($name)) . ':' . $encoded_value;