Source for file Debug.php

Documentation is available at Debug.php

  1. 1: <?php
  2. 2:  
  3. 3: /**
  4. 4:  * Nette Framework
  5. 5:  *
  6. 6:  * Copyright (c) 2004, 2009 David Grudl (http://davidgrudl.com)
  7. 7:  *
  8. 8:  * This source file is subject to the "Nette license" that is bundled
  9. 9:  * with this package in the file license.txt.
  10. 10:  *
  11. 11:  * For more information please see https://nette.org
  12. 12:  *
  13. 13:  * @copyright  Copyright (c) 2004, 2009 David Grudl
  14. 14:  * @license    https://nette.org/license  Nette license
  15. 15:  * @link       https://nette.org
  16. 16:  * @category   Nette
  17. 17:  * @package    Nette
  18. 18:  * @version    $Id$
  19. 19:  */
  20. 20:  
  21. 21:  
  22. 22:  
  23. 23: require_once dirname(__FILE__'/compatibility.php';
  24. 24:  
  25. 25: require_once dirname(__FILE__'/exceptions.php';
  26. 26:  
  27. 27: require_once dirname(__FILE__'/Framework.php';
  28. 28:  
  29. 29:  
  30. 30:  
  31. 31: /**
  32. 32:  * Debug static class.
  33. 33:  *
  34. 34:  * @author     David Grudl
  35. 35:  * @copyright  Copyright (c) 2004, 2009 David Grudl
  36. 36:  * @package    Nette
  37. 37:  */
  38. 38: final class Debug
  39. 39: {
  40. 40:     /**#@+ server modes {@link Debug::enable()} */
  41. 41:     const DEVELOPMENT FALSE;
  42. 42:     const PRODUCTION TRUE;
  43. 43:     const DETECT NULL;
  44. 44:     /**#@-*/
  45. 45:  
  46. 46:     /** @var array  free counters for your usage */
  47. 47:     public static $counters array();
  48. 48:  
  49. 49:     /** @deprecated {@link Debug::$consoleMode} */
  50. 50:     public static $html;
  51. 51:  
  52. 52:     /** @var bool determines whether a server is running in production mode */
  53. 53:     public static $productionMode;
  54. 54:  
  55. 55:     /** @var bool determines whether a server is running in console mode */
  56. 56:     public static $consoleMode;
  57. 57:  
  58. 58:     /** @var int  how many nested levels of array/object properties display {@link Debug::dump()} */
  59. 59:     public static $maxDepth 3;
  60. 60:  
  61. 61:     /** @var int  how long strings display {@link Debug::dump()} */
  62. 62:     public static $maxLen 150;
  63. 63:  
  64. 64:     /** @var int  sensitive keys not displayed by {@link Debug::dump()} when {@link Debug::$productionMode} in on */
  65. 65:     public static $keysToHide array('password''passwd''pass''pwd''creditcard''credit card''cc''pin');
  66. 66:  
  67. 67:     /** @var bool {@link Debug::enable()} */
  68. 68:     private static $enabled FALSE;
  69. 69:  
  70. 70:     /** @var bool {@link Debug::enableProfiler()} */
  71. 71:     private static $enabledProfiler FALSE;
  72. 72:  
  73. 73:     /** @var bool is Firebug & FirePHP detected? */
  74. 74:     private static $firebugDetected;
  75. 75:  
  76. 76:     /** @var bool is AJAX request detected? */
  77. 77:     private static $ajaxDetected;
  78. 78:  
  79. 79:     /** @var string  name of the file where script errors should be logged */
  80. 80:     private static $logFile;
  81. 81:  
  82. 82:     /** @var resource */
  83. 83:     private static $logHandle;
  84. 84:  
  85. 85:     /** @var bool  send e-mail notifications of errors? */
  86. 86:     private static $sendEmails;
  87. 87:  
  88. 88:     /** @var string  e-mail headers & body */
  89. 89:     private static $emailHeaders array(
  90. 90:         'To' => '',
  91. 91:         'From' => 'noreply@%host%',
  92. 92:         'X-Mailer' => 'Nette Framework',
  93. 93:         'Subject' => 'PHP: An error occurred on the server %host%',
  94. 94:         'Body' => '[%date%] %message%',
  95. 95:     );
  96. 96:  
  97. 97:     /** @var callback */
  98. 98:     public static $mailer array(__CLASS__'defaultMailer');
  99. 99:  
  100. 100:     /** @deprecated */
  101. 101:     public static $emailProbability;
  102. 102:  
  103. 103:     /** @var array  */
  104. 104:     private static $colophons array(array(__CLASS__'getDefaultColophons'));
  105. 105:  
  106. 106:     /** @var array  */
  107. 107:     private static $keyFilter array();
  108. 108:  
  109. 109:     /** @var int */
  110. 110:     public static $time;
  111. 111:  
  112. 112:     /**#@+ FirePHP log priority */
  113. 113:     const LOG 'LOG';
  114. 114:     const INFO 'INFO';
  115. 115:     const WARN 'WARN';
  116. 116:     const ERROR 'ERROR';
  117. 117:     const TRACE 'TRACE';
  118. 118:     const EXCEPTION 'EXCEPTION';
  119. 119:     const GROUP_START 'GROUP_START';
  120. 120:     const GROUP_END 'GROUP_END';
  121. 121:     /**#@-*/
  122. 122:  
  123. 123:  
  124. 124:  
  125. 125:     /**
  126. 126:      * Static class - cannot be instantiated.
  127. 127:      */
  128. 128:     final public function __construct()
  129. 129:     {
  130. 130:         throw new LogicException("Cannot instantiate static class " get_class($this));
  131. 131:     }
  132. 132:  
  133. 133:  
  134. 134:  
  135. 135:     /**
  136. 136:      * Static class constructor.
  137. 137:      */
  138. 138:     public static function init()
  139. 139:     {
  140. 140:         self::$time microtime(TRUE);
  141. 141:         self::$consoleMode PHP_SAPI === 'cli';
  142. 142:         self::$productionMode self::DETECT;
  143. 143:         self::$firebugDetected isset($_SERVER['HTTP_USER_AGENT']&& strpos($_SERVER['HTTP_USER_AGENT']'FirePHP/');
  144. 144:         self::$ajaxDetected isset($_SERVER['HTTP_X_REQUESTED_WITH']&& $_SERVER['HTTP_X_REQUESTED_WITH'=== 'XMLHttpRequest';
  145. 145:     }
  146. 146:  
  147. 147:  
  148. 148:  
  149. 149:     /********************* useful tools ****************d*g**/
  150. 150:  
  151. 151:  
  152. 152:  
  153. 153:     /**
  154. 154:      * Dumps information about a variable in readable format.
  155. 155:      *
  156. 156:      * @param  mixed  variable to dump.
  157. 157:      * @param  bool   return output instead of printing it? (bypasses $productionMode)
  158. 158:      * @return mixed  variable or dump
  159. 159:      */
  160. 160:     public static function dump($var$return FALSE)
  161. 161:     {
  162. 162:         if (!$return && self::$productionMode{
  163. 163:             return $var;
  164. 164:         }
  165. 165:  
  166. 166:         //self::$keyFilter = self::$productionMode ? array_change_key_case(array_flip(self::$keysToHide), CASE_LOWER) : NULL;
  167. 167:  
  168. 168:         $output "<pre class=\"dump\">" self::_dump($var0"</pre>\n";
  169. 169:  
  170. 170:         if (self::$consoleMode{
  171. 171:             $output htmlspecialchars_decode(strip_tags($output)ENT_NOQUOTES);
  172. 172:         }
  173. 173:  
  174. 174:         if ($return{
  175. 175:             return $output;
  176. 176:  
  177. 177:         else {
  178. 178:             echo $output;
  179. 179:             return $var;
  180. 180:         }
  181. 181:     }
  182. 182:  
  183. 183:  
  184. 184:  
  185. 185:     /**
  186. 186:      * Internal dump() implementation.
  187. 187:      *
  188. 188:      * @param  mixed  variable to dump
  189. 189:      * @param  int    current recursion level
  190. 190:      * @return string 
  191. 191:      */
  192. 192:     private static function _dump(&$var$level)
  193. 193:     {
  194. 194:         if (is_bool($var)) {
  195. 195:             return "<span>bool</span>(" ($var 'TRUE' 'FALSE'")\n";
  196. 196:  
  197. 197:         elseif ($var === NULL{
  198. 198:             return "<span>NULL</span>\n";
  199. 199:  
  200. 200:         elseif (is_int($var)) {
  201. 201:             return "<span>int</span>($var)\n";
  202. 202:  
  203. 203:         elseif (is_float($var)) {
  204. 204:             return "<span>float</span>($var)\n";
  205. 205:  
  206. 206:         elseif (is_string($var)) {
  207. 207:             if (self::$maxLen && strlen($varself::$maxLen{
  208. 208:                 $s htmlSpecialChars(substr($var0self::$maxLen)ENT_NOQUOTES' ... ';
  209. 209:             else {
  210. 210:                 $s htmlSpecialChars($varENT_NOQUOTES);
  211. 211:             }
  212. 212:             return "<span>string</span>(" strlen($var") \"$s\"\n";
  213. 213:  
  214. 214:         elseif (is_array($var)) {
  215. 215:             $s "<span>array</span>(" count($var") {\n";
  216. 216:             $space str_repeat('  '$level);
  217. 217:  
  218. 218:             static $marker;
  219. 219:             if ($marker === NULL$marker uniqid("\x00"TRUE);
  220. 220:             if (isset($var[$marker])) {
  221. 221:                 $s .= "$space  *RECURSION*\n";
  222. 222:  
  223. 223:             elseif ($level self::$maxDepth || !self::$maxDepth{
  224. 224:                 $var[$marker0;
  225. 225:                 foreach ($var as $k => &$v{
  226. 226:                     if ($k === $markercontinue;
  227. 227:                     $s .= "$space  (is_int($k$k "\"$k\""" => ";
  228. 228:                     if (self::$keyFilter && is_string($v&& isset(self::$keyFilter[strtolower($k)])) {
  229. 229:                         $s .= "<span>string</span>(?) <i>*** hidden ***</i>\n";
  230. 230:                     else {
  231. 231:                         $s .= self::_dump($v$level 1);
  232. 232:                     }
  233. 233:                 }
  234. 234:                 unset($var[$marker]);
  235. 235:             else {
  236. 236:                 $s .= "$space  ...\n";
  237. 237:             }
  238. 238:             return $s "$space}\n";
  239. 239:  
  240. 240:         elseif (is_object($var)) {
  241. 241:             $arr = (array) $var;
  242. 242:             $s "<span>object</span>(" get_class($var") (" count($arr") {\n";
  243. 243:             $space str_repeat('  '$level);
  244. 244:  
  245. 245:             static $list array();
  246. 246:             if (in_array($var$listTRUE)) {
  247. 247:                 $s .= "$space  *RECURSION*\n";
  248. 248:  
  249. 249:             elseif ($level self::$maxDepth || !self::$maxDepth{
  250. 250:                 $list[$var;
  251. 251:                 foreach ($arr as $k => &$v{
  252. 252:                     $m '';
  253. 253:                     if ($k[0=== "\x00"{
  254. 254:                         $m $k[1=== '*' ' <span>protected</span>' ' <span>private</span>';
  255. 255:                         $k substr($kstrrpos($k"\x00"1);
  256. 256:                     }
  257. 257:                     $s .= "$space  \"$k\"$m => ";
  258. 258:                     if (self::$keyFilter && is_string($v&& isset(self::$keyFilter[strtolower($k)])) {
  259. 259:                         $s .= "<span>string</span>(?) <i>*** hidden ***</i>\n";
  260. 260:                     else {
  261. 261:                         $s .= self::_dump($v$level 1);
  262. 262:                     }
  263. 263:                 }
  264. 264:                 array_pop($list);
  265. 265:             else {
  266. 266:                 $s .= "$space  ...\n";
  267. 267:             }
  268. 268:             return $s "$space}\n";
  269. 269:  
  270. 270:         elseif (is_resource($var)) {
  271. 271:             return "<span>resource of type</span>(" get_resource_type($var")\n";
  272. 272:  
  273. 273:         else {
  274. 274:             return "<span>unknown type</span>\n";
  275. 275:         }
  276. 276:     }
  277. 277:  
  278. 278:  
  279. 279:  
  280. 280:     /**
  281. 281:      * Starts/stops stopwatch.
  282. 282:      * @param  string  name
  283. 283:      * @return elapsed seconds
  284. 284:      */
  285. 285:     public static function timer($name NULL)
  286. 286:     {
  287. 287:         static $time array();
  288. 288:         $now microtime(TRUE);
  289. 289:         $delta isset($time[$name]$now $time[$name0;
  290. 290:         $time[$name$now;
  291. 291:         return $delta;
  292. 292:     }
  293. 293:  
  294. 294:  
  295. 295:  
  296. 296:     /********************* errors and exceptions reporing ****************d*g**/
  297. 297:  
  298. 298:  
  299. 299:  
  300. 300:     /**
  301. 301:      * Enables displaying or logging errors and exceptions.
  302. 302:      * @param  bool          enable production mode? (NULL means autodetection)
  303. 303:      * @param  string        error log file (FALSE disables logging in production mode)
  304. 304:      * @param  array|string administrator email or email headers; enables email sending in production mode
  305. 305:      * @return void 
  306. 306:      */
  307. 307:     public static function enable($productionMode NULL$logFile NULL$email NULL)
  308. 308:     {
  309. 309:         if (version_compare(PHP_VERSION'5.2.1'=== 0{
  310. 310:             throw new NotSupportedException(__METHOD__ . ' is not supported in PHP 5.2.1')// PHP bug #40815
  311. 311:         }
  312. 312:  
  313. 313:         error_reporting(E_ALL E_STRICT);
  314. 314:  
  315. 315:         // production/development mode detection
  316. 316:         if (is_bool($productionMode)) {
  317. 317:             self::$productionMode $productionMode;
  318. 318:         }
  319. 319:         if (self::$productionMode === self::DETECT{
  320. 320:             if (class_exists('Environment')) {
  321. 321:                 self::$productionMode Environment::isProduction();
  322. 322:  
  323. 323:             elseif (isset($_SERVER['SERVER_ADDR']|| isset($_SERVER['LOCAL_ADDR'])) // IP address based detection
  324. 324:                 $addr isset($_SERVER['SERVER_ADDR']$_SERVER['SERVER_ADDR'$_SERVER['LOCAL_ADDR'];
  325. 325:                 $oct explode('.'$addr);
  326. 326:                 self::$productionMode $addr !== '::1' && (count($oct!== || ($oct[0!== '10' && $oct[0!== '127' && ($oct[0!== '172' || $oct[116 || $oct[131)
  327. 327:                     && ($oct[0!== '169' || $oct[1!== '254'&& ($oct[0!== '192' || $oct[1!== '168')));
  328. 328:  
  329. 329:             else {
  330. 330:                 self::$productionMode !self::$consoleMode;
  331. 331:             }
  332. 332:         }
  333. 333:  
  334. 334:         // logging configuration
  335. 335:         if (self::$productionMode && $logFile !== FALSE{
  336. 336:             self::$logFile 'log/php_error.log';
  337. 337:  
  338. 338:             if (class_exists('Environment')) {
  339. 339:                 if (is_string($logFile)) {
  340. 340:                     self::$logFile Environment::expand($logFile);
  341. 341:  
  342. 342:                 else try {
  343. 343:                     self::$logFile Environment::expand('%logDir%/php_error.log');
  344. 344:  
  345. 345:                 catch (InvalidStateException $e{
  346. 346:                 }
  347. 347:  
  348. 348:             elseif (is_string($logFile)) {
  349. 349:                 self::$logFile $logFile;
  350. 350:             }
  351. 351:  
  352. 352:             ini_set('error_log'self::$logFile);
  353. 353:         }
  354. 354:  
  355. 355:         // php configuration
  356. 356:         if (function_exists('ini_set')) {
  357. 357:             ini_set('display_errors'!self::$productionMode)// or 'stderr'
  358. 358:             ini_set('html_errors'!self::$consoleMode);
  359. 359:             ini_set('log_errors'(bool) self::$logFile);
  360. 360:  
  361. 361:         elseif (ini_get('log_errors'!= (bool) self::$logFile || // intentionally ==
  362. 362:             (ini_get('display_errors'!= !self::$productionMode && ini_get('display_errors'!== (self::$productionMode 'stderr' 'stdout'))) {
  363. 363:             throw new NotSupportedException('Function ini_set() must be enabled.');
  364. 364:         }
  365. 365:  
  366. 366:         self::$sendEmails $logFile && $email;
  367. 367:         if (self::$sendEmails{
  368. 368:             if (is_string($email)) {
  369. 369:                 self::$emailHeaders['To'$email;
  370. 370:  
  371. 371:             elseif (is_array($email)) {
  372. 372:                 self::$emailHeaders $email self::$emailHeaders;
  373. 373:             }
  374. 374:         }
  375. 375:  
  376. 376:         if (!defined('E_DEPRECATED')) {
  377. 377:             define('E_DEPRECATED'8192);
  378. 378:         }
  379. 379:  
  380. 380:         if (!defined('E_USER_DEPRECATED')) {
  381. 381:             define('E_USER_DEPRECATED'16384);
  382. 382:         }
  383. 383:  
  384. 384:         set_exception_handler(array(__CLASS__'exceptionHandler'));
  385. 385:         set_error_handler(array(__CLASS__'errorHandler'));
  386. 386:         register_shutdown_function(array(__CLASS__'shutdownHandler'));
  387. 387:         self::$enabled TRUE;
  388. 388:  
  389. 389:         if (is_int($productionMode)) // back compatibility
  390. 390:             //trigger_error('Debug::enable($errorLevel) is deprecated; Remove $errorLevel parameter.', E_USER_WARNING);
  391. 391:         }
  392. 392:     }
  393. 393:  
  394. 394:  
  395. 395:  
  396. 396:     /**
  397. 397:      * Unregister error handler routine.
  398. 398:      * @return void 
  399. 399:      */
  400. 400:     public static function isEnabled()
  401. 401:     {
  402. 402:         return self::$enabled;
  403. 403:     }
  404. 404:  
  405. 405:  
  406. 406:  
  407. 407:     /**
  408. 408:      * Debug exception handler.
  409. 409:      *
  410. 410:      * @param  Exception 
  411. 411:      * @return void 
  412. 412:      * @ignore internal
  413. 413:      */
  414. 414:     public static function exceptionHandler(Exception $exception)
  415. 415:     {
  416. 416:         if (!headers_sent()) {
  417. 417:             header('HTTP/1.1 500 Internal Server Error');
  418. 418:         }
  419. 419:  
  420. 420:         self::processException($exceptionTRUE);
  421. 421:         exit;
  422. 422:     }
  423. 423:  
  424. 424:  
  425. 425:  
  426. 426:     /**
  427. 427:      * Own error handler.
  428. 428:      *
  429. 429:      * @param  int    level of the error raised
  430. 430:      * @param  string error message
  431. 431:      * @param  string file that the error was raised in
  432. 432:      * @param  int    line number the error was raised at
  433. 433:      * @param  array  an array of variables that existed in the scope the error was triggered in
  434. 434:      * @return bool   FALSE to call normal error handler, NULL otherwise
  435. 435:      * @throws FatalErrorException
  436. 436:      * @ignore internal
  437. 437:      */
  438. 438:     public static function errorHandler($severity$message$file$line$context)
  439. 439:     {
  440. 440:         static $fatals array(
  441. 441:             E_USER_ERROR => 1,
  442. 442:             E_RECOVERABLE_ERROR => 1// since PHP 5.2
  443. 443:         );
  444. 444:  
  445. 445:         if (isset($fatals[$severity])) {
  446. 446:             throw new FatalErrorException($message0$severity$file$line$context);
  447. 447:  
  448. 448:         elseif (($severity error_reporting()) !== $severity{
  449. 449:             return NULL// nothing to do
  450. 450:         }
  451. 451:  
  452. 452:         static $types array(
  453. 453:             E_WARNING => 'Warning',
  454. 454:             E_USER_WARNING => 'Warning',
  455. 455:             E_NOTICE => 'Notice',
  456. 456:             E_USER_NOTICE => 'Notice',
  457. 457:             E_STRICT => 'Strict standards',
  458. 458:             E_DEPRECATED => 'Deprecated',
  459. 459:             E_USER_DEPRECATED => 'Deprecated',
  460. 460:         );
  461. 461:  
  462. 462:         $type isset($types[$severity]$types[$severity'Unknown error';
  463. 463:  
  464. 464:         if (self::$logFile{
  465. 465:             if (self::$sendEmails{
  466. 466:                 self::sendEmail("$type$message in $file on line $line");
  467. 467:             }
  468. 468:             return FALSE// call normal error handler
  469. 469:  
  470. 470:         elseif (!self::$productionMode && self::$firebugDetected && !headers_sent()) {
  471. 471:             $message strip_tags($message);
  472. 472:             self::fireLog("$type$message in $file on line $line"self::ERROR);
  473. 473:             return NULL;
  474. 474:         }
  475. 475:  
  476. 476:         return FALSE// call normal error handler
  477. 477:     }
  478. 478:  
  479. 479:  
  480. 480:  
  481. 481:     /**
  482. 482:      * Shutdown handler to process fatal errors.
  483. 483:      * @return void 
  484. 484:      * @ignore internal
  485. 485:      */
  486. 486:     public static function shutdownHandler()
  487. 487:     {
  488. 488:         static $types array(
  489. 489:             E_ERROR => 1,
  490. 490:             E_CORE_ERROR => 1,
  491. 491:             E_COMPILE_ERROR => 1,
  492. 492:             E_PARSE => 1,
  493. 493:         );
  494. 494:  
  495. 495:         $error error_get_last();
  496. 496:  
  497. 497:         if (isset($types[$error['type']]&& ($error['type'error_reporting())) {
  498. 498:             if (!headers_sent()) // for PHP < 5.2.4
  499. 499:                 header('HTTP/1.1 500 Internal Server Error');
  500. 500:             }
  501. 501:  
  502. 502:             if (ini_get('html_errors')) {
  503. 503:                 $error['message'html_entity_decode(strip_tags($error['message']));
  504. 504:             }
  505. 505:  
  506. 506:             self::processException(new FatalErrorException($error['message']0$error['type']$error['file']$error['line']NULL)TRUE);
  507. 507:         }
  508. 508:     }
  509. 509:  
  510. 510:  
  511. 511:  
  512. 512:     /**
  513. 513:      * Logs or displays exception.
  514. 514:      * @param  Exception 
  515. 515:      * @param  bool  is writing to standard output buffer allowed?
  516. 516:      * @return void 
  517. 517:      */
  518. 518:     public static function processException(Exception $exception$outputAllowed FALSE)
  519. 519:     {
  520. 520:         if (self::$logFile{
  521. 521:             error_log("PHP Fatal error:  Uncaught $exception");
  522. 522:             $file @strftime('%d-%b-%Y %H-%M-%S 'Debug::$timestrstr(number_format(Debug::$time4'~''')'~');
  523. 523:             $file dirname(self::$logFile"/exception $file.html";
  524. 524:             self::$logHandle @fopen($file'x');
  525. 525:             if (self::$logHandle{
  526. 526:                 ob_start(array(__CLASS__'writeFile')1);
  527. 527:                 self::paintBlueScreen($exception);
  528. 528:                 ob_end_flush();
  529. 529:                 fclose(self::$logHandle);
  530. 530:             }
  531. 531:             if (self::$sendEmails{
  532. 532:                 self::sendEmail((string) $exception);
  533. 533:             }
  534. 534:  
  535. 535:         elseif (self::$productionMode{
  536. 536:             // be quiet
  537. 537:  
  538. 538:         elseif (self::$consoleMode// dump to console
  539. 539:             if ($outputAllowed{
  540. 540:                 echo "$exception\n";
  541. 541:                 foreach (self::$colophons as $callback{
  542. 542:                     foreach ((array) call_user_func($callback'bluescreen'as $lineecho strip_tags($line"\n";
  543. 543:                 }
  544. 544:             }
  545. 545:  
  546. 546:         elseif (self::$firebugDetected && self::$ajaxDetected && !headers_sent()) // AJAX mode
  547. 547:             self::fireLog($exceptionself::EXCEPTION);
  548. 548:  
  549. 549:         elseif ($outputAllowed// dump to browser
  550. 550:             self::paintBlueScreen($exception);
  551. 551:  
  552. 552:         elseif (self::$firebugDetected && !headers_sent()) {
  553. 553:             self::fireLog($exceptionself::EXCEPTION);
  554. 554:         }
  555. 555:     }
  556. 556:  
  557. 557:  
  558. 558:  
  559. 559:     /**
  560. 560:      * Paint blue screen.
  561. 561:      * @param  Exception 
  562. 562:      * @return void 
  563. 563:      * @ignore internal
  564. 564:      */
  565. 565:     public static function paintBlueScreen(Exception $exception)
  566. 566:     {
  567. 567:         $internals array();
  568. 568:         foreach (array('Object''ObjectMixin'as $class{
  569. 569:             if (class_exists($classFALSE)) {
  570. 570:                 $rc new ReflectionClass($class);
  571. 571:                 $internals[$rc->getFileName()TRUE;
  572. 572:             }
  573. 573:         }
  574. 574:         $colophons self::$colophons;
  575. 575:         require dirname(__FILE__'/Debug.templates/bluescreen.phtml';
  576. 576:     }
  577. 577:  
  578. 578:  
  579. 579:  
  580. 580:     /**
  581. 581:      * Redirects output to file.
  582. 582:      * @param  string 
  583. 583:      * @return string 
  584. 584:      * @ignore internal
  585. 585:      */
  586. 586:     public static function writeFile($buffer)
  587. 587:     {
  588. 588:         fwrite(self::$logHandle$buffer);
  589. 589:     }
  590. 590:  
  591. 591:  
  592. 592:  
  593. 593:     /**
  594. 594:      * Sends e-mail notification.
  595. 595:      * @param  string 
  596. 596:      * @return void 
  597. 597:      */
  598. 598:     private static function sendEmail($message)
  599. 599:     {
  600. 600:         $monitorFile self::$logFile '.monitor';
  601. 601:         $saved @file_get_contents($monitorFile)// intentionally @
  602. 602:         if ($saved === FALSE || is_numeric($saved)) {
  603. 603:             if (@file_put_contents($monitorFile'e-mail has been sent')) // intentionally @
  604. 604:                 call_user_func(self::$mailer$message);
  605. 605:             }
  606. 606:         }
  607. 607:     }
  608. 608:  
  609. 609:  
  610. 610:  
  611. 611:     /**
  612. 612:      * Default mailer.
  613. 613:      * @param  string 
  614. 614:      * @return void 
  615. 615:      */
  616. 616:     private static function defaultMailer($message)
  617. 617:     {
  618. 618:         $host isset($_SERVER['HTTP_HOST']$_SERVER['HTTP_HOST':
  619. 619:                 (isset($_SERVER['SERVER_NAME']$_SERVER['SERVER_NAME''');
  620. 620:  
  621. 621:         $headers str_replace(
  622. 622:             array('%host%''%date%''%message%'),
  623. 623:             array($host@date('Y-m-d H:i:s'Debug::$time)$message)// intentionally @
  624. 624:             self::$emailHeaders
  625. 625:         );
  626. 626:  
  627. 627:         $subject $headers['Subject'];
  628. 628:         $to $headers['To'];
  629. 629:         $body $headers['Body'];
  630. 630:         unset($headers['Subject']$headers['To']$headers['Body']);
  631. 631:         $header '';
  632. 632:         foreach ($headers as $key => $value{
  633. 633:             $header .= "$key$value\r\n";
  634. 634:         }
  635. 635:  
  636. 636:         // we need to change \r\n to \n because Unix mailer changes it back to \r\n
  637. 637:         $body str_replace("\r\n""\n"$body);
  638. 638:         if (PHP_OS != 'Linux'$body str_replace("\n""\r\n"$body);
  639. 639:  
  640. 640:         mail($to$subject$body$header);
  641. 641:     }
  642. 642:  
  643. 643:  
  644. 644:  
  645. 645:     /********************* profiler ****************d*g**/
  646. 646:  
  647. 647:  
  648. 648:  
  649. 649:     /**
  650. 650:      * Enables profiler.
  651. 651:      * @return void 
  652. 652:      */
  653. 653:     public static function enableProfiler()
  654. 654:     {
  655. 655:         self::$enabledProfiler TRUE;
  656. 656:         register_shutdown_function(array(__CLASS__'paintProfiler'));
  657. 657:     }
  658. 658:  
  659. 659:  
  660. 660:  
  661. 661:     /**
  662. 662:      * Disables profiler.
  663. 663:      * @return void 
  664. 664:      */
  665. 665:     public static function disableProfiler()
  666. 666:     {
  667. 667:         self::$enabledProfiler FALSE;
  668. 668:     }
  669. 669:  
  670. 670:  
  671. 671:  
  672. 672:     /**
  673. 673:      * Paint profiler window.
  674. 674:      * @return void 
  675. 675:      * @ignore internal
  676. 676:      */
  677. 677:     public static function paintProfiler()
  678. 678:     {
  679. 679:         if (!self::$enabledProfiler || self::$productionMode{
  680. 680:             return;
  681. 681:         }
  682. 682:         self::$enabledProfiler FALSE;
  683. 683:  
  684. 684:         if (self::$firebugDetected{
  685. 685:             self::fireLog('Nette profiler'self::GROUP_START);
  686. 686:             foreach (self::$colophons as $callback{
  687. 687:                 foreach ((array) call_user_func($callback'profiler'as $lineself::fireLog(strip_tags($line));
  688. 688:             }
  689. 689:             self::fireLog(NULLself::GROUP_END);
  690. 690:         }
  691. 691:  
  692. 692:         if (!self::$ajaxDetected{
  693. 693:             $colophons self::$colophons;
  694. 694:             require dirname(__FILE__'/Debug.templates/profiler.phtml';
  695. 695:         }
  696. 696:     }
  697. 697:  
  698. 698:  
  699. 699:  
  700. 700:     /********************* colophons ****************d*g**/
  701. 701:  
  702. 702:  
  703. 703:  
  704. 704:     /**
  705. 705:      * Add custom descriptions.
  706. 706:      * @param  callback 
  707. 707:      * @return void 
  708. 708:      */
  709. 709:     public static function addColophon($callback)
  710. 710:     {
  711. 711:         fixCallback($callback);
  712. 712:         if (!is_callable($callback)) {
  713. 713:             $able is_callable($callbackTRUE$textual);
  714. 714:             throw new InvalidArgumentException("Colophon handler '$textual' is not ($able 'callable.' 'valid PHP callback.'));
  715. 715:         }
  716. 716:  
  717. 717:         if (!in_array($callbackself::$colophonsTRUE)) {
  718. 718:             self::$colophons[$callback;
  719. 719:         }
  720. 720:     }
  721. 721:  
  722. 722:  
  723. 723:  
  724. 724:     /**
  725. 725:      * Returns default colophons.
  726. 726:      * @param  string  profiler | bluescreen
  727. 727:      * @return array 
  728. 728:      */
  729. 729:     public static function getDefaultColophons($sender)
  730. 730:     {
  731. 731:         if ($sender === 'profiler'{
  732. 732:             $arr['Elapsed time: ' sprintf('%0.3f'(microtime(TRUEDebug::$time1000' ms';
  733. 733:  
  734. 734:             foreach ((array) self::$counters as $name => $value{
  735. 735:                 if (is_array($value)) $value implode(', '$value);
  736. 736:                 $arr[htmlSpecialChars($name' = <strong>' htmlSpecialChars($value'</strong>';
  737. 737:             }
  738. 738:  
  739. 739:             $autoloaded class_exists('AutoLoader'FALSEAutoLoader::$count 0;
  740. 740:             $s '<span>' count(get_included_files()) '/' .  $autoloaded ' files</span>, ';
  741. 741:  
  742. 742:             $exclude array('stdClass''Exception''ErrorException''Traversable''IteratorAggregate''Iterator''ArrayAccess''Serializable''Closure');
  743. 743:             foreach (get_loaded_extensions(as $ext{
  744. 744:                 $ref new ReflectionExtension($ext);
  745. 745:                 $exclude array_merge($exclude$ref->getClassNames());
  746. 746:             }
  747. 747:             $classes array_diff(get_declared_classes()$exclude);
  748. 748:             $intf array_diff(get_declared_interfaces()$exclude);
  749. 749:             $func get_defined_functions();
  750. 750:             $func = (array) @$func['user'];
  751. 751:             $consts get_defined_constants(TRUE);
  752. 752:             $consts array_keys((array) @$consts['user']);
  753. 753:             foreach (array('classes''intf''func''consts'as $item{
  754. 754:                 $s .= '<span ' ($$item 'title="' implode(", "$$item'"' '''>' count($$item' ' $item '</span>, ';
  755. 755:             }
  756. 756:             $arr[$s;
  757. 757:         }
  758. 758:  
  759. 759:         if ($sender === 'bluescreen'{
  760. 760:             $arr['Report generated at ' @date('Y/m/d H:i:s'Debug::$time)// intentionally @
  761. 761:             if (isset($_SERVER['HTTP_HOST']$_SERVER['REQUEST_URI'])) {
  762. 762:                 $url (isset($_SERVER['HTTPS']&& strcasecmp($_SERVER['HTTPS']'off''https://' 'http://'htmlSpecialChars($_SERVER['HTTP_HOST'$_SERVER['REQUEST_URI']);
  763. 763:                 $arr['<a href="' $url '">' $url '</a>';
  764. 764:             }
  765. 765:             $arr['PHP ' htmlSpecialChars(PHP_VERSION);
  766. 766:             if (isset($_SERVER['SERVER_SOFTWARE'])) $arr[htmlSpecialChars($_SERVER['SERVER_SOFTWARE']);
  767. 767:             $arr[htmlSpecialChars(Framework::NAME ' ' Framework::VERSION' <i>(revision ' htmlSpecialChars(Framework::REVISION')</i>';
  768. 768:         }
  769. 769:         return $arr;
  770. 770:     }
  771. 771:  
  772. 772:  
  773. 773:  
  774. 774:     /********************* Firebug extension ****************d*g**/
  775. 775:  
  776. 776:  
  777. 777:  
  778. 778:     /**
  779. 779:      * Sends variable dump to Firebug tab request/server.
  780. 780:      * @param  mixed   variable to dump
  781. 781:      * @param  string  unique key
  782. 782:      * @return bool    was successful?
  783. 783:      */
  784. 784:     public static function fireDump($var$key)
  785. 785:     {
  786. 786:         return self::fireSend(2array((string) $key => $var));
  787. 787:     }
  788. 788:  
  789. 789:  
  790. 790:  
  791. 791:     /**
  792. 792:      * Sends message to Firebug console.
  793. 793:      * @param  mixed   message to log
  794. 794:      * @param  string  priority of message (LOG, INFO, WARN, ERROR, GROUP_START, GROUP_END)
  795. 795:      * @param  string  optional label
  796. 796:      * @return bool    was successful?
  797. 797:      */
  798. 798:     public static function fireLog($message$priority self::LOG$label NULL)
  799. 799:     {
  800. 800:         if ($message instanceof Exception{
  801. 801:             if ($priority !== self::EXCEPTION && $priority !== self::TRACE{
  802. 802:                 $priority self::TRACE;
  803. 803:             }
  804. 804:             $message array(
  805. 805:                 'Class' => get_class($message),
  806. 806:                 'Message' => $message->getMessage(),
  807. 807:                 'File' => $message->getFile(),
  808. 808:                 'Line' => $message->getLine(),
  809. 809:                 'Trace' => $message->getTrace(),
  810. 810:                 'Type' => '',
  811. 811:                 'Function' => '',
  812. 812:             );
  813. 813:             foreach ($message['Trace'as $row{
  814. 814:                 if (empty($row['file'])) $row['file''?';
  815. 815:                 if (empty($row['line'])) $row['line''?';
  816. 816:             }
  817. 817:         elseif ($priority === self::GROUP_START{
  818. 818:             $label $message;
  819. 819:             $message NULL;
  820. 820:         }
  821. 821:         return self::fireSend(1self::replaceObjects(array(array('Type' => $priority'Label' => $label)$message)));
  822. 822:     }
  823. 823:  
  824. 824:  
  825. 825:  
  826. 826:     /**
  827. 827:      * Performs Firebug output.
  828. 828:      * @see http://www.firephp.org
  829. 829:      * @param  int     structure index
  830. 830:      * @param  array   payload
  831. 831:      * @return bool    was successful?
  832. 832:      */
  833. 833:     private static function fireSend($index$payload)
  834. 834:     {
  835. 835:         if (self::$productionModereturn NULL;
  836. 836:  
  837. 837:         if (headers_sent()) return FALSE// or throw exception?
  838. 838:  
  839. 839:         header('X-Wf-Protocol-nette: http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
  840. 840:         header('X-Wf-nette-Plugin-1: http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.2.0');
  841. 841:  
  842. 842:         if ($index === 1{
  843. 843:             header('X-Wf-nette-Structure-1: http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1');
  844. 844:  
  845. 845:         elseif ($index === 2{
  846. 846:             header('X-Wf-nette-Structure-2: http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1');
  847. 847:         }
  848. 848:  
  849. 849:         $payload json_encode($payload);
  850. 850:         static $counter;
  851. 851:         foreach (str_split($payload4990as $s{
  852. 852:             $num = ++$counter;
  853. 853:             header("X-Wf-nette-$index-1-n$num: |$s|\\");
  854. 854:         }
  855. 855:         header("X-Wf-nette-$index-1-n$num: |$s|");
  856. 856:  
  857. 857:         return TRUE;
  858. 858:     }
  859. 859:  
  860. 860:  
  861. 861:  
  862. 862:     /**
  863. 863:      * fireLog helper.
  864. 864:      * @param  mixed 
  865. 865:      * @return mixed 
  866. 866:      */
  867. 867:     static private function replaceObjects($val)
  868. 868:     {
  869. 869:         if (is_object($val)) {
  870. 870:             return 'object ' get_class($val'';
  871. 871:  
  872. 872:         elseif (is_string($val)) {
  873. 873:             return $val @iconv('UTF-16''UTF-8//IGNORE'iconv('UTF-8''UTF-16//IGNORE'$val))// intentionally @
  874. 874:  
  875. 875:         elseif (is_array($val)) {
  876. 876:             foreach ($val as $k => $v{
  877. 877:                 unset($val[$k]);
  878. 878:                 $k @iconv('UTF-16''UTF-8//IGNORE'iconv('UTF-8''UTF-16//IGNORE'$k))// intentionally @
  879. 879:                 $val[$kself::replaceObjects($v);
  880. 880:             }
  881. 881:         }
  882. 882:  
  883. 883:         return $val;
  884. 884:     }
  885. 885:  
  886. 887:  
  887. 888:  
  888. 889:  
  889. 891:  
  890. 892: // hint:
  891. 893: // if (!function_exists('dump')) { function dump($var, $return = FALSE) { return Debug::dump($var, $return); } }