FireShowPageTraceBehavior.class.php 68 KB

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