diff --git a/dibi/dibi.php b/dibi/dibi.php index 82344b36..96e2b3fe 100644 --- a/dibi/dibi.php +++ b/dibi/dibi.php @@ -26,11 +26,11 @@ if (version_compare(PHP_VERSION, '5.2.0', '<')) { /** * Compatibility with Nette */ -if (interface_exists('Nette\\IDebugPanel')) { - class_alias('Nette\\IDebugPanel', 'IDebugPanel'); +if (interface_exists('Nette\Diagnostics\IBarPanel')) { + class_alias('Nette\Diagnostics\IBarPanel', 'IBarPanel'); -} elseif (!interface_exists('IDebugPanel')) { - interface IDebugPanel {} +} elseif (!interface_exists('IBarPanel')) { + interface IBarPanel {} } diff --git a/dibi/libs/DibiException.php b/dibi/libs/DibiException.php index 67d57775..7d4e1f2c 100644 --- a/dibi/libs/DibiException.php +++ b/dibi/libs/DibiException.php @@ -29,7 +29,7 @@ if (!defined('NETTE')) { * * @author David Grudl */ -class DibiException extends Exception implements IDebugPanel +class DibiException extends Exception { /** @var string */ private $sql; @@ -68,43 +68,6 @@ class DibiException extends Exception implements IDebugPanel return parent::__toString() . ($this->sql ? "\nSQL: " . $this->sql : ''); } - - - /********************* interface Nette\IDebugPanel ****************d*g**/ - - - - /** - * Returns HTML code for custom tab. - * @return mixed - */ - public function getTab() - { - return 'SQL'; - } - - - - /** - * Returns HTML code for custom panel. - * @return mixed - */ - public function getPanel() - { - return $this->sql ? dibi::dump($this->sql, TRUE) : NULL; - } - - - - /** - * Returns panel ID. - * @return string - */ - public function getId() - { - return __CLASS__; - } - } diff --git a/dibi/libs/DibiProfiler.php b/dibi/libs/DibiProfiler.php index 00c8bec4..cc33e7f7 100644 --- a/dibi/libs/DibiProfiler.php +++ b/dibi/libs/DibiProfiler.php @@ -22,7 +22,7 @@ * * @author David Grudl */ -class DibiProfiler extends DibiObject implements IDibiProfiler, IDebugPanel +class DibiProfiler extends DibiObject implements IDibiProfiler, IBarPanel { /** maximum number of rows */ static public $maxQueries = 30; @@ -52,12 +52,17 @@ class DibiProfiler extends DibiObject implements IDibiProfiler, IDebugPanel public function __construct(array $config) { - if (is_callable('Nette\Debug::addPanel')) { - call_user_func('Nette\Debug::addPanel', $this); - } elseif (is_callable('NDebug::addPanel')) { - NDebug::addPanel($this); - } elseif (is_callable('Debug::addPanel')) { - Debug::addPanel($this); + if (is_callable('Nette\Diagnostics\Debugger::enable')) { + eval('$tmp = Nette\Diagnostics\Debugger::$bar;'); + $tmp->addPanel($this); + eval('$tmp = Nette\Diagnostics\Debugger::$blueScreen;'); + $tmp->addPanel(array($this, 'renderException'), __CLASS__); + } elseif (is_callable('NDebugger::enable')) { + NDebugger::$bar->addPanel($this); + NDebugger::$blueScreen->addPanel(array($this, 'renderException'), __CLASS__); + } elseif (is_callable('Debugger::enable')) { + Debugger::$bar->addPanel($this); + Debugger::$blueScreen->addPanel(array($this, 'renderException'), __CLASS__); } $this->useFirebug = isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'FirePHP/'); @@ -77,6 +82,18 @@ class DibiProfiler extends DibiObject implements IDibiProfiler, IDebugPanel + public function renderException($e) + { + if ($e instanceof DibiException && $e->getSql()) { + return array( + 'tab' => 'SQL', + 'panel' => dibi::dump($e->getSql(), TRUE), + ); + } + } + + + /** * @param string filename * @return DibiProfiler provides a fluent interface @@ -242,7 +259,7 @@ class DibiProfiler extends DibiObject implements IDibiProfiler, IDebugPanel - /********************* interface Nette\IDebugPanel ****************d*g**/ + /********************* interface Nette\Diagnostics\IBarPanel ****************d*g**/ @@ -308,15 +325,4 @@ class DibiProfiler extends DibiObject implements IDibiProfiler, IDebugPanel '; } - - - /** - * Returns panel ID. - * @return string - */ - public function getId() - { - return get_class($this); - } - } diff --git a/examples/Nette/Debug.php b/examples/Nette/Debugger.php similarity index 76% rename from examples/Nette/Debug.php rename to examples/Nette/Debugger.php index b400a559..1872014f 100644 --- a/examples/Nette/Debug.php +++ b/examples/Nette/Debugger.php @@ -1,4 +1,4 @@ -data=&self::$errors;self::addPanel(new -DebugPanel('dumps',$tab,$panel));}public -static -function -enable($mode=NULL,$logDirectory=NULL,$email=NULL){error_reporting(E_ALL|E_STRICT);if(is_bool($mode)){self::$productionMode=$mode;}elseif(is_string($mode)){$mode=preg_split('#[,\s]+#',"$mode 127.0.0.1 ::1");}if(is_array($mode)){self::$productionMode=!isset($_SERVER['REMOTE_ADDR'])||!in_array($_SERVER['REMOTE_ADDR'],$mode,TRUE);}if(self::$productionMode===self::DETECT){if(class_exists('Environment')){self::$productionMode=Environment::isProduction();}elseif(isset($_SERVER['SERVER_ADDR'])||isset($_SERVER['LOCAL_ADDR'])){$addrs=array();if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){$addrs=preg_split('#,\s*#',$_SERVER['HTTP_X_FORWARDED_FOR']);}if(isset($_SERVER['REMOTE_ADDR'])){$addrs[]=$_SERVER['REMOTE_ADDR'];}$addrs[]=isset($_SERVER['SERVER_ADDR'])?$_SERVER['SERVER_ADDR']:$_SERVER['LOCAL_ADDR'];self::$productionMode=FALSE;foreach($addrs -as$addr){$oct=explode('.',$addr);if($addr!=='::1'&&(count($oct)!==4||($oct[0]!=='10'&&$oct[0]!=='127'&&($oct[0]!=='172'||$oct[1]<16||$oct[1]>31)&&($oct[0]!=='169'||$oct[1]!=='254')&&($oct[0]!=='192'||$oct[1]!=='168')))){self::$productionMode=TRUE;break;}}}else{self::$productionMode=!self::$consoleMode;}}if(is_string($logDirectory)){self::$logDirectory=realpath($logDirectory);if(self::$logDirectory===FALSE){throw -new -DirectoryNotFoundException("Directory '$logDirectory' is not found.");}}elseif($logDirectory===FALSE){self::$logDirectory=FALSE;}else{self::$logDirectory=defined('APP_DIR')?APP_DIR.'/../log':getcwd().'/log';}if(self::$logDirectory){ini_set('error_log',self::$logDirectory.'/php_error.log');}if(function_exists('ini_set')){ini_set('display_errors',!self::$productionMode);ini_set('html_errors',FALSE);ini_set('log_errors',FALSE);}elseif(ini_get('display_errors')!=!self::$productionMode&&ini_get('display_errors')!==(self::$productionMode?'stderr':'stdout')){throw -new -NotSupportedException('Function ini_set() must be enabled.');}if($email){if(!is_string($email)){throw -new -InvalidArgumentException('Email address must be a string.');}self::$email=$email;}if(!defined('E_DEPRECATED')){define('E_DEPRECATED',8192);}if(!defined('E_USER_DEPRECATED')){define('E_USER_DEPRECATED',16384);}if(!self::$enabled){register_shutdown_function(array(__CLASS__,'_shutdownHandler'));set_exception_handler(array(__CLASS__,'_exceptionHandler'));set_error_handler(array(__CLASS__,'_errorHandler'));self::$enabled=TRUE;}}public -static -function -isEnabled(){return -self::$enabled;}public -static -function -log($message,$priority=self::INFO){if(self::$logDirectory===FALSE){return;}elseif(!self::$logDirectory){throw -new -InvalidStateException('Logging directory is not specified in Debug::$logDirectory.');}elseif(!is_dir(self::$logDirectory)){throw -new -DirectoryNotFoundException("Directory '".self::$logDirectory."' is not found or is not directory.");}if($message -instanceof -Exception){$exception=$message;$message="PHP Fatal error: ".($message -instanceof -FatalErrorException?$exception->getMessage():"Uncaught exception ".get_class($exception)." with message '".$exception->getMessage()."'")." in ".$exception->getFile().":".$exception->getLine();}error_log(@date('[Y-m-d H-i-s] ').trim($message).(self::$source?' @ '.self::$source:'').PHP_EOL,3,self::$logDirectory.'/'.strtolower($priority).'.log');if(($priority===self::ERROR||$priority===self::CRITICAL)&&self::$email&&@filemtime(self::$logDirectory.'/email-sent')+self::$emailSnoozegetPrevious():(isset($exception->previous)?$exception->previous:'')));foreach(new -DirectoryIterator(self::$logDirectory)as$entry){if(strpos($entry,$hash)){$skip=TRUE;break;}}if(empty($skip)&&$logHandle=@fopen(self::$logDirectory."/exception ".@date('Y-m-d H-i-s')." $hash.html",'w')){ob_start();ob_start(create_function('$buffer','extract(NClosureFix::$vars['.NClosureFix::uses(array('logHandle'=>$logHandle)).'], EXTR_REFS); fwrite($logHandle, $buffer); '),1);DebugHelpers::renderBlueScreen($exception);ob_end_flush();ob_end_clean();fclose($logHandle);}}}public -static -function -_shutdownHandler(){static$types=array(E_ERROR=>1,E_CORE_ERROR=>1,E_COMPILE_ERROR=>1,E_PARSE=>1);$error=error_get_last();if(isset($types[$error['type']])){self::_exceptionHandler(new -FatalErrorException($error['message'],0,$error['type'],$error['file'],$error['line'],NULL));return;}if(self::$showBar&&!self::$productionMode&&!self::$ajaxDetected&&!self::$consoleMode&&(!preg_match('#^Content-Type: (?!text/html)#im',implode("\n",headers_list())))){DebugHelpers::renderDebugBar(self::$panels);}}public -static -function -_exceptionHandler(Exception$exception){if(!headers_sent()){header('HTTP/1.1 500 Internal Server Error');}$htmlMode=!self::$ajaxDetected&&!preg_match('#^Content-Type: (?!text/html)#im',implode("\n",headers_list()));try{if(self::$productionMode){self::log($exception,self::ERROR);if(self::$consoleMode){echo"ERROR: the server encountered an internal error and was unable to complete your request.\n";}elseif($htmlMode){echo"\n\n";echo"\n\n";echo"Server Error\n\n

Server Error

\n\n

We're sorry! The server encountered an internal error and was unable to complete your request. Please try again later.

\n\n

error 500

";}}else{if(self::$consoleMode){echo"$exception\n";}elseif($htmlMode){DebugHelpers::renderBlueScreen($exception);}elseif(!self::fireLog($exception,self::ERROR)){self::log($exception);}}foreach(self::$onFatalError -as$handler){call_user_func($handler,$exception);}}catch(Exception$e){echo"\nNette\\Debug FATAL ERROR: thrown ",get_class($e),': ',$e->getMessage(),"\nwhile processing ",get_class($exception),': ',$exception->getMessage(),"\n";exit;}}public -static -function -_errorHandler($severity,$message,$file,$line,$context){if(self::$lastError!==FALSE){self::$lastError=new -ErrorException($message,0,$severity,$file,$line);return -NULL;}if(self::$scream){error_reporting(E_ALL|E_STRICT);}if($severity===E_RECOVERABLE_ERROR||$severity===E_USER_ERROR){throw -new -FatalErrorException($message,0,$severity,$file,$line,$context);}elseif(($severity&error_reporting())!==$severity){return -FALSE;}elseif(self::$strictMode&&!self::$productionMode){self::_exceptionHandler(new -FatalErrorException($message,0,$severity,$file,$line,$context));exit;}static$types=array(E_WARNING=>'Warning',E_COMPILE_WARNING=>'Warning',E_USER_WARNING=>'Warning',E_NOTICE=>'Notice',E_USER_NOTICE=>'Notice',E_STRICT=>'Strict standards',E_DEPRECATED=>'Deprecated',E_USER_DEPRECATED=>'Deprecated');$message='PHP '.(isset($types[$severity])?$types[$severity]:'Unknown error').": $message";$count=&self::$errors["$message|$file|$line"];if($count++){return -NULL;}elseif(self::$productionMode){self::log("$message in $file:$line",self::ERROR);return -NULL;}else{$ok=self::fireLog(new -ErrorException($message,0,$severity,$file,$line),self::WARNING);return -self::$consoleMode||(!self::$showBar&&!$ok)?FALSE:NULL;}return -FALSE;}public -static -function -processException(Exception$exception){trigger_error(__METHOD__.'() is deprecated; use '.__CLASS__.'::log($exception, Debug::ERROR) instead.',E_USER_WARNING);self::log($exception,self::ERROR);}public -static -function -toStringException(Exception$exception){if(self::$enabled){self::_exceptionHandler($exception);}else{trigger_error($exception->getMessage(),E_USER_ERROR);}exit;}public -static -function -tryError(){if(!self::$enabled&&self::$lastError===FALSE){set_error_handler(array(__CLASS__,'_errorHandler'));}self::$lastError=NULL;}public -static -function -catchError(&$error){if(!self::$enabled&&self::$lastError!==FALSE){restore_error_handler();}$error=self::$lastError;self::$lastError=FALSE;return(bool)$error;}private -static -function -defaultMailer($message){$host=isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:(isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'');$parts=str_replace(array("\r\n","\n"),array("\n",PHP_EOL),array('headers'=>"From: noreply@$host\nX-Mailer: Nette Framework\n",'subject'=>"PHP: An error occurred on the server $host",'body'=>"[".@date('Y-m-d H:i:s')."] $message"));mail(self::$email,$parts['subject'],$parts['body'],$parts['headers']);}public -static -function -dump($var,$return=FALSE){if(!$return&&self::$productionMode){return$var;}$output="
".DebugHelpers::htmlDump($var)."
\n";if(!$return&&self::$showLocation){$trace=debug_backtrace();$i=isset($trace[1]['class'])&&$trace[1]['class']===__CLASS__?1:0;if(isset($trace[$i]['file'],$trace[$i]['line'])){$output=substr_replace($output,' '.htmlspecialchars("in file {$trace[$i]['file']} on line {$trace[$i]['line']}",ENT_NOQUOTES).'',-8,0);}}if(self::$consoleMode){$output=htmlspecialchars_decode(strip_tags($output),ENT_NOQUOTES);}if($return){return$output;}else{echo$output;return$var;}}public -static -function -timer($name=NULL){static$time=array();$now=microtime(TRUE);$delta=isset($time[$name])?$now-$time[$name]:0;$time[$name]=$now;return$delta;}public -static -function -addPanel(IDebugPanel$panel){self::$panels[]=$panel;}public -static -function -barDump($var,$title=NULL){if(!self::$productionMode){$dump=array();foreach((is_array($var)?$var:array(''=>$var))as$key=>$val){$dump[$key]=DebugHelpers::clickableDump($val);}self::$panels[3]->data[]=array('title'=>$title,'dump'=>$dump);}return$var;}public -static -function -fireLog($message){if(self::$productionMode){return;}elseif(!self::$firebugDetected||headers_sent()){return -FALSE;}static$payload=array('logs'=>array());$item=array('name'=>'PHP','level'=>'debug','order'=>count($payload['logs']),'time'=>str_pad(number_format((microtime(TRUE)-self::$time)*1000,1,'.',' '),8,'0',STR_PAD_LEFT).' ms','template'=>'','message'=>'','style'=>'background:#767ab6');$args=func_get_args();if(isset($args[0])&&is_string($args[0])){$item['template']=array_shift($args);}if(isset($args[0])&&$args[0]instanceof -Exception){$e=array_shift($args);$trace=$e->getTrace();if(isset($trace[0]['class'])&&$trace[0]['class']===__CLASS__&&($trace[0]['function']==='_shutdownHandler'||$trace[0]['function']==='_errorHandler')){unset($trace[0]);}$item['exc_info']=array($e->getMessage(),$e->getFile(),array());$item['exc_frames']=array();foreach($trace -as$frame){$frame+=array('file'=>NULL,'line'=>NULL,'class'=>NULL,'type'=>NULL,'function'=>NULL,'object'=>NULL,'args'=>NULL);$item['exc_info'][2][]=array($frame['file'],$frame['line'],"$frame[class]$frame[type]$frame[function]",$frame['object']);$item['exc_frames'][]=$frame['args'];}$file=str_replace(dirname(dirname(dirname($e->getFile()))),"\xE2\x80\xA6",$e->getFile());$item['template']=($e -instanceof -ErrorException?'':get_class($e).': ').$e->getMessage().($e->getCode()?' #'.$e->getCode():'').' in '.$file.':'.$e->getLine();array_unshift($trace,array('file'=>$e->getFile(),'line'=>$e->getLine()));}else{$trace=debug_backtrace();if(isset($trace[0]['class'])&&$trace[0]['class']===__CLASS__&&($trace[0]['function']==='_shutdownHandler'||$trace[0]['function']==='_errorHandler')){unset($trace[0]);}}if(isset($args[0])&&in_array($args[0],array(self::DEBUG,self::INFO,self::WARNING,self::ERROR,self::CRITICAL),TRUE)){$item['level']=array_shift($args);}$item['args']=$args;foreach($trace -as$frame){if(isset($frame['file'])&&is_file($frame['file'])){$item['pathname']=$frame['file'];$item['lineno']=$frame['line'];break;}}$payload['logs'][]=DebugHelpers::jsonDump($item,-1);foreach(str_split(base64_encode(@json_encode($payload)),4990)as$k=>$v){header("FireLogger-de11e-$k:$v");}return -TRUE;}}class -FatalErrorException -extends -Exception{private$severity;public -function -__construct($message,$code,$severity,$file,$line,$context){parent::__construct($message,$code);$this->severity=$severity;$this->file=$file;$this->line=$line;$this->context=$context;}public -function -getSeverity(){return$this->severity;}}interface -IDebugPanel{function +interface +IBarPanel{function getTab();function -getPanel();function -getId();}class -DebugPanel -implements -IDebugPanel{private$id;private$tabCb;private$panelCb;public$data;public +getPanel();}class +DebugBar{private$panels=array();public function -__construct($id,$tabCb,$panelCb){$this->id=$id;$this->tabCb=$tabCb;$this->panelCb=$panelCb;}public +addPanel(IBarPanel$panel,$id=NULL){if($id===NULL){$c=0;do{$id=get_class($panel).($c++?"-$c":'');}while(isset($this->panels[$id]));}$this->panels[$id]=$panel;}public function -getId(){return$this->id;}public +render(){$panels=array();foreach($this->panels +as$id=>$panel){try{$panels[]=array('id'=>preg_replace('#[^a-z0-9]+#i','-',$id),'tab'=>$tab=(string)$panel->getTab(),'panel'=>$tab?(string)$panel->getPanel():NULL);}catch(Exception$e){$panels[]=array('id'=>"error-$id",'tab'=>"Error: $id",'panel'=>nl2br(htmlSpecialChars((string)$e)));}}?> + + + + + + +  + + + + + + + + + +$panel):if(!$panel['panel'])continue;?> +
+
+ +
+ ¤ + × +
+
+
+ + +
+
+
    + + +
  • ',trim($panel['tab']),'';endif?>
  • + +
  • ×
  • +
+
+
+ + + +
+ + + + +tabCb,$this->id,$this->data);return -ob_get_clean();}public +addPanel($panel,$id=NULL){if($id===NULL){$this->panels[]=$panel;}else{$this->panels[$id]=$panel;}}public function -getPanel(){ob_start();call_user_func($this->panelCb,$this->id,$this->data);return -ob_get_clean();}}final -class -DebugHelpers{public -static -function -renderBlueScreen(Exception$exception){if(class_exists('Environment',FALSE)){$application=Environment::getContext()->hasService('Nette\\Application\\Application',TRUE)?Environment::getContext()->getService('Nette\\Application\\Application'):NULL;}static$errorTypes=array(E_ERROR=>'Fatal Error',E_USER_ERROR=>'User Error',E_RECOVERABLE_ERROR=>'Recoverable Error',E_CORE_ERROR=>'Core Error',E_COMPILE_ERROR=>'Compile Error',E_PARSE=>'Parse Error',E_WARNING=>'Warning',E_CORE_WARNING=>'Core Warning',E_COMPILE_WARNING=>'Compile Warning',E_USER_WARNING=>'User Warning',E_NOTICE=>'Notice',E_USER_NOTICE=>'User Notice',E_STRICT=>'Strict',E_DEPRECATED=>'Deprecated',E_USER_DEPRECATED=>'User Deprecated');$title=($exception +render(Exception$exception){if(class_exists('Environment',FALSE)){$application=Environment::getContext()->hasService('Nette\\Application\\Application',TRUE)?Environment::getContext()->getService('Nette\\Application\\Application'):NULL;}$panels=$this->panels;static$errorTypes=array(E_ERROR=>'Fatal Error',E_USER_ERROR=>'User Error',E_RECOVERABLE_ERROR=>'Recoverable Error',E_CORE_ERROR=>'Core Error',E_COMPILE_ERROR=>'Compile Error',E_PARSE=>'Parse Error',E_WARNING=>'Warning',E_CORE_WARNING=>'Core Warning',E_COMPILE_WARNING=>'Compile Warning',E_USER_WARNING=>'User Warning',E_NOTICE=>'Notice',E_USER_NOTICE=>'User Notice',E_STRICT=>'Strict',E_DEPRECATED=>'Deprecated',E_USER_DEPRECATED=>'User Deprecated');$title=($exception instanceof -FatalErrorException&&isset($errorTypes[$exception->getSeverity()]))?$errorTypes[$exception->getSeverity()]:get_class($exception);$expandPath=NETTE_DIR.DIRECTORY_SEPARATOR;$counter=0;if(headers_sent()){echo'';}?> +FatalErrorException&&isset($errorTypes[$exception->getSeverity()]))?$errorTypes[$exception->getSeverity()]:get_class($exception);$expandPath=NETTE_DIR.DIRECTORY_SEPARATOR;$counter=0;?> + @@ -216,17 +165,17 @@ htmlspecialchars($ex->getMessage())?>

- getTab())&&($panel=$ex->getPanel())):?> + +

+htmlSpecialChars($panel['tab'])?>
- +
- + @@ -238,17 +187,17 @@ as$key=>$row){if(isset($row['file'])&&strpos($row['file'],$expandPath)!==0){$exp

Source file

-

File: getFile(),$ex->getLine())),'">'?> +

File: getFile(),$ex->getLine())),'">'?> getFile()),(Debug::$editor?'':'')?>   Line: getLine()?>

+htmlspecialchars($ex->getFile()),(Debugger::$editor?'':'')?>   Line: getLine()?>

getFile(),$ex->getLine())?>
+self::highlightFile($ex->getFile(),$ex->getLine())?>
- +

Call stack

@@ -261,10 +210,10 @@ as$key=>$row):?> title=" title=""> ',htmlSpecialChars(basename($row['file'])),'',(Debug::$editor?'':''),' (',$row['line'],')'?> +htmlSpecialChars(basename(dirname($row['file']))),'/',htmlSpecialChars(basename($row['file'])),'',(Debugger::$editor?'':''),' (',$row['line'],')'?> inner-code @@ -293,7 +242,7 @@ DebugHelpers::clickableDump($v);echo"\n";}?>
 id="netteBsSrc">
+self::highlightFile($row['file'],$row['line'])?> @@ -438,14 +387,14 @@ htmlspecialchars($s),'
';?>