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