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:  * NDebug 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 NDebug
  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 NDebug::consoleDump()} */
  55. 55:     private static $consoleData;
  56. 56:  
  57. 57:     /********************* NDebug::dump() ****************d*g**/
  58. 58:  
  59. 59:     /** @var int  how many nested levels of array/object properties display {@link NDebug::dump()} */
  60. 60:     public static $maxDepth 3;
  61. 61:  
  62. 62:     /** @var int  how long strings display {@link NDebug::dump()} */
  63. 63:     public static $maxLen 150;
  64. 64:  
  65. 65:     /** @var int  display location? {@link NDebug::dump()} */
  66. 66:     public static $showLocation FALSE;
  67. 67:  
  68. 68:     /********************* errors and exceptions reporing ****************d*g**/
  69. 69:  
  70. 70:     /**#@+ server modes {@link NDebug::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 NDebug::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 NDebug::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 NDebug 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:         static $tableUtf$tableBin$re '#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{10FFFF}]#u';
  293. 293:         if ($tableUtf === NULL{
  294. 294:             foreach (range("\x00""\xFF"as $ch{
  295. 295:                 if (ord($ch32 && strpos("\r\n\t"$ch=== FALSE$tableUtf[$ch$tableBin[$ch'\\x' str_pad(dechex(ord($ch))2'0'STR_PAD_LEFT);
  296. 296:                 elseif (ord($ch127$tableUtf[$ch$tableBin[$ch$ch;
  297. 297:                 else $tableUtf[$ch$ch$tableBin[$ch'\\x' dechex(ord($ch))}
  298. 298:             }
  299. 299:             $tableUtf['\\x'$tableBin['\\x''\\\\x';
  300. 300:         }
  301. 301:  
  302. 302:         if (is_bool($var)) {
  303. 303:             return "<span>bool</span>(" ($var 'TRUE' 'FALSE'")\n";
  304. 304:  
  305. 305:         elseif ($var === NULL{
  306. 306:             return "<span>NULL</span>\n";
  307. 307:  
  308. 308:         elseif (is_int($var)) {
  309. 309:             return "<span>int</span>($var)\n";
  310. 310:  
  311. 311:         elseif (is_float($var)) {
  312. 312:             return "<span>float</span>($var)\n";
  313. 313:  
  314. 314:         elseif (is_string($var)) {
  315. 315:             if (self::$maxLen && strlen($varself::$maxLen{
  316. 316:                 $s htmlSpecialChars(substr($var0self::$maxLen)ENT_NOQUOTES' ... ';
  317. 317:             else {
  318. 318:                 $s htmlSpecialChars($varENT_NOQUOTES);
  319. 319:             }
  320. 320:             $s strtr($spreg_match($re$s|| preg_last_error($tableBin $tableUtf);
  321. 321:             return "<span>string</span>(" strlen($var") \"$s\"\n";
  322. 322:  
  323. 323:         elseif (is_array($var)) {
  324. 324:             $s "<span>array</span>(" count($var") ";
  325. 325:             $space str_repeat($space1 '   '$level);
  326. 326:  
  327. 327:             static $marker;
  328. 328:             if ($marker === NULL$marker uniqid("\x00"TRUE);
  329. 329:             if (empty($var)) {
  330. 330:  
  331. 331:             elseif (isset($var[$marker])) {
  332. 332:                 $s .= "{\n$space$space1*RECURSION*\n$space}";
  333. 333:  
  334. 334:             elseif ($level self::$maxDepth || !self::$maxDepth{
  335. 335:                 $s .= "<code>{\n";
  336. 336:                 $var[$marker0;
  337. 337:                 foreach ($var as $k => &$v{
  338. 338:                     if ($k === $markercontinue;
  339. 339:                     $k is_int($k$k '"' strtr($kpreg_match($re$k|| preg_last_error($tableBin $tableUtf'"';
  340. 340:                     $s .= "$space$space1$k => self::_dump($v$level 1);
  341. 341:                 }
  342. 342:                 unset($var[$marker]);
  343. 343:                 $s .= "$space}</code>";
  344. 344:  
  345. 345:             else {
  346. 346:                 $s .= "{\n$space$space1...\n$space}";
  347. 347:             }
  348. 348:             return $s "\n";
  349. 349:  
  350. 350:         elseif (is_object($var)) {
  351. 351:             $arr = (array) $var;
  352. 352:             $s "<span>object</span>(" get_class($var") (" count($arr") ";
  353. 353:             $space str_repeat($space1 '   '$level);
  354. 354:  
  355. 355:             static $list array();
  356. 356:             if (empty($arr)) {
  357. 357:                 $s .= "{}";
  358. 358:  
  359. 359:             elseif (in_array($var$listTRUE)) {
  360. 360:                 $s .= "{\n$space$space1*RECURSION*\n$space}";
  361. 361:  
  362. 362:             elseif ($level self::$maxDepth || !self::$maxDepth{
  363. 363:                 $s .= "<code>{\n";
  364. 364:                 $list[$var;
  365. 365:                 foreach ($arr as $k => &$v{
  366. 366:                     $m '';
  367. 367:                     if ($k[0=== "\x00"{
  368. 368:                         $m $k[1=== '*' ' <span>protected</span>' ' <span>private</span>';
  369. 369:                         $k substr($kstrrpos($k"\x00"1);
  370. 370:                     }
  371. 371:                     $k strtr($kpreg_match($re$k|| preg_last_error($tableBin $tableUtf);
  372. 372:                     $s .= "$space$space1\"$k\"$m => self::_dump($v$level 1);
  373. 373:                 }
  374. 374:                 array_pop($list);
  375. 375:                 $s .= "$space}</code>";
  376. 376:  
  377. 377:             else {
  378. 378:                 $s .= "{\n$space$space1...\n$space}";
  379. 379:             }
  380. 380:             return $s "\n";
  381. 381:  
  382. 382:         elseif (is_resource($var)) {
  383. 383:             return "<span>resource of type</span>(" get_resource_type($var")\n";
  384. 384:  
  385. 385:         else {
  386. 386:             return "<span>unknown type</span>\n";
  387. 387:         }
  388. 388:     }
  389. 389:  
  390. 390:  
  391. 391:  
  392. 392:     /**
  393. 393:      * Starts/stops stopwatch.
  394. 394:      * @param  string  name
  395. 395:      * @return elapsed seconds
  396. 396:      */
  397. 397:     public static function timer($name NULL)
  398. 398:     {
  399. 399:         static $time array();
  400. 400:         $now microtime(TRUE);
  401. 401:         $delta isset($time[$name]$now $time[$name0;
  402. 402:         $time[$name$now;
  403. 403:         return $delta;
  404. 404:     }
  405. 405:  
  406. 406:  
  407. 407:  
  408. 408:     /********************* errors and exceptions reporing ****************d*g**/
  409. 409:  
  410. 410:  
  411. 411:  
  412. 412:     /**
  413. 413:      * Enables displaying or logging errors and exceptions.
  414. 414:      * @param  mixed         production, development mode or autodetection
  415. 415:      * @param  string        error log file (FALSE disables logging in production mode)
  416. 416:      * @param  array|string administrator email or email headers; enables email sending in production mode
  417. 417:      * @return void 
  418. 418:      */
  419. 419:     public static function enable($mode NULL$logFile NULL$email NULL)
  420. 420:     {
  421. 421:         error_reporting(E_ALL E_STRICT);
  422. 422:  
  423. 423:         // production/development mode detection
  424. 424:         if (is_bool($mode)) {
  425. 425:             self::$productionMode $mode;
  426. 426:         }
  427. 427:         if (self::$productionMode === self::DETECT{
  428. 428:             if (class_exists('NEnvironment')) {
  429. 429:                 self::$productionMode NEnvironment::isProduction();
  430. 430:  
  431. 431:             elseif (isset($_SERVER['SERVER_ADDR']|| isset($_SERVER['LOCAL_ADDR'])) // IP address based detection
  432. 432:                 $addr isset($_SERVER['SERVER_ADDR']$_SERVER['SERVER_ADDR'$_SERVER['LOCAL_ADDR'];
  433. 433:                 $oct explode('.'$addr);
  434. 434:                 self::$productionMode $addr !== '::1' && (count($oct!== || ($oct[0!== '10' && $oct[0!== '127' && ($oct[0!== '172' || $oct[116 || $oct[131)
  435. 435:                     && ($oct[0!== '169' || $oct[1!== '254'&& ($oct[0!== '192' || $oct[1!== '168')));
  436. 436:  
  437. 437:             else {
  438. 438:                 self::$productionMode !self::$consoleMode;
  439. 439:             }
  440. 440:         }
  441. 441:  
  442. 442:         // logging configuration
  443. 443:         if (self::$productionMode && $logFile !== FALSE{
  444. 444:             self::$logFile 'log/php_error.log';
  445. 445:  
  446. 446:             if (class_exists('NEnvironment')) {
  447. 447:                 if (is_string($logFile)) {
  448. 448:                     self::$logFile NEnvironment::expand($logFile);
  449. 449:  
  450. 450:                 else try {
  451. 451:                     self::$logFile NEnvironment::expand('%logDir%/php_error.log');
  452. 452:  
  453. 453:                 catch (InvalidStateException $e{
  454. 454:                 }
  455. 455:  
  456. 456:             elseif (is_string($logFile)) {
  457. 457:                 self::$logFile $logFile;
  458. 458:             }
  459. 459:  
  460. 460:             ini_set('error_log'self::$logFile);
  461. 461:         }
  462. 462:  
  463. 463:         // php configuration
  464. 464:         if (function_exists('ini_set')) {
  465. 465:             ini_set('display_errors'!self::$productionMode)// or 'stderr'
  466. 466:             ini_set('html_errors'!self::$logFile && !self::$consoleMode);
  467. 467:             ini_set('log_errors'(bool) self::$logFile);
  468. 468:  
  469. 469:         elseif (ini_get('log_errors'!= (bool) self::$logFile || // intentionally ==
  470. 470:             (ini_get('display_errors'!= !self::$productionMode && ini_get('display_errors'!== (self::$productionMode 'stderr' 'stdout'))) {
  471. 471:             throw new NotSupportedException('Function ini_set() must be enabled.');
  472. 472:         }
  473. 473:  
  474. 474:         self::$sendEmails self::$logFile && $email;
  475. 475:         if (self::$sendEmails{
  476. 476:             if (is_string($email)) {
  477. 477:                 self::$emailHeaders['To'$email;
  478. 478:  
  479. 479:             elseif (is_array($email)) {
  480. 480:                 self::$emailHeaders $email self::$emailHeaders;
  481. 481:             }
  482. 482:         }
  483. 483:  
  484. 484:         if (!defined('E_DEPRECATED')) {
  485. 485:             define('E_DEPRECATED'8192);
  486. 486:         }
  487. 487:  
  488. 488:         if (!defined('E_USER_DEPRECATED')) {
  489. 489:             define('E_USER_DEPRECATED'16384);
  490. 490:         }
  491. 491:  
  492. 492:         set_exception_handler(array(__CLASS__'exceptionHandler'));
  493. 493:         set_error_handler(array(__CLASS__'errorHandler'));
  494. 494:         self::$enabled TRUE;
  495. 495:     }
  496. 496:  
  497. 497:  
  498. 498:  
  499. 499:     /**
  500. 500:      * Unregister error handler routine.
  501. 501:      * @return void 
  502. 502:      */
  503. 503:     public static function isEnabled()
  504. 504:     {
  505. 505:         return self::$enabled;
  506. 506:     }
  507. 507:  
  508. 508:  
  509. 509:  
  510. 510:     /**
  511. 511:      * NDebug exception handler.
  512. 512:      *
  513. 513:      * @param  Exception 
  514. 514:      * @return void 
  515. 515:      * @ignore internal
  516. 516:      */
  517. 517:     public static function exceptionHandler(Exception $exception)
  518. 518:     {
  519. 519:         if (!headers_sent()) {
  520. 520:             header('HTTP/1.1 500 Internal Server Error');
  521. 521:         }
  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:             if (!headers_sent()) {
  551. 551:                 header('HTTP/1.1 500 Internal Server Error');
  552. 552:             }
  553. 553:             self::processException(new FatalErrorException($message0$severity$file$line$context)TRUE);
  554. 554:             exit;
  555. 555:         }
  556. 556:  
  557. 557:         static $types array(
  558. 558:             E_WARNING => 'Warning',
  559. 559:             E_USER_WARNING => 'Warning',
  560. 560:             E_NOTICE => 'Notice',
  561. 561:             E_USER_NOTICE => 'Notice',
  562. 562:             E_STRICT => 'Strict standards',
  563. 563:             E_DEPRECATED => 'Deprecated',
  564. 564:             E_USER_DEPRECATED => 'Deprecated',
  565. 565:         );
  566. 566:  
  567. 567:         $type isset($types[$severity]$types[$severity'Unknown error';
  568. 568:  
  569. 569:         if (self::$logFile{
  570. 570:             if (self::$sendEmails{
  571. 571:                 self::sendEmail("$type$message in $file on line $line");
  572. 572:             }
  573. 573:             return FALSE// call normal error handler
  574. 574:  
  575. 575:         elseif (!self::$productionMode && self::$firebugDetected && !headers_sent()) {
  576. 576:             $message strip_tags($message);
  577. 577:             self::fireLog("$type$message in $file on line $line"self::ERROR);
  578. 578:             return NULL;
  579. 579:         }
  580. 580:  
  581. 581:         return FALSE// call normal error handler
  582. 582:     }
  583. 583:  
  584. 584:  
  585. 585:  
  586. 586:     /**
  587. 587:      * Logs or displays exception.
  588. 588:      * @param  Exception 
  589. 589:      * @param  bool  is writing to standard output buffer allowed?
  590. 590:      * @return void 
  591. 591:      */
  592. 592:     public static function processException(Exception $exception$outputAllowed FALSE)
  593. 593:     {
  594. 594:         if (self::$logFile{
  595. 595:             error_log("PHP Fatal error:  Uncaught $exception");
  596. 596:             $file @strftime('%d-%b-%Y %H-%M-%S 'NDebug::$timestrstr(number_format(NDebug::$time4'~''')'~');
  597. 597:             $file dirname(self::$logFile"/exception $file.html";
  598. 598:             self::$logHandle @fopen($file'x');
  599. 599:             if (self::$logHandle{
  600. 600:                 ob_start(array(__CLASS__'writeFile')1);
  601. 601:                 self::paintBlueScreen($exception);
  602. 602:                 ob_end_flush();
  603. 603:                 fclose(self::$logHandle);
  604. 604:             }
  605. 605:             if (self::$sendEmails{
  606. 606:                 self::sendEmail((string) $exception);
  607. 607:             }
  608. 608:  
  609. 609:         elseif (self::$productionMode{
  610. 610:             // be quiet
  611. 611:  
  612. 612:         elseif (self::$consoleMode// dump to console
  613. 613:             if ($outputAllowed{
  614. 614:                 echo "$exception\n";
  615. 615:                 foreach (self::$colophons as $callback{
  616. 616:                     foreach ((array) call_user_func($callback'bluescreen'as $lineecho strip_tags($line"\n";
  617. 617:                 }
  618. 618:             }
  619. 619:  
  620. 620:         elseif (self::$firebugDetected && self::$ajaxDetected && !headers_sent()) // AJAX mode
  621. 621:             self::fireLog($exceptionself::EXCEPTION);
  622. 622:  
  623. 623:         elseif ($outputAllowed// dump to browser
  624. 624:             if (!headers_sent()) {
  625. 625:                 @ob_end_clean()while (ob_get_level(&& @ob_end_clean());
  626. 626:                 
  627. 627:                 header('Content-Encoding: identity'TRUE)// override gzhandler
  628. 628:             }
  629. 629:             self::paintBlueScreen($exception);
  630. 630:  
  631. 631:         elseif (self::$firebugDetected && !headers_sent()) {
  632. 632:             self::fireLog($exceptionself::EXCEPTION);
  633. 633:         }
  634. 634:  
  635. 635:         foreach (self::$onFatalError as $handler{
  636. 636:             fixCallback($handler);
  637. 637:             call_user_func($handler$exception);
  638. 638:         }
  639. 639:     }
  640. 640:  
  641. 641:  
  642. 642:  
  643. 643:     /**
  644. 644:      * Paint blue screen.
  645. 645:      * @param  Exception 
  646. 646:      * @return void 
  647. 647:      * @ignore internal
  648. 648:      */
  649. 649:     public static function paintBlueScreen(Exception $exception)
  650. 650:     {
  651. 651:         $internals array();
  652. 652:         foreach (array('NObject''NObjectMixin'as $class{
  653. 653:             if (class_exists($classFALSE)) {
  654. 654:                 $rc new ReflectionClass($class);
  655. 655:                 $internals[$rc->getFileName()TRUE;
  656. 656:             }
  657. 657:         }
  658. 658:  
  659. 659:         if (class_exists('NEnvironment'FALSE)) {
  660. 660:             $application NEnvironment::getServiceLocator()->hasService('NApplication'TRUENEnvironment::getServiceLocator()->getService('NApplication'NULL;
  661. 661:         }
  662. 662:  
  663. 663:         $colophons self::$colophons;
  664. 664:         require dirname(__FILE__'/Debug.templates/bluescreen.phtml';
  665. 665:     }
  666. 666:  
  667. 667:  
  668. 668:  
  669. 669:     /**
  670. 670:      * Redirects output to file.
  671. 671:      * @param  string 
  672. 672:      * @return string 
  673. 673:      * @ignore internal
  674. 674:      */
  675. 675:     public static function writeFile($buffer)
  676. 676:     {
  677. 677:         fwrite(self::$logHandle$buffer);
  678. 678:     }
  679. 679:  
  680. 680:  
  681. 681:  
  682. 682:     /**
  683. 683:      * Sends e-mail notification.
  684. 684:      * @param  string 
  685. 685:      * @return void 
  686. 686:      */
  687. 687:     private static function sendEmail($message)
  688. 688:     {
  689. 689:         $monitorFile self::$logFile '.monitor';
  690. 690:         if (!is_file($monitorFile)) {
  691. 691:             if (@file_put_contents($monitorFile'e-mail has been sent')) // intentionally @
  692. 692:                 call_user_func(self::$mailer$message);
  693. 693:             }
  694. 694:         }
  695. 695:     }
  696. 696:  
  697. 697:  
  698. 698:  
  699. 699:     /**
  700. 700:      * Default mailer.
  701. 701:      * @param  string 
  702. 702:      * @return void 
  703. 703:      */
  704. 704:     private static function defaultMailer($message)
  705. 705:     {
  706. 706:         $host isset($_SERVER['HTTP_HOST']$_SERVER['HTTP_HOST':
  707. 707:                 (isset($_SERVER['SERVER_NAME']$_SERVER['SERVER_NAME''');
  708. 708:  
  709. 709:         $headers str_replace(
  710. 710:             array('%host%''%date%''%message%'),
  711. 711:             array($host@date('Y-m-d H:i:s'NDebug::$time)$message)// intentionally @
  712. 712:             self::$emailHeaders
  713. 713:         );
  714. 714:  
  715. 715:         $subject $headers['Subject'];
  716. 716:         $to $headers['To'];
  717. 717:         $body $headers['Body'];
  718. 718:         unset($headers['Subject']$headers['To']$headers['Body']);
  719. 719:         $header '';
  720. 720:         foreach ($headers as $key => $value{
  721. 721:             $header .= "$key$value\r\n";
  722. 722:         }
  723. 723:  
  724. 724:         // we need to change \r\n to \n because Unix mailer changes it back to \r\n
  725. 725:         $body str_replace("\r\n""\n"$body);
  726. 726:         if (PHP_OS != 'Linux'$body str_replace("\n""\r\n"$body);
  727. 727:  
  728. 728:         mail($to$subject$body$header);
  729. 729:     }
  730. 730:  
  731. 731:  
  732. 732:  
  733. 733:     /********************* profiler ****************d*g**/
  734. 734:  
  735. 735:  
  736. 736:  
  737. 737:     /**
  738. 738:      * Enables profiler.
  739. 739:      * @return void 
  740. 740:      */
  741. 741:     public static function enableProfiler()
  742. 742:     {
  743. 743:         self::$enabledProfiler TRUE;
  744. 744:     }
  745. 745:  
  746. 746:  
  747. 747:  
  748. 748:     /**
  749. 749:      * Disables profiler.
  750. 750:      * @return void 
  751. 751:      */
  752. 752:     public static function disableProfiler()
  753. 753:     {
  754. 754:         self::$enabledProfiler FALSE;
  755. 755:     }
  756. 756:  
  757. 757:  
  758. 758:  
  759. 759:     /********************* colophons ****************d*g**/
  760. 760:  
  761. 761:  
  762. 762:  
  763. 763:     /**
  764. 764:      * Add custom descriptions.
  765. 765:      * @param  callback 
  766. 766:      * @return void 
  767. 767:      */
  768. 768:     public static function addColophon($callback)
  769. 769:     {
  770. 770:         fixCallback($callback);
  771. 771:         if (!is_callable($callback)) {
  772. 772:             $able is_callable($callbackTRUE$textual);
  773. 773:             throw new InvalidArgumentException("Colophon handler '$textual' is not ($able 'callable.' 'valid PHP callback.'));
  774. 774:         }
  775. 775:  
  776. 776:         if (!in_array($callbackself::$colophonsTRUE)) {
  777. 777:             self::$colophons[$callback;
  778. 778:         }
  779. 779:     }
  780. 780:  
  781. 781:  
  782. 782:  
  783. 783:     /**
  784. 784:      * Returns default colophons.
  785. 785:      * @param  string  profiler | bluescreen
  786. 786:      * @return array 
  787. 787:      */
  788. 788:     public static function getDefaultColophons($sender)
  789. 789:     {
  790. 790:         if ($sender === 'profiler'{
  791. 791:             $arr['Elapsed time: <b>' number_format((microtime(TRUENDebug::$time10001'.'' ''</b> ms | Allocated memory: <b>' number_format(memory_get_peak_usage(10001'.'' ''</b> kB';
  792. 792:  
  793. 793:             foreach ((array) self::$counters as $name => $value{
  794. 794:                 if (is_array($value)) $value implode(', '$value);
  795. 795:                 $arr[htmlSpecialChars($name' = <strong>' htmlSpecialChars($value'</strong>';
  796. 796:             }
  797. 797:  
  798. 798:             $autoloaded class_exists('NAutoLoader'FALSENAutoLoader::$count 0;
  799. 799:             $s '<span>' count(get_included_files()) '/' .  $autoloaded ' files</span>, ';
  800. 800:  
  801. 801:             $exclude array('stdClass''Exception''ErrorException''Traversable''IteratorAggregate''Iterator''ArrayAccess''Serializable''Closure');
  802. 802:             foreach (get_loaded_extensions(as $ext{
  803. 803:                 $ref new ReflectionExtension($ext);
  804. 804:                 $exclude array_merge($exclude$ref->getClassNames());
  805. 805:             }
  806. 806:             $classes array_diff(get_declared_classes()$exclude);
  807. 807:             $intf array_diff(get_declared_interfaces()$exclude);
  808. 808:             $func get_defined_functions();
  809. 809:             $func = (array) @$func['user'];
  810. 810:             $consts get_defined_constants(TRUE);
  811. 811:             $consts array_keys((array) @$consts['user']);
  812. 812:             foreach (array('classes''intf''func''consts'as $item{
  813. 813:                 $s .= '<span ' ($$item 'title="' implode(", "$$item'"' '''>' count($$item' ' $item '</span>, ';
  814. 814:             }
  815. 815:             $arr[$s;
  816. 816:         }
  817. 817:  
  818. 818:         if ($sender === 'bluescreen'{
  819. 819:             $arr['Report generated at ' @date('Y/m/d H:i:s'NDebug::$time)// intentionally @
  820. 820:             if (isset($_SERVER['HTTP_HOST']$_SERVER['REQUEST_URI'])) {
  821. 821:                 $url (isset($_SERVER['HTTPS']&& strcasecmp($_SERVER['HTTPS']'off''https://' 'http://'htmlSpecialChars($_SERVER['HTTP_HOST'$_SERVER['REQUEST_URI']);
  822. 822:                 $arr['<a href="' $url '">' $url '</a>';
  823. 823:             }
  824. 824:             $arr['PHP ' htmlSpecialChars(PHP_VERSION);
  825. 825:             if (isset($_SERVER['SERVER_SOFTWARE'])) $arr[htmlSpecialChars($_SERVER['SERVER_SOFTWARE']);
  826. 826:             $arr[htmlSpecialChars(NFramework::NAME ' ' NFramework::VERSION' <i>(revision ' htmlSpecialChars(NFramework::REVISION')</i>';
  827. 827:         }
  828. 828:         return $arr;
  829. 829:     }
  830. 830:  
  831. 831:  
  832. 832:  
  833. 833:     /********************* Firebug extension ****************d*g**/
  834. 834:  
  835. 835:  
  836. 836:  
  837. 837:     /**
  838. 838:      * Sends variable dump to Firebug tab request/server.
  839. 839:      * @param  mixed  variable to dump
  840. 840:      * @param  string unique key
  841. 841:      * @return mixed  variable itself
  842. 842:      */
  843. 843:     public static function fireDump($var$key)
  844. 844:     {
  845. 845:         self::fireSend(2array((string) $key => $var));
  846. 846:         return $var;
  847. 847:     }
  848. 848:  
  849. 849:  
  850. 850:  
  851. 851:     /**
  852. 852:      * Sends message to Firebug console.
  853. 853:      * @param  mixed   message to log
  854. 854:      * @param  string  priority of message (LOG, INFO, WARN, ERROR, GROUP_START, GROUP_END)
  855. 855:      * @param  string  optional label
  856. 856:      * @return bool    was successful?
  857. 857:      */
  858. 858:     public static function fireLog($message$priority self::LOG$label NULL)
  859. 859:     {
  860. 860:         if ($message instanceof Exception{
  861. 861:             if ($priority !== self::EXCEPTION && $priority !== self::TRACE{
  862. 862:                 $priority self::TRACE;
  863. 863:             }
  864. 864:             $message array(
  865. 865:                 'Class' => get_class($message),
  866. 866:                 'Message' => $message->getMessage(),
  867. 867:                 'File' => $message->getFile(),
  868. 868:                 'Line' => $message->getLine(),
  869. 869:                 'Trace' => $message->getTrace(),
  870. 870:                 'Type' => '',
  871. 871:                 'Function' => '',
  872. 872:             );
  873. 873:             foreach ($message['Trace'as $row{
  874. 874:                 if (empty($row['file'])) $row['file''?';
  875. 875:                 if (empty($row['line'])) $row['line''?';
  876. 876:             }
  877. 877:         elseif ($priority === self::GROUP_START{
  878. 878:             $label $message;
  879. 879:             $message NULL;
  880. 880:         }
  881. 881:         return self::fireSend(1self::replaceObjects(array(array('Type' => $priority'Label' => $label)$message)));
  882. 882:     }
  883. 883:  
  884. 884:  
  885. 885:  
  886. 886:     /**
  887. 887:      * Performs Firebug output.
  888. 888:      * @see http://www.firephp.org
  889. 889:      * @param  int     structure index
  890. 890:      * @param  array   payload
  891. 891:      * @return bool    was successful?
  892. 892:      */
  893. 893:     private static function fireSend($index$payload)
  894. 894:     {
  895. 895:         if (self::$productionModereturn NULL;
  896. 896:  
  897. 897:         if (headers_sent()) return FALSE// or throw exception?
  898. 898:  
  899. 899:         header('X-Wf-Protocol-nette: http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
  900. 900:         header('X-Wf-nette-Plugin-1: http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.2.0');
  901. 901:  
  902. 902:         if ($index === 1{
  903. 903:             header('X-Wf-nette-Structure-1: http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1');
  904. 904:  
  905. 905:         elseif ($index === 2{
  906. 906:             header('X-Wf-nette-Structure-2: http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1');
  907. 907:         }
  908. 908:  
  909. 909:         $payload json_encode($payload);
  910. 910:         static $counter;
  911. 911:         foreach (str_split($payload4990as $s{
  912. 912:             $num = ++$counter;
  913. 913:             header("X-Wf-nette-$index-1-n$num: |$s|\\");
  914. 914:         }
  915. 915:         header("X-Wf-nette-$index-1-n$num: |$s|");
  916. 916:  
  917. 917:         return TRUE;
  918. 918:     }
  919. 919:  
  920. 920:  
  921. 921:  
  922. 922:     /**
  923. 923:      * fireLog helper.
  924. 924:      * @param  mixed 
  925. 925:      * @return mixed 
  926. 926:      */
  927. 927:     static private function replaceObjects($val)
  928. 928:     {
  929. 929:         if (is_object($val)) {
  930. 930:             return 'object ' get_class($val'';
  931. 931:  
  932. 932:         elseif (is_string($val)) {
  933. 933:             return @iconv('UTF-16''UTF-8//IGNORE'iconv('UTF-8''UTF-16//IGNORE'$val))// intentionally @
  934. 934:  
  935. 935:         elseif (is_array($val)) {
  936. 936:             foreach ($val as $k => $v{
  937. 937:                 unset($val[$k]);
  938. 938:                 $k @iconv('UTF-16''UTF-8//IGNORE'iconv('UTF-8''UTF-16//IGNORE'$k))// intentionally @
  939. 939:                 $val[$kself::replaceObjects($v);
  940. 940:             }
  941. 941:         }
  942. 942:  
  943. 943:         return $val;
  944. 944:     }
  945. 945:  
  946. 947:  
  947. 948:  
  948. 949:  
  949. 951:  
  950. 952: // hint:
  951. 953: // if (!function_exists('dump')) { function dump($var, $return = FALSE) { return NDebug::dump($var, $return); } }