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