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