diff --git a/examples/Nette/Debugger.php b/examples/Nette/Debugger.php index aaecb907..9e314309 100644 --- a/examples/Nette/Debugger.php +++ b/examples/Nette/Debugger.php @@ -2,7 +2,7 @@ /** * This file is part of the Nette Framework (http://nette.org) * - * Copyright (c) 2004, 2012 David Grudl (http://davidgrudl.com) + * Copyright (c) 2004 David Grudl (http://davidgrudl.com) * * For the full copyright and license information, please view * the file license.txt that was distributed with this source code. @@ -15,9 +15,9 @@ define('NETTE_DIR',dirname(__FILE__));interface IBarPanel{function getTab();function getPanel();}class -DebugBar{private$panels=array();public +NDebugBar{private$panels=array();public function -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 +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;return$this;}public function render(){$obLevel=ob_get_level();$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)));while(ob_get_level()>$obLevel){ob_end_clean();}}}?> @@ -29,33 +29,33 @@ as$id=>$panel){try{$panels[]=array('id'=>preg_replace('#[^a-z0-9]+#i','-',$id),'   - + +(function(){Nette.Class=function(a){var b=a.constructor||function(){},c,f=Object.prototype.hasOwnProperty;delete a.constructor;if(a.Extends){var d=function(){this.constructor=b};d.prototype=a.Extends.prototype;b.prototype=new d;delete a.Extends}if(a.Static){for(c in a.Static)f.call(a.Static,c)&&(b[c]=a.Static[c]);delete a.Static}for(c in a)f.call(a,c)&&(b.prototype[c]=a[c]);return b};Nette.Q=Nette.Class({Static:{factory:function(a){return new Nette.Q(a)},implement:function(a){var b,c=Nette.Q.implement, +f=Nette.Q.prototype,d=Object.prototype.hasOwnProperty;for(b in a)d.call(a,b)&&(c[b]=a[b],f[b]=function(a){return function(){return this.each(c[a],arguments)}}(b))}},constructor:function(a){if("string"===typeof a)a=this._find(document,a);else if(!a||a.nodeType||void 0===a.length||a===window)a=[a];for(var b=0,c=a.length;ba)return null;if("select-one"===this.type)return b[a].value;for(a=0,values=[],len=b.length;a $panel):if(!$panel['panel'])continue;?>
@@ -296,7 +300,7 @@ $list=get_defined_constants(TRUE);if(!empty($list['user'])):?> $v){echo'';echo'\n";}?> +foreach($list['user']as$k=>$v){echo'';echo'\n";}?>
',htmlspecialchars($k),'',DebugHelpers::clickableDump($v),"
',htmlspecialchars($k),'',NDebugHelpers::clickableDump($v),"
@@ -326,7 +330,7 @@ preg_replace('#^.+|.+$#s','',ob_get_clean())?> $v)echo'',htmlspecialchars($k),'',DebugHelpers::clickableDump($v),"\n";?> +as$k=>$v)echo'',htmlspecialchars($k),'',NDebugHelpers::clickableDump($v),"\n";?> @@ -350,7 +354,8 @@ foreach(apache_request_headers()as$k=>$v)echo'',htmlspecialchars($k),' -

$

+

$

empty

@@ -358,7 +363,7 @@ foreach(apache_request_headers()as$k=>$v)echo'',htmlspecialchars($k),' $v)echo'',htmlspecialchars($k),'',DebugHelpers::clickableDump($v),"\n";?> +foreach($GLOBALS[$name]as$k=>$v)echo'',htmlspecialchars($k),'',NDebugHelpers::clickableDump($v),"\n";?> @@ -398,43 +403,47 @@ htmlSpecialChars($panel['tab'])?> - + ',$source[1]);array_unshift($source,NULL);$i=$start;while(--$i>=1){if(preg_match('#.*(]*>)#',$source[$i],$m)){if($m[1]!==''){$spans++;$out.=$m[1];}break;}}$source=array_slice($source,$start,$count,TRUE);end($source);$numWidth=strlen((string)key($source));foreach($source -as$n=>$s){$spans+=substr_count($s,']+>#',$s,$tags);if($n===$line){$out.=sprintf("%{$numWidth}s: %s\n%s",$n,strip_tags($s),implode('',$tags[0]));}else{$out.=sprintf("%{$numWidth}s: %s\n",$n,$s);}}$out.=str_repeat('',$spans).'';$out=preg_replace_callback('#">\$(\w+)( )?#',create_function('$m','extract(NCFix::$vars['.NCFix::uses(array('vars'=>$vars)).'], EXTR_REFS); +highlightFile($file,$line,$lines=15,$vars=array()){$source=@file_get_contents($file);if($source){return +self::highlightPhp($source,$line,$lines,$vars);}}public +static +function +highlightPhp($source,$line,$lines=15,$vars=array()){if(function_exists('ini_set')){ini_set('highlight.comment','#998; font-style: italic');ini_set('highlight.default','#000');ini_set('highlight.html','#06B');ini_set('highlight.keyword','#D24; font-weight: bold');ini_set('highlight.string','#080');}$source=str_replace(array("\r\n","\r"),"\n",$source);$source=explode("\n",highlight_string($source,TRUE));$spans=1;$out=$source[0];$source=explode('
',$source[1]);array_unshift($source,NULL);$start=$i=max(1,$line-floor($lines*2/3));while(--$i>=1){if(preg_match('#.*(]*>)#',$source[$i],$m)){if($m[1]!==''){$spans++;$out.=$m[1];}break;}}$source=array_slice($source,$start,$lines,TRUE);end($source);$numWidth=strlen((string)key($source));foreach($source +as$n=>$s){$spans+=substr_count($s,']+>#',$s,$tags);if($n==$line){$out.=sprintf("%{$numWidth}s: %s\n%s",$n,strip_tags($s),implode('',$tags[0]));}else{$out.=sprintf("%{$numWidth}s: %s\n",$n,$s);}}$out.=str_repeat('',$spans).'';$out=preg_replace_callback('#">\$(\w+)( )?#',create_function('$m','extract(NCFix::$vars['.NCFix::uses(array('vars'=>$vars)).'], EXTR_REFS); return isset($vars[$m[1]]) - ? \'" title="\' . str_replace(\'"\', \'"\', strip_tags(DebugHelpers::htmlDump($vars[$m[1]]))) . $m[0] + ? \'" title="\' . str_replace(\'"\', \'"\', strip_tags(NDebugHelpers::htmlDump($vars[$m[1]]))) . $m[0] : $m[0]; - '),$out);return$out;}}final + '),$out);return"
$out
";}}final class -DefaultBarPanel +NDefaultBarPanel implements IBarPanel{private$id;public$data;public function @@ -443,7 +452,7 @@ function getTab(){ob_start();$data=$this->data;if($this->id==='time'){?> ms +number_format((microtime(TRUE)-NDebugger::$time)*1000,1,'.',' ')?> ms id==='memory'){?> $count):list($message,$file,$line)=explode('|',$item)?> 2?'nette-alt':''?>">
+htmlspecialchars($message),' in ',NDebugHelpers::editorLink($file,$line),':',$line?> array());public static function log($message,$priority=self::DEBUG){if(!isset($_SERVER['HTTP_X_FIRELOGGER'])||headers_sent()){return -FALSE;}$item=array('name'=>'PHP','level'=>$priority,'order'=>count(self::$payload['logs']),'time'=>str_pad(number_format((microtime(TRUE)-Debugger::$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']==='Debugger'&&($trace[0]['function']==='_shutdownHandler'||$trace[0]['function']==='_errorHandler')){unset($trace[0]);}$file=str_replace(dirname(dirname(dirname($e->getFile()))),"\xE2\x80\xA6",$e->getFile());$item['template']=($e +FALSE;}$item=array('name'=>'PHP','level'=>$priority,'order'=>count(self::$payload['logs']),'time'=>str_pad(number_format((microtime(TRUE)-NDebugger::$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']==='NDebugger'&&($trace[0]['function']==='_shutdownHandler'||$trace[0]['function']==='_errorHandler')){unset($trace[0]);}$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();$item['pathname']=$e->getFile();$item['lineno']=$e->getLine();}else{$trace=debug_backtrace();if(isset($trace[1]['class'])&&$trace[1]['class']==='Debugger'&&($trace[1]['function']==='fireLog')){unset($trace[0]);}foreach($trace +ErrorException?'':get_class($e).': ').$e->getMessage().($e->getCode()?' #'.$e->getCode():'').' in '.$file.':'.$e->getLine();$item['pathname']=$e->getFile();$item['lineno']=$e->getLine();}else{$trace=debug_backtrace();if(isset($trace[1]['class'])&&$trace[1]['class']==='NDebugger'&&($trace[1]['function']==='fireLog')){unset($trace[0]);}foreach($trace as$frame){if(isset($frame['file'])&&is_file($frame['file'])){$item['pathname']=$frame['file'];$item['lineno']=$frame['line'];break;}}}$item['exc_info']=array('','',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'];}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;self::$payload['logs'][]=self::jsonDump($item,-1);foreach(str_split(base64_encode(@json_encode(self::$payload)),4990)as$k=>$v){header("FireLogger-de11e-$k:$v");}return TRUE;}private static function -jsonDump(&$var,$level=0){if(is_bool($var)||is_null($var)||is_int($var)||is_float($var)){return$var;}elseif(is_string($var)){if(Debugger::$maxLen&&strlen($var)>Debugger::$maxLen){$var=substr($var,0,Debugger::$maxLen)." \xE2\x80\xA6 ";}return@iconv('UTF-16','UTF-8//IGNORE',iconv('UTF-8','UTF-16//IGNORE',$var));}elseif(is_array($var)){static$marker;if($marker===NULL){$marker=uniqid("\x00",TRUE);}if(isset($var[$marker])){return"\xE2\x80\xA6RECURSION\xE2\x80\xA6";}elseif($level&$v){if($k!==$marker){$res[self::jsonDump($k)]=self::jsonDump($v,$level+1);}}unset($var[$marker]);return$res;}else{return" \xE2\x80\xA6 ";}}elseif(is_object($var)){$arr=(array)$var;static$list=array();if(in_array($var,$list,TRUE)){return"\xE2\x80\xA6RECURSION\xE2\x80\xA6";}elseif($level'(object) '.get_class($var));foreach($arr +jsonDump(&$var,$level=0){if(is_bool($var)||is_null($var)||is_int($var)||is_float($var)){return$var;}elseif(is_string($var)){if(NDebugger::$maxLen&&strlen($var)>NDebugger::$maxLen){$var=substr($var,0,NDebugger::$maxLen)." \xE2\x80\xA6 ";}return@iconv('UTF-16','UTF-8//IGNORE',iconv('UTF-8','UTF-16//IGNORE',$var));}elseif(is_array($var)){static$marker;if($marker===NULL){$marker=uniqid("\x00",TRUE);}if(isset($var[$marker])){return"\xE2\x80\xA6RECURSION\xE2\x80\xA6";}elseif($level&$v){if($k!==$marker){$res[self::jsonDump($k)]=self::jsonDump($v,$level+1);}}unset($var[$marker]);return$res;}else{return" \xE2\x80\xA6 ";}}elseif(is_object($var)){$arr=(array)$var;static$list=array();if(in_array($var,$list,TRUE)){return"\xE2\x80\xA6RECURSION\xE2\x80\xA6";}elseif($level'(object) '.get_class($var));foreach($arr as$k=>&$v){if($k[0]==="\x00"){$k=substr($k,strrpos($k,"\x00")+1);}$res[self::jsonDump($k)]=self::jsonDump($v,$level+1);}array_pop($list);return$res;}else{return" \xE2\x80\xA6 ";}}elseif(is_resource($var)){return"resource ".get_resource_type($var);}else{return"unknown type";}}}final class -DebugHelpers{public +NDebugHelpers{public static function -editorLink($file,$line){if(Debugger::$editor&&is_file($file)){$dir=dirname(strtr($file,'/',DIRECTORY_SEPARATOR));$base=isset($_SERVER['SCRIPT_FILENAME'])?dirname(dirname(strtr($_SERVER['SCRIPT_FILENAME'],'/',DIRECTORY_SEPARATOR))):dirname($dir);if(substr($dir,0,strlen($base))===$base){$dir='...'.substr($dir,strlen($base));}return -Html::el('a')->href(strtr(Debugger::$editor,array('%file'=>rawurlencode($file),'%line'=>$line)))->title("$file:$line")->setHtml(htmlSpecialChars(rtrim($dir,DIRECTORY_SEPARATOR)).DIRECTORY_SEPARATOR.''.htmlSpecialChars(basename($file)).'');}else{return -Html::el('span')->setText($file);}}public +editorLink($file,$line){if(NDebugger::$editor&&is_file($file)){$dir=dirname(strtr($file,'/',DIRECTORY_SEPARATOR));$base=isset($_SERVER['SCRIPT_FILENAME'])?dirname(dirname(strtr($_SERVER['SCRIPT_FILENAME'],'/',DIRECTORY_SEPARATOR))):dirname($dir);if(substr($dir,0,strlen($base))===$base){$dir='...'.substr($dir,strlen($base));}return +NHtml::el('a')->href(strtr(NDebugger::$editor,array('%file'=>rawurlencode($file),'%line'=>$line)))->title("$file:$line")->setHtml(htmlSpecialChars(rtrim($dir,DIRECTORY_SEPARATOR)).DIRECTORY_SEPARATOR.''.htmlSpecialChars(basename($file)).'');}else{return +NHtml::el('span')->setText($file);}}public static function -htmlDump(&$var,$level=0){static$tableUtf,$tableBin,$reBinary='#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{10FFFF}]#u';if($tableUtf===NULL){foreach(range("\x00","\xFF")as$ch){if(ord($ch)<32&&strpos("\r\n\t",$ch)===FALSE){$tableUtf[$ch]=$tableBin[$ch]='\\x'.str_pad(dechex(ord($ch)),2,'0',STR_PAD_LEFT);}elseif(ord($ch)<127){$tableUtf[$ch]=$tableBin[$ch]=$ch;}else{$tableUtf[$ch]=$ch;$tableBin[$ch]='\\x'.dechex(ord($ch));}}$tableBin["\\"]='\\\\';$tableBin["\r"]='\\r';$tableBin["\n"]='\\n';$tableBin["\t"]='\\t';$tableUtf['\\x']=$tableBin['\\x']='\\\\x';}if(is_bool($var)){return''.($var?'TRUE':'FALSE')."\n";}elseif($var===NULL){return"NULL\n";}elseif(is_int($var)){return"$var\n";}elseif(is_float($var)){$var=var_export($var,TRUE);if(strpos($var,'.')===FALSE){$var.='.0';}return"$var\n";}elseif(is_string($var)){if(Debugger::$maxLen&&strlen($var)>Debugger::$maxLen){$s=htmlSpecialChars(substr($var,0,Debugger::$maxLen),ENT_NOQUOTES).' ... ';}else{$s=htmlSpecialChars($var,ENT_NOQUOTES);}$s=strtr($s,preg_match($reBinary,$s)||preg_last_error()?$tableBin:$tableUtf);$len=strlen($var);return"\"$s\"".($len>1?" ($len)":"")."\n";}elseif(is_array($var)){$s='array('.count($var).") ";$space=str_repeat($space1=' ',$level);$brackets=range(0,count($var)-1)===array_keys($var)?"[]":"{}";static$marker;if($marker===NULL){$marker=uniqid("\x00",TRUE);}if(empty($var)){}elseif(isset($var[$marker])){$brackets=$var[$marker];$s.="$brackets[0] *RECURSION* $brackets[1]";}elseif($level$brackets[0]\n";$var[$marker]=$brackets;foreach($var +htmlDump(&$var,$level=0){static$tableUtf,$tableBin,$reBinary='#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{10FFFF}]#u';if($tableUtf===NULL){foreach(range("\x00","\xFF")as$ch){if(ord($ch)<32&&strpos("\r\n\t",$ch)===FALSE){$tableUtf[$ch]=$tableBin[$ch]='\\x'.str_pad(dechex(ord($ch)),2,'0',STR_PAD_LEFT);}elseif(ord($ch)<127){$tableUtf[$ch]=$tableBin[$ch]=$ch;}else{$tableUtf[$ch]=$ch;$tableBin[$ch]='\\x'.dechex(ord($ch));}}$tableBin["\\"]='\\\\';$tableBin["\r"]='\\r';$tableBin["\n"]='\\n';$tableBin["\t"]='\\t';$tableUtf['\\x']=$tableBin['\\x']='\\\\x';}if(is_bool($var)){return''.($var?'TRUE':'FALSE')."\n";}elseif($var===NULL){return"NULL\n";}elseif(is_int($var)){return"$var\n";}elseif(is_float($var)){$var=var_export($var,TRUE);if(strpos($var,'.')===FALSE){$var.='.0';}return"$var\n";}elseif(is_string($var)){if(NDebugger::$maxLen&&strlen($var)>NDebugger::$maxLen){$s=htmlSpecialChars(substr($var,0,NDebugger::$maxLen),ENT_NOQUOTES,'ISO-8859-1').' ... ';}else{$s=htmlSpecialChars($var,ENT_NOQUOTES,'ISO-8859-1');}$s=strtr($s,preg_match($reBinary,$s)||preg_last_error()?$tableBin:$tableUtf);$len=strlen($var);return"\"$s\"".($len>1?" ($len)":"")."\n";}elseif(is_array($var)){$s='array('.count($var).") ";$space=str_repeat($space1=' ',$level);$brackets=range(0,count($var)-1)===array_keys($var)?"[]":"{}";static$marker;if($marker===NULL){$marker=uniqid("\x00",TRUE);}if(empty($var)){}elseif(isset($var[$marker])){$brackets=$var[$marker];$s.="$brackets[0] *RECURSION* $brackets[1]";}elseif($level$brackets[0]\n";$var[$marker]=$brackets;foreach($var as$k=>&$v){if($k===$marker){continue;}$k=strtr($k,preg_match($reBinary,$k)||preg_last_error()?$tableBin:$tableUtf);$k=htmlSpecialChars(preg_match('#^\w+$#',$k)?$k:"\"$k\"");$s.="$space$space1$k => ".self::htmlDump($v,$level+1);}unset($var[$marker]);$s.="$space$brackets[1]";}else{$s.="$brackets[0] ... $brackets[1]";}return$s."\n";}elseif(is_object($var)){if($var instanceof Closure){$rc=new -ReflectionFunction($var);$arr=array();foreach($rc->getParameters()as$param){$arr[]='$'.$param->getName();}$arr=array('file'=>$rc->getFileName(),'line'=>$rc->getStartLine(),'parameters'=>implode(', ',$arr));}else{$arr=(array)$var;}$s=''.get_class($var)."(".count($arr).") ";$space=str_repeat($space1=' ',$level);static$list=array();if(empty($arr)){}elseif(in_array($var,$list,TRUE)){$s.="{ *RECURSION* }";}elseif($levelgetParameters()as$param){$arr[]='$'.$param->getName();}$arr=array('file'=>$rc->getFileName(),'line'=>$rc->getStartLine(),'parameters'=>implode(', ',$arr));}else{$arr=(array)$var;}$s=''.get_class($var)."(".count($arr).") ";$space=str_repeat($space1=' ',$level);static$list=array();if(empty($arr)){}elseif(in_array($var,$list,TRUE)){$s.="{ *RECURSION* }";}elseif($level&$v){$m='';if($k[0]==="\x00"){$m=' '.($k[1]==='*'?'protected':'private').'';$k=substr($k,strrpos($k,"\x00")+1);}$k=strtr($k,preg_match($reBinary,$k)||preg_last_error()?$tableBin:$tableUtf);$k=htmlSpecialChars(preg_match('#^\w+$#',$k)?$k:"\"$k\"");$s.="$space$space1$k$m => ".self::htmlDump($v,$level+1);}array_pop($list);$s.="$space}";}else{$s.="{ ... }";}return$s."\n";}elseif(is_resource($var)){return''.htmlSpecialChars(get_resource_type($var))." resource\n";}else{return"unknown type\n";}}public static function -clickableDump($dump){return'
'.preg_replace_callback('#^( *)((?>[^(\r\n]{1,200}))\((\d+)\) #m',create_function('$m','
+clickableDump($dump,$collapsed=FALSE){return'
'.preg_replace_callback('#^( *)((?>[^(\r\n]{1,200}))\((\d+)\) #m',create_function('$m','extract(NCFix::$vars['.NCFix::uses(array('collapsed'=>$collapsed)).'], EXTR_REFS);
 				return "$m[1]$m[2]($m[3]) "
-					. (trim($m[1]) || $m[3] < 7
+					. (($m[1] || !$collapsed) && ($m[3] < 7)
 					? \' \'
 					: \' \');
-			'),self::htmlDump($dump)).'
';}}class -Logger{const + '),self::htmlDump($dump)).'
';}public +static +function +findTrace(array$trace,$method,&$index=NULL){$m=explode('::',$method);foreach($trace +as$i=>$item){if(isset($item['function'])&&$item['function']===end($m)&&isset($item['class'])===isset($m[1])&&(!isset($item['class'])||$item['class']===$m[0]||is_subclass_of($item['class'],$m[0]))){$index=$i;return$item;}}}}class +NLogger{const DEBUG='debug',INFO='info',WARNING='warning',ERROR='error',CRITICAL='critical';public static$emailSnooze=172800;public$mailer=array(__CLASS__,'defaultMailer');public$directory;public$email;public function @@ -556,15 +569,15 @@ DirectoryNotFoundException("Directory '$this->directory' is not found or is not static function defaultMailer($message,$email){$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($email,$parts['subject'],$parts['body'],$parts['headers']);}}class -Html +NHtml implements -ArrayAccess,Countable,IteratorAggregate{private$name;private$isEmpty;public$attrs=array();protected$children=array();public +ArrayAccess,Countable{private$name;private$isEmpty;public$attrs=array();protected$children=array();public static$xhtml=TRUE;public static$emptyElements=array('img'=>1,'hr'=>1,'br'=>1,'input'=>1,'meta'=>1,'area'=>1,'embed'=>1,'keygen'=>1,'source'=>1,'base'=>1,'col'=>1,'link'=>1,'param'=>1,'basefont'=>1,'frame'=>1,'isindex'=>1,'wbr'=>1,'command'=>1);public static function el($name=NULL,$attrs=NULL){$el=new -self;$parts=explode(' ',$name,2);$el->setName($parts[0]);if(is_array($attrs)){$el->attrs=$attrs;}elseif($attrs!==NULL){$el->setText($attrs);}if(isset($parts[1])){foreach(Strings::matchAll($parts[1].' ','#([a-z0-9:-]+)(?:=(["\'])?(.*?)(?(2)\\2|\s))?#i')as$m){$el->attrs[$m[1]]=isset($m[3])?$m[3]:TRUE;}}return$el;}final +self;$parts=explode(' ',$name,2);$el->setName($parts[0]);if(is_array($attrs)){$el->attrs=$attrs;}elseif($attrs!==NULL){$el->setText($attrs);}return$el;}final public function setName($name,$isEmpty=NULL){if($name!==NULL&&!is_string($name)){throw @@ -618,7 +631,7 @@ create($name,$attrs=NULL){$this->insert(NULL,$child=self::el($name,$attrs));retu function insert($index,$child,$replace=FALSE){if($child instanceof -Html||is_scalar($child)){if($index===NULL){$this->children[]=$child;}else{array_splice($this->children,(int)$index,$replace?1:0,array($child));}}else{throw +NHtml||is_scalar($child)){if($index===NULL){$this->children[]=$child;}else{array_splice($this->children,(int)$index,$replace?1:0,array($child));}}else{throw new InvalidArgumentException("Child node must be scalar or Html object, ".(is_object($child)?get_class($child):gettype($child))." given.");}return$this;}final public @@ -641,16 +654,6 @@ function removeChildren(){$this->children=array();}final public function -getIterator($deep=FALSE){if($deep){$deep=$deep>0?RecursiveIteratorIterator::SELF_FIRST:RecursiveIteratorIterator::CHILD_FIRST;return -new -RecursiveIteratorIterator(new -GenericRecursiveIterator(new -ArrayIterator($this->children)),$deep);}else{return -new -GenericRecursiveIterator(new -ArrayIterator($this->children));}}final -public -function getChildren(){return$this->children;}final public function @@ -673,9 +676,11 @@ as$k=>$v){if($v!==NULL&&$v!==FALSE){$s.=' data-'.$k.'="'.htmlspecialchars((strin as$k=>$v){if($v!=NULL){$tmp[]=$v===TRUE?$k:(is_string($k)?$k.':'.$v:$v);}}if($tmp===NULL){continue;}$value=implode($key==='style'||!strncmp($key,'on',2)?';':' ',$tmp);}else{$value=(string)$value;}$s.=' '.$key.'="'.htmlspecialchars($value).'"';}$s=str_replace('@','@',$s);return$s;}public function __clone(){foreach($this->children -as$key=>$value){if(is_object($value)){$this->children[$key]=clone$value;}}}}@header('X-Powered-By: Nette Framework');final +as$key=>$value){if(is_object($value)){$this->children[$key]=clone$value;}}}}function +dump($var){foreach(func_get_args()as$arg){NDebugger::dump($arg);}return$var;}function +ndebug(){NDebugger::$strictMode=TRUE;NDebugger::enable(NDebugger::DEVELOPMENT);}final class -Debugger{public +NDebugger{public static$productionMode;public static$consoleMode;public static$time;private @@ -707,27 +712,40 @@ public function __construct(){throw new -StaticClassException;}public +NStaticClassException;}public static function _init(){self::$time=microtime(TRUE);self::$consoleMode=PHP_SAPI==='cli';self::$productionMode=self::DETECT;if(self::$consoleMode){self::$source=empty($_SERVER['argv'])?'cli':'cli: '.implode(' ',$_SERVER['argv']);}else{self::$ajaxDetected=isset($_SERVER['HTTP_X_REQUESTED_WITH'])&&$_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';if(isset($_SERVER['REQUEST_URI'])){self::$source=(isset($_SERVER['HTTPS'])&&strcasecmp($_SERVER['HTTPS'],'off')?'https://':'http://').(isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:(isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'')).$_SERVER['REQUEST_URI'];}}self::$logger=new -Logger;self::$logDirectory=&self::$logger->directory;self::$email=&self::$logger->email;self::$mailer=&self::$logger->mailer;self::$emailSnooze=&Logger::$emailSnooze;self::$fireLogger=new -FireLogger;self::$blueScreen=new -DebugBlueScreen;self::$blueScreen->addPanel(create_function('$e',' - if ($e instanceof TemplateException) { +NLogger;self::$logDirectory=&self::$logger->directory;self::$email=&self::$logger->email;self::$mailer=&self::$logger->mailer;self::$emailSnooze=&NLogger::$emailSnooze;self::$fireLogger=new +NFireLogger;self::$blueScreen=new +NDebugBlueScreen;self::$blueScreen->addPanel(create_function('$e',' + if ($e instanceof NTemplateException) { return array( \'tab\' => \'Template\', - \'panel\' => \'

File: \' . DebugHelpers::editorLink($e->sourceFile, $e->sourceLine) + \'panel\' => \'

File: \' . NDebugHelpers::editorLink($e->sourceFile, $e->sourceLine) . \'  Line: \' . ($e->sourceLine ? $e->sourceLine : \'n/a\') . \'

\' - . ($e->sourceLine ? \'
\' . DebugBlueScreen::highlightFile($e->sourceFile, $e->sourceLine) . \'
\' : \'\') + . ($e->sourceLine ? NDebugBlueScreen::highlightFile($e->sourceFile, $e->sourceLine) : \'\') ); + } elseif ($e instanceof NNeonException && preg_match(\'#line (\\d+)#\', $e->getMessage(), $m)) { + if ($item = NDebugHelpers::findTrace($e->getTrace(), \'NConfigNeonAdapter::load\')) { + return array( + \'tab\' => \'NEON\', + \'panel\' => \'

File: \' . NDebugHelpers::editorLink($item[\'args\'][0], $m[1]) . \'  Line: \' . $m[1] . \'

\' + . NDebugBlueScreen::highlightFile($item[\'args\'][0], $m[1]) + ); + } elseif ($item = NDebugHelpers::findTrace($e->getTrace(), \'NNeon::decode\')) { + return array( + \'tab\' => \'NEON\', + \'panel\' => NDebugBlueScreen::highlightPhp($item[\'args\'][0], $m[1]) + ); + } } '));self::$bar=new -DebugBar;self::$bar->addPanel(new -DefaultBarPanel('time'));self::$bar->addPanel(new -DefaultBarPanel('memory'));self::$bar->addPanel(self::$errorPanel=new -DefaultBarPanel('errors'));self::$bar->addPanel(self::$dumpPanel=new -DefaultBarPanel('dumps'));}public +NDebugBar;self::$bar->addPanel(new +NDefaultBarPanel('time'));self::$bar->addPanel(new +NDefaultBarPanel('memory'));self::$bar->addPanel(self::$errorPanel=new +NDefaultBarPanel('errors'));self::$bar->addPanel(self::$dumpPanel=new +NDefaultBarPanel('dumps'));}public static function enable($mode=NULL,$logDirectory=NULL,$email=NULL){error_reporting(E_ALL|E_STRICT);if(is_bool($mode)){self::$productionMode=$mode;}elseif($mode!==self::DETECT||self::$productionMode===NULL){$mode=is_string($mode)?preg_split('#[,\s]+#',$mode):array($mode);$mode[]='127.0.0.1';$mode[]='::1';self::$productionMode=!in_array(isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:php_uname('n'),$mode,TRUE);}if(is_string($logDirectory)){self::$logDirectory=realpath($logDirectory);if(self::$logDirectory===FALSE){throw @@ -745,12 +763,12 @@ static function log($message,$priority=self::INFO){if(self::$logDirectory===FALSE){return;}elseif(!self::$logDirectory){throw new -InvalidStateException('Logging directory is not specified in Debugger::$logDirectory.');}if($message +InvalidStateException('Logging directory is not specified in NDebugger::$logDirectory.');}if($message instanceof Exception){$exception=$message;$message=($message instanceof FatalErrorException?'Fatal error: '.$exception->getMessage():get_class($exception).": ".$exception->getMessage())." in ".$exception->getFile().":".$exception->getLine();$hash=md5($exception.(method_exists($exception,'getPrevious')?$exception->getPrevious():(isset($exception->previous)?$exception->previous:'')));$exceptionFilename="exception-".@date('Y-m-d-H-i-s')."-$hash.html";foreach(new -DirectoryIterator(self::$logDirectory)as$entry){if(strpos($entry,$hash)){$exceptionFilename=$entry;$saved=TRUE;break;}}}self::$logger->log(array(@date('[Y-m-d H-i-s]'),$message,self::$source?' @ '.self::$source:NULL,!empty($exceptionFilename)?' @@ '.$exceptionFilename:NULL),$priority);if(!empty($exceptionFilename)){$exceptionFilename=self::$logDirectory.'/'.$exceptionFilename;if(empty($saved)&&$logHandle=@fopen($exceptionFilename,'w')){ob_start();ob_start(create_function('$buffer','extract(NCFix::$vars['.NCFix::uses(array('logHandle'=>$logHandle)).'], EXTR_REFS); fwrite($logHandle, $buffer); '),1);self::$blueScreen->render($exception);ob_end_flush();ob_end_clean();fclose($logHandle);}return +DirectoryIterator(self::$logDirectory)as$entry){if(strpos($entry,$hash)){$exceptionFilename=$entry;$saved=TRUE;break;}}}self::$logger->log(array(@date('[Y-m-d H-i-s]'),$message,self::$source?' @ '.self::$source:NULL,!empty($exceptionFilename)?' @@ '.$exceptionFilename:NULL),$priority);if(!empty($exceptionFilename)){$exceptionFilename=self::$logDirectory.'/'.$exceptionFilename;if(empty($saved)&&$logHandle=@fopen($exceptionFilename,'w')){ob_start();ob_start(create_function('$buffer','extract(NCFix::$vars['.NCFix::uses(array('logHandle'=>$logHandle)).'], EXTR_REFS); fwrite($logHandle, $buffer); '),4096);self::$blueScreen->render($exception);ob_end_flush();ob_end_clean();fclose($logHandle);}return strtr($exceptionFilename,'\\/',DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR);}}public static function @@ -758,7 +776,7 @@ _shutdownHandler(){if(!self::$enabled){return;}static$types=array(E_ERROR=>1,E_C FatalErrorException($error['message'],0,$error['type'],$error['file'],$error['line'],NULL));}if(self::$bar&&!self::$productionMode&&self::isHtmlMode()){self::$bar->render();}}public static function -_exceptionHandler(Exception$exception){if(!headers_sent()){header('HTTP/1.1 500 Internal Server Error');}try{if(self::$productionMode){try{self::log($exception,self::ERROR);}catch(Exception$e){echo'FATAL ERROR: unable to log error';}if(self::$consoleMode){echo"ERROR: the server encountered an internal error and was unable to complete your request.\n";}elseif(self::isHtmlMode()){?> +_exceptionHandler(Exception$exception){if(!headers_sent()){$protocol=isset($_SERVER['SERVER_PROTOCOL'])?$_SERVER['SERVER_PROTOCOL']:'HTTP/1.1';header($protocol.' 500',TRUE,500);}try{if(self::$productionMode){try{self::log($exception,self::ERROR);}catch(Exception$e){echo'FATAL ERROR: unable to log error';}if(self::$consoleMode){echo"ERROR: the server encountered an internal error and was unable to complete your request.\n";}elseif(self::isHtmlMode()){?> @@ -798,13 +816,13 @@ function catchError(&$error){if(!self::$enabled&&self::$lastError!==FALSE){restore_error_handler();}$error=self::$lastError;self::$lastError=FALSE;return(bool)$error;}public static function -dump($var,$return=FALSE){if(!$return&&self::$productionMode){return$var;}$output="
".DebugHelpers::htmlDump($var)."
\n";if(!$return){$trace=debug_backtrace();$i=!isset($trace[1]['class'])&&isset($trace[1]['function'])&&$trace[1]['function']==='dump'?1:0;if(isset($trace[$i]['file'],$trace[$i]['line'])&&is_file($trace[$i]['file'])){$lines=file($trace[$i]['file']);preg_match('#dump\((.*)\)#',$lines[$trace[$i]['line']-1],$m);$output=substr_replace($output,' title="'.htmlspecialchars((isset($m[0])?"$m[0] \n":'')."in file {$trace[$i]['file']} on line {$trace[$i]['line']}").'"',4,0);if(self::$showLocation){$output=substr_replace($output,' in '.DebugHelpers::editorLink($trace[$i]['file'],$trace[$i]['line']).":{$trace[$i]['line']}",-8,0);}}}if(self::$consoleMode){$output=htmlspecialchars_decode(strip_tags($output),ENT_QUOTES);}if($return){return$output;}else{echo$output;return$var;}}public +dump($var,$return=FALSE){if(!$return&&self::$productionMode){return$var;}$output="
".NDebugHelpers::htmlDump($var)."
\n";if(!$return){$trace=debug_backtrace();$i=NDebugHelpers::findTrace($trace,'dump')?1:0;if(isset($trace[$i]['file'],$trace[$i]['line'])&&is_file($trace[$i]['file'])){$lines=file($trace[$i]['file']);preg_match('#dump\((.*)\)#',$lines[$trace[$i]['line']-1],$m);$output=substr_replace($output,' title="'.htmlspecialchars((isset($m[0])?"$m[0] \n":'')."in file {$trace[$i]['file']} on line {$trace[$i]['line']}").'"',4,0);if(self::$showLocation){$output=substr_replace($output,' in '.NDebugHelpers::editorLink($trace[$i]['file'],$trace[$i]['line']).":{$trace[$i]['line']}",-8,0);}}}if(self::$consoleMode){$output=htmlspecialchars_decode(strip_tags($output),ENT_QUOTES);}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 -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::$dumpPanel->data[]=array('title'=>$title,'dump'=>$dump);}return$var;}public +barDump($var,$title=NULL){if(!self::$productionMode){$dump=array();foreach((is_array($var)?$var:array(''=>$var))as$key=>$val){$dump[$key]=NDebugHelpers::clickableDump($val);}self::$dumpPanel->data[]=array('title'=>$title,'dump'=>$dump);}return$var;}public static function fireLog($message){if(!self::$productionMode){return @@ -814,8 +832,8 @@ function isHtmlMode(){return!self::$ajaxDetected&&!self::$consoleMode&&!preg_match('#^Content-Type: (?!text/html)#im',implode("\n",headers_list()));}public static function -addPanel(IBarPanel$panel,$id=NULL){self::$bar->addPanel($panel,$id);}}function -dump($var){foreach(func_get_args()as$arg)Debugger::dump($arg);return$var;}class +addPanel(IBarPanel$panel,$id=NULL){return +self::$bar->addPanel($panel,$id);}}class FatalErrorException extends Exception{private$severity;public @@ -826,4 +844,4 @@ getSeverity(){return$this->severity;}}class NCFix{static$vars=array();static function uses($args){self::$vars[]=$args;return -count(self::$vars)-1;}}Debugger::_init(); +count(self::$vars)-1;}}NDebugger::_init(); diff --git a/examples/fetching-examples.php b/examples/fetching-examples.php index e09bffd9..df566868 100644 --- a/examples/fetching-examples.php +++ b/examples/fetching-examples.php @@ -7,6 +7,7 @@ require_once 'Nette/Debugger.php'; require_once '../dibi/dibi.php'; +ndebug(); dibi::connect(array( 'driver' => 'sqlite', @@ -29,38 +30,38 @@ product_id | title // fetch a single row echo "

fetch()

\n"; $row = dibi::fetch('SELECT title FROM products'); -Debugger::dump($row); // Chair +dump($row); // Chair // fetch a single value echo "

fetchSingle()

\n"; $value = dibi::fetchSingle('SELECT title FROM products'); -Debugger::dump($value); // Chair +dump($value); // Chair // fetch complete result set echo "

fetchAll()

\n"; $all = dibi::fetchAll('SELECT * FROM products'); -Debugger::dump($all); +dump($all); // fetch complete result set like association array echo "

fetchAssoc('title')

\n"; $res = dibi::query('SELECT * FROM products'); $assoc = $res->fetchAssoc('title'); // key -Debugger::dump($assoc); +dump($assoc); // fetch complete result set like pairs key => value echo "

fetchPairs('product_id', 'title')

\n"; $pairs = $res->fetchPairs('product_id', 'title'); -Debugger::dump($pairs); +dump($pairs); // fetch row by row echo "

using foreach

\n"; foreach ($res as $n => $row) { - Debugger::dump($row); + dump($row); } @@ -74,12 +75,12 @@ $res = dibi::query(' echo "

fetchAssoc('customers.name|products.title')

\n"; $assoc = $res->fetchAssoc('customers.name|products.title'); // key -Debugger::dump($assoc); +dump($assoc); echo "

fetchAssoc('customers.name[]products.title')

\n"; $assoc = $res->fetchAssoc('customers.name[]products.title'); // key -Debugger::dump($assoc); +dump($assoc); echo "

fetchAssoc('customers.name->products.title')

\n"; $assoc = $res->fetchAssoc('customers.name->products.title'); // key -Debugger::dump($assoc); +dump($assoc); diff --git a/examples/nette-debug-and-exceptions.php b/examples/nette-debug-and-exceptions.php index 1252ef37..856c31e9 100644 --- a/examples/nette-debug-and-exceptions.php +++ b/examples/nette-debug-and-exceptions.php @@ -15,7 +15,7 @@ require_once '../dibi/dibi.php'; // enable Nette Debugger -Debugger::enable(); +ndebug(); dibi::connect(array( diff --git a/examples/nette-debug-and-variables.php b/examples/nette-debug-and-variables.php index fed24944..2917090a 100644 --- a/examples/nette-debug-and-variables.php +++ b/examples/nette-debug-and-variables.php @@ -15,7 +15,7 @@ require_once '../dibi/dibi.php'; // enable Nette Debugger -Debugger::enable(); +NDebugger::enable(); dibi::connect(array( @@ -27,4 +27,4 @@ dibi::connect(array( )); -Debugger::barDump( dibi::fetchAll('SELECT * FROM customers WHERE customer_id < ?', 38), '[customers]' ); +NDebugger::barDump( dibi::fetchAll('SELECT * FROM customers WHERE customer_id < ?', 38), '[customers]' ); diff --git a/examples/result-set-data-types.php b/examples/result-set-data-types.php index 5e38bbc9..116922a3 100644 --- a/examples/result-set-data-types.php +++ b/examples/result-set-data-types.php @@ -7,6 +7,7 @@ require_once 'Nette/Debugger.php'; require_once '../dibi/dibi.php'; +ndebug(); date_default_timezone_set('Europe/Prague'); @@ -24,7 +25,7 @@ $res->setType('customer_id', Dibi::INTEGER) ->setFormat(dibi::DATETIME, 'Y-m-d H:i:s'); -Debugger::dump( $res->fetch() ); +dump( $res->fetch() ); // outputs: // object(DibiRow)#3 (3) { // customer_id => int(1) @@ -37,7 +38,7 @@ Debugger::dump( $res->fetch() ); // using auto-detection (works well with MySQL or other strictly typed databases) $res = dibi::query('SELECT * FROM [customers]'); -Debugger::dump( $res->fetch() ); +dump( $res->fetch() ); // outputs: // object(DibiRow)#3 (3) { // customer_id => int(1) diff --git a/examples/using-extension-methods.php b/examples/using-extension-methods.php index 4b330812..b91a040a 100644 --- a/examples/using-extension-methods.php +++ b/examples/using-extension-methods.php @@ -7,6 +7,7 @@ require_once 'Nette/Debugger.php'; require_once '../dibi/dibi.php'; +ndebug(); dibi::connect(array( 'driver' => 'sqlite', @@ -27,4 +28,4 @@ function DibiResult_prototype_fetchShuffle(DibiResult $obj) // fetch complete result set shuffled $res = dibi::query('SELECT * FROM [customers]'); $all = $res->fetchShuffle(); -Debugger::dump($all); +dump($all);