Namespaces

  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Config
      • Adapters
      • Extensions
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Diagnostics
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
      • PhpGenerator
  • NetteModule
  • None
  • PHP

Classes

  • Bar
  • BlueScreen
  • Debugger
  • FireLogger
  • Helpers
  • Logger

Interfaces

  • IBarPanel
  • Overview
  • Namespace
  • Class
  • Tree
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (http://nette.org)
  5:  *
  6:  * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
  7:  *
  8:  * For the full copyright and license information, please view
  9:  * the file license.txt that was distributed with this source code.
 10:  */
 11: 
 12: namespace Nette\Diagnostics;
 13: 
 14: use Nette;
 15: 
 16: 
 17: 
 18: /**
 19:  * Debugger: displays and logs errors.
 20:  *
 21:  * Behavior is determined by two factors: mode & output
 22:  * - modes: production / development
 23:  * - output: HTML / AJAX / CLI / other (e.g. XML)
 24:  *
 25:  * @author     David Grudl
 26:  */
 27: final class Debugger
 28: {
 29:     /** @var bool in production mode is suppressed any debugging output */
 30:     public static $productionMode;
 31: 
 32:     /** @var bool in console mode is omitted HTML output */
 33:     public static $consoleMode;
 34: 
 35:     /** @var int timestamp with microseconds of the start of the request */
 36:     public static $time;
 37: 
 38:     /** @var bool is AJAX request detected? */
 39:     private static $ajaxDetected;
 40: 
 41:     /** @var string  requested URI or command line */
 42:     public static $source;
 43: 
 44:     /** @var string URL pattern mask to open editor */
 45:     public static $editor = 'editor://open/?file=%file&line=%line';
 46: 
 47:     /** @var string command to open browser (use 'start ""' in Windows) */
 48:     public static $browser;
 49: 
 50:     /********************* Debugger::dump() ****************d*g**/
 51: 
 52:     /** @var int  how many nested levels of array/object properties display {@link Debugger::dump()} */
 53:     public static $maxDepth = 3;
 54: 
 55:     /** @var int  how long strings display {@link Debugger::dump()} */
 56:     public static $maxLen = 150;
 57: 
 58:     /** @var bool display location? {@link Debugger::dump()} */
 59:     public static $showLocation = FALSE;
 60: 
 61:     /** @var array */
 62:     public static $consoleColors = array(
 63:         'bool' => '1;33',
 64:         'null' => '1;33',
 65:         'int' => '1;36',
 66:         'float' => '1;36',
 67:         'string' => '1;32',
 68:         'array' => '1;31',
 69:         'key' => '1;37',
 70:         'object' => '1;31',
 71:         'visibility' => '1;30',
 72:         'resource' => '1;37',
 73:     );
 74: 
 75:     /********************* errors and exceptions reporting ****************d*g**/
 76: 
 77:     /** server modes {@link Debugger::enable()} */
 78:     const DEVELOPMENT = FALSE,
 79:         PRODUCTION = TRUE,
 80:         DETECT = NULL;
 81: 
 82:     /** @var BlueScreen */
 83:     public static $blueScreen;
 84: 
 85:     /** @var bool|int determines whether any error will cause immediate death; if integer that it's matched against error severity */
 86:     public static $strictMode = FALSE; // $immediateDeath
 87: 
 88:     /** @var bool disables the @ (shut-up) operator so that notices and warnings are no longer hidden */
 89:     public static $scream = FALSE;
 90: 
 91:     /** @var array of callables specifies the functions that are automatically called after fatal error */
 92:     public static $onFatalError = array();
 93: 
 94:     /** @var bool {@link Debugger::enable()} */
 95:     private static $enabled = FALSE;
 96: 
 97:     /** @var mixed {@link Debugger::tryError()} FALSE means catching is disabled */
 98:     private static $lastError = FALSE;
 99: 
100:     /********************* logging ****************d*g**/
101: 
102:     /** @var Logger */
103:     public static $logger;
104: 
105:     /** @var FireLogger */
106:     public static $fireLogger;
107: 
108:     /** @var string name of the directory where errors should be logged; FALSE means that logging is disabled */
109:     public static $logDirectory;
110: 
111:     /** @var string email to sent error notifications */
112:     public static $email;
113: 
114:     /** @deprecated */
115:     public static $mailer;
116: 
117:     /** @deprecated */
118:     public static $emailSnooze;
119: 
120:     /********************* debug bar ****************d*g**/
121: 
122:     /** @var Bar */
123:     public static $bar;
124: 
125:     /** @var DefaultBarPanel */
126:     private static $errorPanel;
127: 
128:     /** @var DefaultBarPanel */
129:     private static $dumpPanel;
130: 
131:     /********************* Firebug extension ****************d*g**/
132: 
133:     /** {@link Debugger::log()} and {@link Debugger::fireLog()} */
134:     const DEBUG = 'debug',
135:         INFO = 'info',
136:         WARNING = 'warning',
137:         ERROR = 'error',
138:         CRITICAL = 'critical';
139: 
140: 
141: 
142:     /**
143:      * Static class - cannot be instantiated.
144:      */
145:     final public function __construct()
146:     {
147:         throw new Nette\StaticClassException;
148:     }
149: 
150: 
151: 
152:     /**
153:      * Static class constructor.
154:      * @internal
155:      */
156:     public static function _init()
157:     {
158:         self::$time = isset($_SERVER['REQUEST_TIME_FLOAT']) ? $_SERVER['REQUEST_TIME_FLOAT'] : microtime(TRUE);
159:         self::$consoleMode = PHP_SAPI === 'cli';
160:         self::$productionMode = self::DETECT;
161:         if (self::$consoleMode) {
162:             self::$source = empty($_SERVER['argv']) ? 'cli' : 'cli: ' . implode(' ', $_SERVER['argv']);
163:         } else {
164:             self::$ajaxDetected = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
165:             if (isset($_SERVER['REQUEST_URI'])) {
166:                 self::$source = (isset($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'off') ? 'https://' : 'http://')
167:                     . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : ''))
168:                     . $_SERVER['REQUEST_URI'];
169:             }
170:         }
171: 
172:         self::$logger = new Logger;
173:         self::$logDirectory = & self::$logger->directory;
174:         self::$email = & self::$logger->email;
175:         self::$mailer = & self::$logger->mailer;
176:         self::$emailSnooze = & Logger::$emailSnooze;
177: 
178:         self::$fireLogger = new FireLogger;
179: 
180:         self::$blueScreen = new BlueScreen;
181:         self::$blueScreen->addPanel(function($e) {
182:             if ($e instanceof Nette\Templating\FilterException) {
183:                 return array(
184:                     'tab' => 'Template',
185:                     'panel' => '<p><b>File:</b> ' . Helpers::editorLink($e->sourceFile, $e->sourceLine)
186:                     . '&nbsp; <b>Line:</b> ' . ($e->sourceLine ? $e->sourceLine : 'n/a') . '</p>'
187:                     . ($e->sourceLine ? BlueScreen::highlightFile($e->sourceFile, $e->sourceLine) : '')
188:                 );
189:             } elseif ($e instanceof Nette\Utils\NeonException && preg_match('#line (\d+)#', $e->getMessage(), $m)) {
190:                 if ($item = Helpers::findTrace($e->getTrace(), 'Nette\Config\Adapters\NeonAdapter::load')) {
191:                     return array(
192:                         'tab' => 'NEON',
193:                         'panel' => '<p><b>File:</b> ' . Helpers::editorLink($item['args'][0], $m[1]) . '&nbsp; <b>Line:</b> ' . $m[1] . '</p>'
194:                             . BlueScreen::highlightFile($item['args'][0], $m[1])
195:                     );
196:                 } elseif ($item = Helpers::findTrace($e->getTrace(), 'Nette\Utils\Neon::decode')) {
197:                     return array(
198:                         'tab' => 'NEON',
199:                         'panel' => BlueScreen::highlightPhp($item['args'][0], $m[1])
200:                     );
201:                 }
202:             }
203:         });
204: 
205:         self::$bar = new Bar;
206:         self::$bar->addPanel(new DefaultBarPanel('time'));
207:         self::$bar->addPanel(new DefaultBarPanel('memory'));
208:         self::$bar->addPanel(self::$errorPanel = new DefaultBarPanel('errors')); // filled by _errorHandler()
209:         self::$bar->addPanel(self::$dumpPanel = new DefaultBarPanel('dumps')); // filled by barDump()
210:     }
211: 
212: 
213: 
214:     /********************* errors and exceptions reporting ****************d*g**/
215: 
216: 
217: 
218:     /**
219:      * Enables displaying or logging errors and exceptions.
220:      * @param  mixed         production, development mode, autodetection or IP address(es) whitelist.
221:      * @param  string        error log directory; enables logging in production mode, FALSE means that logging is disabled
222:      * @param  string        administrator email; enables email sending in production mode
223:      * @return void
224:      */
225:     public static function enable($mode = NULL, $logDirectory = NULL, $email = NULL)
226:     {
227:         error_reporting(E_ALL | E_STRICT);
228: 
229:         // production/development mode detection
230:         if (is_bool($mode)) {
231:             self::$productionMode = $mode;
232: 
233:         } elseif ($mode !== self::DETECT || self::$productionMode === NULL) { // IP addresses or computer names whitelist detection
234:             $list = is_string($mode) ? preg_split('#[,\s]+#', $mode) : (array) $mode;
235:             if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
236:                 $list[] = '127.0.0.1';
237:                 $list[] = '::1';
238:             }
239:             self::$productionMode = !in_array(isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : php_uname('n'), $list, TRUE);
240:         }
241: 
242:         // logging configuration
243:         if (is_string($logDirectory)) {
244:             self::$logDirectory = realpath($logDirectory);
245:             if (self::$logDirectory === FALSE) {
246:                 throw new Nette\DirectoryNotFoundException("Directory '$logDirectory' is not found.");
247:             }
248:         } elseif ($logDirectory === FALSE) {
249:             self::$logDirectory = FALSE;
250: 
251:         } elseif (self::$logDirectory === NULL) {
252:             self::$logDirectory = defined('APP_DIR') ? APP_DIR . '/../log' : getcwd() . '/log';
253:         }
254:         if (self::$logDirectory) {
255:             ini_set('error_log', self::$logDirectory . '/php_error.log');
256:         }
257: 
258:         // php configuration
259:         if (function_exists('ini_set')) {
260:             ini_set('display_errors', !self::$productionMode); // or 'stderr'
261:             ini_set('html_errors', FALSE);
262:             ini_set('log_errors', FALSE);
263: 
264:         } elseif (ini_get('display_errors') != !self::$productionMode && ini_get('display_errors') !== (self::$productionMode ? 'stderr' : 'stdout')) { // intentionally ==
265:             throw new Nette\NotSupportedException('Function ini_set() must be enabled.');
266:         }
267: 
268:         if ($email) {
269:             if (!is_string($email)) {
270:                 throw new Nette\InvalidArgumentException('Email address must be a string.');
271:             }
272:             self::$email = $email;
273:         }
274: 
275:         if (!defined('E_DEPRECATED')) {
276:             define('E_DEPRECATED', 8192);
277:         }
278: 
279:         if (!defined('E_USER_DEPRECATED')) {
280:             define('E_USER_DEPRECATED', 16384);
281:         }
282: 
283:         if (!self::$enabled) {
284:             register_shutdown_function(array(__CLASS__, '_shutdownHandler'));
285:             set_exception_handler(array(__CLASS__, '_exceptionHandler'));
286:             set_error_handler(array(__CLASS__, '_errorHandler'));
287:             self::$enabled = TRUE;
288:         }
289:     }
290: 
291: 
292: 
293:     /**
294:      * Is Debug enabled?
295:      * @return bool
296:      */
297:     public static function isEnabled()
298:     {
299:         return self::$enabled;
300:     }
301: 
302: 
303: 
304:     /**
305:      * Logs message or exception to file (if not disabled) and sends email notification (if enabled).
306:      * @param  string|Exception
307:      * @param  int  one of constant Debugger::INFO, WARNING, ERROR (sends email), CRITICAL (sends email)
308:      * @return string logged error filename
309:      */
310:     public static function log($message, $priority = self::INFO)
311:     {
312:         if (self::$logDirectory === FALSE) {
313:             return;
314: 
315:         } elseif (!self::$logDirectory) {
316:             throw new Nette\InvalidStateException('Logging directory is not specified in Nette\Diagnostics\Debugger::$logDirectory.');
317:         }
318: 
319:         if ($message instanceof \Exception) {
320:             $exception = $message;
321:             $message = ($message instanceof Nette\FatalErrorException
322:                 ? 'Fatal error: ' . $exception->getMessage()
323:                 : get_class($exception) . ": " . $exception->getMessage())
324:                 . " in " . $exception->getFile() . ":" . $exception->getLine();
325: 
326:             $hash = md5($exception );
327:             $exceptionFilename = "exception-" . @date('Y-m-d-H-i-s') . "-$hash.html";
328:             foreach (new \DirectoryIterator(self::$logDirectory) as $entry) {
329:                 if (strpos($entry, $hash)) {
330:                     $exceptionFilename = $entry;
331:                     $saved = TRUE;
332:                     break;
333:                 }
334:             }
335:         }
336: 
337:         self::$logger->log(array(
338:             @date('[Y-m-d H-i-s]'),
339:             trim($message),
340:             self::$source ? ' @  ' . self::$source : NULL,
341:             !empty($exceptionFilename) ? ' @@  ' . $exceptionFilename : NULL
342:         ), $priority);
343: 
344:         if (!empty($exceptionFilename)) {
345:             $exceptionFilename = self::$logDirectory . '/' . $exceptionFilename;
346:             if (empty($saved) && $logHandle = @fopen($exceptionFilename, 'w')) {
347:                 ob_start(); // double buffer prevents sending HTTP headers in some PHP
348:                 ob_start(function($buffer) use ($logHandle) { fwrite($logHandle, $buffer); }, 4096);
349:                 self::$blueScreen->render($exception);
350:                 ob_end_flush();
351:                 ob_end_clean();
352:                 fclose($logHandle);
353:             }
354:             return strtr($exceptionFilename, '\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR);
355:         }
356:     }
357: 
358: 
359: 
360:     /**
361:      * Shutdown handler to catch fatal errors and execute of the planned activities.
362:      * @return void
363:      * @internal
364:      */
365:     public static function _shutdownHandler()
366:     {
367:         if (!self::$enabled) {
368:             return;
369:         }
370: 
371:         // fatal error handler
372:         static $types = array(
373:             E_ERROR => 1,
374:             E_CORE_ERROR => 1,
375:             E_COMPILE_ERROR => 1,
376:             E_PARSE => 1,
377:         );
378:         $error = error_get_last();
379:         if (isset($types[$error['type']])) {
380:             self::_exceptionHandler(new Nette\FatalErrorException($error['message'], 0, $error['type'], $error['file'], $error['line'], NULL));
381:         }
382: 
383:         // debug bar (require HTML & development mode)
384:         if (self::$bar && !self::$productionMode && self::isHtmlMode()) {
385:             self::$bar->render();
386:         }
387:     }
388: 
389: 
390: 
391:     /**
392:      * Handler to catch uncaught exception.
393:      * @param  \Exception
394:      * @return void
395:      * @internal
396:      */
397:     public static function _exceptionHandler(\Exception $exception)
398:     {
399:         if (!headers_sent()) { // for PHP < 5.2.4
400:             $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
401:             header($protocol . ' 500', TRUE, 500);
402:         }
403: 
404:         try {
405:             if (self::$productionMode) {
406:                 try {
407:                     self::log($exception, self::ERROR);
408:                 } catch (\Exception $e) {
409:                     echo 'FATAL ERROR: unable to log error';
410:                 }
411: 
412:                 if (self::$consoleMode) {
413:                     echo "ERROR: the server encountered an internal error and was unable to complete your request.\n";
414: 
415:                 } elseif (self::isHtmlMode()) {
416:                     require __DIR__ . '/templates/error.phtml';
417:                 }
418: 
419:             } else {
420:                 if (self::$consoleMode) { // dump to console
421:                     echo "$exception\n";
422:                     if ($file = self::log($exception)) {
423:                         echo "(stored in $file)\n";
424:                         if (self::$browser) {
425:                             exec(self::$browser . ' ' . escapeshellarg($file));
426:                         }
427:                     }
428: 
429:                 } elseif (self::isHtmlMode()) { // dump to browser
430:                     self::$blueScreen->render($exception);
431:                     if (self::$bar) {
432:                         self::$bar->render();
433:                     }
434: 
435:                 } elseif (!self::fireLog($exception, self::ERROR)) { // AJAX or non-HTML mode
436:                     $file = self::log($exception);
437:                     if (!headers_sent()) {
438:                         header("X-Nette-Error-Log: $file");
439:                     }
440:                 }
441:             }
442: 
443:             foreach (self::$onFatalError as $handler) {
444:                 call_user_func($handler, $exception);
445:             }
446: 
447:         } catch (\Exception $e) {
448:             if (self::$productionMode) {
449:                 echo self::isHtmlMode() ? '<meta name=robots content=noindex>FATAL ERROR' : 'FATAL ERROR';
450:             } else {
451:                 echo "FATAL ERROR: thrown ", get_class($e), ': ', $e->getMessage(),
452:                     "\nwhile processing ", get_class($exception), ': ', $exception->getMessage(), "\n";
453:             }
454:         }
455: 
456:         self::$enabled = FALSE; // un-register shutdown function
457:         exit(255);
458:     }
459: 
460: 
461: 
462:     /**
463:      * Handler to catch warnings and notices.
464:      * @param  int    level of the error raised
465:      * @param  string error message
466:      * @param  string file that the error was raised in
467:      * @param  int    line number the error was raised at
468:      * @param  array  an array of variables that existed in the scope the error was triggered in
469:      * @return bool   FALSE to call normal error handler, NULL otherwise
470:      * @throws Nette\FatalErrorException
471:      * @internal
472:      */
473:     public static function _errorHandler($severity, $message, $file, $line, $context)
474:     {
475:         if (self::$scream) {
476:             error_reporting(E_ALL | E_STRICT);
477:         }
478: 
479:         if (self::$lastError !== FALSE && ($severity & error_reporting()) === $severity) { // tryError mode
480:             self::$lastError = new \ErrorException($message, 0, $severity, $file, $line);
481:             return NULL;
482:         }
483: 
484:         if ($severity === E_RECOVERABLE_ERROR || $severity === E_USER_ERROR) {
485:             throw new Nette\FatalErrorException($message, 0, $severity, $file, $line, $context);
486: 
487:         } elseif (($severity & error_reporting()) !== $severity) {
488:             return FALSE; // calls normal error handler to fill-in error_get_last()
489: 
490:         } elseif (!self::$productionMode && (is_bool(self::$strictMode) ? self::$strictMode : ((self::$strictMode & $severity) === $severity))) {
491:             self::_exceptionHandler(new Nette\FatalErrorException($message, 0, $severity, $file, $line, $context));
492:         }
493: 
494:         static $types = array(
495:             E_WARNING => 'Warning',
496:             E_COMPILE_WARNING => 'Warning', // currently unable to handle
497:             E_USER_WARNING => 'Warning',
498:             E_NOTICE => 'Notice',
499:             E_USER_NOTICE => 'Notice',
500:             E_STRICT => 'Strict standards',
501:             E_DEPRECATED => 'Deprecated',
502:             E_USER_DEPRECATED => 'Deprecated',
503:         );
504: 
505:         $message = 'PHP ' . (isset($types[$severity]) ? $types[$severity] : 'Unknown error') . ": $message";
506:         $count = & self::$errorPanel->data["$message|$file|$line"];
507: 
508:         if ($count++) { // repeated error
509:             return NULL;
510: 
511:         } elseif (self::$productionMode) {
512:             self::log("$message in $file:$line", self::ERROR);
513:             return NULL;
514: 
515:         } else {
516:             $ok = self::fireLog(new \ErrorException($message, 0, $severity, $file, $line), self::WARNING);
517:             return !self::isHtmlMode() || (!self::$bar && !$ok) ? FALSE : NULL;
518:         }
519: 
520:         return FALSE; // call normal error handler
521:     }
522: 
523: 
524: 
525:     /**
526:      * Handles exception thrown in __toString().
527:      * @param  \Exception
528:      * @return void
529:      */
530:     public static function toStringException(\Exception $exception)
531:     {
532:         if (self::$enabled) {
533:             self::_exceptionHandler($exception);
534:         } else {
535:             trigger_error($exception->getMessage(), E_USER_ERROR);
536:         }
537:     }
538: 
539: 
540: 
541:     /**
542:      * Starts catching potential errors/warnings.
543:      * @return void
544:      */
545:     public static function tryError()
546:     {
547:         if (!self::$enabled && self::$lastError === FALSE) {
548:             set_error_handler(array(__CLASS__, '_errorHandler'));
549:         }
550:         self::$lastError = NULL;
551:     }
552: 
553: 
554: 
555:     /**
556:      * Returns catched error/warning message.
557:      * @param  \ErrorException  catched error
558:      * @return bool
559:      */
560:     public static function catchError(& $error)
561:     {
562:         if (!self::$enabled && self::$lastError !== FALSE) {
563:             restore_error_handler();
564:         }
565:         $error = self::$lastError;
566:         self::$lastError = FALSE;
567:         return (bool) $error;
568:     }
569: 
570: 
571: 
572:     /********************* useful tools ****************d*g**/
573: 
574: 
575: 
576:     /**
577:      * Dumps information about a variable in readable format.
578:      * @param  mixed  variable to dump
579:      * @param  bool   return output instead of printing it? (bypasses $productionMode)
580:      * @return mixed  variable itself or dump
581:      */
582:     public static function dump($var, $return = FALSE)
583:     {
584:         if (!$return && self::$productionMode) {
585:             return $var;
586:         }
587: 
588:         $output = "<pre class=\"nette-dump\">" . Helpers::htmlDump($var) . "</pre>\n";
589: 
590:         if (!$return) {
591:             $trace = debug_backtrace(FALSE);
592:             $i = Helpers::findTrace($trace, 'dump') ? 1 : 0;
593:             if (isset($trace[$i]['file'], $trace[$i]['line']) && is_file($trace[$i]['file'])) {
594:                 $lines = file($trace[$i]['file']);
595:                 preg_match('#dump\((.*)\)#', $lines[$trace[$i]['line'] - 1], $m);
596:                 $output = substr_replace(
597:                     $output,
598:                     ' title="' . htmlspecialchars((isset($m[0]) ? "$m[0] \n" : '') . "in file {$trace[$i]['file']} on line {$trace[$i]['line']}") . '"',
599:                     4, 0);
600: 
601:                 if (self::$showLocation) {
602:                     $output = substr_replace(
603:                         $output,
604:                         ' <small>in ' . Helpers::editorLink($trace[$i]['file'], $trace[$i]['line']) . ":{$trace[$i]['line']}</small>",
605:                         -8, 0);
606:                 }
607:             }
608:         }
609: 
610:         if (self::$consoleMode) {
611:             if (self::$consoleColors && substr(getenv('TERM'), 0, 5) === 'xterm') {
612:                 $output = preg_replace_callback('#<span class="php-(\w+)">|</span>#', function($m) {
613:                     return "\033[" . (isset($m[1], Debugger::$consoleColors[$m[1]]) ? Debugger::$consoleColors[$m[1]] : '0') . "m";
614:                 }, $output);
615:             }
616:             $output = htmlspecialchars_decode(strip_tags($output), ENT_QUOTES);
617:         }
618: 
619:         if ($return) {
620:             return $output;
621: 
622:         } else {
623:             echo $output;
624:             return $var;
625:         }
626:     }
627: 
628: 
629: 
630:     /**
631:      * Starts/stops stopwatch.
632:      * @param  string  name
633:      * @return float   elapsed seconds
634:      */
635:     public static function timer($name = NULL)
636:     {
637:         static $time = array();
638:         $now = microtime(TRUE);
639:         $delta = isset($time[$name]) ? $now - $time[$name] : 0;
640:         $time[$name] = $now;
641:         return $delta;
642:     }
643: 
644: 
645: 
646:     /**
647:      * Dumps information about a variable in Nette Debug Bar.
648:      * @param  mixed  variable to dump
649:      * @param  string optional title
650:      * @return mixed  variable itself
651:      */
652:     public static function barDump($var, $title = NULL)
653:     {
654:         if (!self::$productionMode) {
655:             $dump = array();
656:             foreach ((is_array($var) ? $var : array('' => $var)) as $key => $val) {
657:                 $dump[$key] = Helpers::clickableDump($val);
658:             }
659:             self::$dumpPanel->data[] = array('title' => $title, 'dump' => $dump);
660:         }
661:         return $var;
662:     }
663: 
664: 
665: 
666:     /**
667:      * Sends message to FireLogger console.
668:      * @param  mixed   message to log
669:      * @return bool    was successful?
670:      */
671:     public static function fireLog($message)
672:     {
673:         if (!self::$productionMode) {
674:             return self::$fireLogger->log($message);
675:         }
676:     }
677: 
678: 
679: 
680:     private static function isHtmlMode()
681:     {
682:         return !self::$ajaxDetected && !self::$consoleMode
683:             && !preg_match('#^Content-Type: (?!text/html)#im', implode("\n", headers_list()));
684:     }
685: 
686: 
687: 
688:     /** @deprecated */
689:     public static function addPanel(IBarPanel $panel, $id = NULL)
690:     {
691:         return self::$bar->addPanel($panel, $id);
692:     }
693: 
694: }
695: 
Nette Framework 2.0.4 API API documentation generated by ApiGen 2.7.0