Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Tue, May 20, 9:56 PM

in-portal

Index: trunk/kernel/include/modlist.php
===================================================================
--- trunk/kernel/include/modlist.php (revision 3814)
+++ trunk/kernel/include/modlist.php (revision 3815)
@@ -1,136 +1,142 @@
<?php
class clsModule extends clsItemDB
{
function clsModule($name="")
{
$this->clsItemDB();
$this->tablename = GetTablePrefix()."Modules";
$this->type=11;
$this->BasePermission="";
$this->id_field = "Name";
$this->debuglevel=0;
if(strlen($name))
$this->LoadFromDatabase($name);
}
function ExecuteFunction($function_name, $params)
{
$function_name = $this->Get('Var').'_'.$function_name;
if( function_exists($function_name) ) {
return $function_name($params);
}
else {
return false;
}
}
}
class clsModList extends clsItemCollection
{
function clsModList()
{
$this->clsItemCollection();
$this->SourceTable=GetTablePrefix()."Modules";
$this->classname = "clsModule";
$this->LoadModules();
}
function LoadModules()
{
$this->Clear();
return $this->Query_Item("SELECT * FROM ".$this->SourceTable);
}
function &FindModule($fieldname, $value)
{
// finds module by field specified
- foreach($this->Items as $module)
- if(strcasecmp($module->Get($fieldname), $value) == 0)
+ $keys = array_keys($this->Items);
+ foreach ($keys as $key) {
+ $module =& $this->Items[$key];
+ if (strcasecmp($module->Get($fieldname), $value) == 0) {
return $module;
- return false;
+ }
+ }
+
+ $false = false;
+ return $false;
}
function GetModuleList()
{
// returns installed modules list
$ret = Array();
foreach($this->Items as $module) $ret[] = $module->Get('Name');
return $ret;
}
function &GetModule($name)
{
//$this->LoadModules();
return $this->FindModule('Name', $name);
}
function ExecuteFunction($function, $params = Array() )
{
// call specified function for each module
// and returns result as array (key = module name)
$result = Array();
foreach($this->Items as $module) {
$result[ $module->Get('Name') ] = $module->ExecuteFunction($function, $params);
}
return $result;
}
function GetModuleByPath($path)
{
$ret = false;
if(strlen($path))
{
$parts = explode("/",$path);
$modpath = $parts[0]."/";
//$this->LoadModules();
return $this->FindModule('TemplatePath',$modpath);
}
return $ret;
}
function GetModuleRoot($name)
{
//$this->LoadModules();
$mod = $this->FindModule('Name', $name);
return is_object($mod) ? $mod->Get("RootCat") : 0;
}
function SetModuleRoot($name, $CatId)
{
$mod =& $this->FindModule('Name', $name);
if( is_object($mod) )
{
$mod->Set('RootCat',$CatId);
$mod->Update();
}
}
function Refresh()
{
// reloads table content
$this->LoadModules();
}
function ModuleInstalled($name)
{
//$this->LoadModules();
return $this->FindModule('Name',$name);
}
function MergeReturn($array)
{
// merge results ganed with ExecuteFunction
// method in a specific way
$tmp = Array();
foreach($array as $mod_name => $mod_results)
if (is_array($mod_results)) {
foreach($mod_results as $mod_var => $mod_var_value) {
$tmp[$mod_var][$mod_name] = $mod_var_value;
}
}
return $tmp;
}
}
Property changes on: trunk/kernel/include/modlist.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.4
\ No newline at end of property
+1.5
\ No newline at end of property
Index: trunk/kernel/include/adodb/drivers/adodb-mysql.inc.php
===================================================================
--- trunk/kernel/include/adodb/drivers/adodb-mysql.inc.php (revision 3814)
+++ trunk/kernel/include/adodb/drivers/adodb-mysql.inc.php (revision 3815)
@@ -1,564 +1,569 @@
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 8.
MySQL code that does not support transactions. Use mysqlt if you need transactions.
Requires mysql client. Works on Windows and Unix.
28 Feb 2001: MetaColumns bug fix - suggested by Freek Dijkstra (phpeverywhere@macfreek.com)
*/
if (! defined("_ADODB_MYSQL_LAYER")) {
define("_ADODB_MYSQL_LAYER", 1 );
class ADODB_mysql extends ADOConnection {
var $databaseType = 'mysql';
var $dataProvider = 'mysql';
var $hasInsertID = true;
var $hasAffectedRows = true;
var $metaTablesSQL = "SHOW TABLES";
var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasLimit = true;
var $hasMoveFirst = true;
var $hasGenID = true;
var $upperCase = 'upper';
var $isoDates = true; // accepts dates in ISO format
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
var $hasTransactions = false;
var $forceNewConnect = false;
var $poorAffectedRows = true;
var $clientFlags = 0;
var $dbxDriver = 1;
function ADODB_mysql()
{
}
function ServerInfo()
{
$arr['description'] = $this->GetOne("select version()");
$arr['version'] = ADOConnection::_findvers($arr['description']);
return $arr;
}
// if magic quotes disabled, use mysql_real_escape_string()
function qstr($s,$magic_quotes=false)
{
if (!$magic_quotes) {
if (ADODB_PHPVER >= 0x4300) {
if (is_resource($this->_connectionID))
return "'".mysql_real_escape_string($s,$this->_connectionID)."'";
}
if ($this->replaceQuote[0] == '\\'){
$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
}
return "'".str_replace("'",$this->replaceQuote,$s)."'";
}
// undo magic quotes for "
$s = str_replace('\\"','"',$s);
return "'$s'";
}
function _insertid()
{
return mysql_insert_id($this->_connectionID);
}
function _affectedrows()
{
return mysql_affected_rows($this->_connectionID);
}
// See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
// Reference on Last_Insert_ID on the recommended way to simulate sequences
var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
var $_genSeqSQL = "create table %s (id int not null)";
var $_genSeq2SQL = "insert into %s values (%s)";
var $_dropSeqSQL = "drop table %s";
function CreateSequence($seqname='adodbseq',$startID=1)
{
if (empty($this->_genSeqSQL)) return false;
$u = strtoupper($seqname);
$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
if (!$ok) return false;
return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
}
function GenID($seqname='adodbseq',$startID=1)
{
// post-nuke sets hasGenID to false
if (!$this->hasGenID) return false;
$getnext = sprintf($this->_genIDSQL,$seqname);
$rs = @$this->Execute($getnext);
if (!$rs) {
$u = strtoupper($seqname);
$this->Execute(sprintf($this->_genSeqSQL,$seqname));
$this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
$rs = $this->Execute($getnext);
}
$this->genID = mysql_insert_id($this->_connectionID);
if ($rs) $rs->Close();
return $this->genID;
}
function &MetaDatabases()
{
$qid = mysql_list_dbs($this->_connectionID);
$arr = array();
$i = 0;
$max = mysql_num_rows($qid);
while ($i < $max) {
$db = mysql_tablename($qid,$i);
if ($db != 'mysql') $arr[] = $db;
$i += 1;
}
return $arr;
}
// Format date column in sql string given an input format that understands Y M D
function SQLDate($fmt, $col=false)
{
if (!$col) $col = $this->sysTimeStamp;
$s = 'DATE_FORMAT('.$col.",'";
$concat = false;
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= '%Y';
break;
case 'Q':
case 'q':
$s .= "'),Quarter($col)";
if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
else $s .= ",('";
$concat = true;
break;
case 'M':
$s .= '%b';
break;
case 'm':
$s .= '%m';
break;
case 'D':
case 'd':
$s .= '%d';
break;
case 'H':
$s .= '%H';
break;
case 'h':
$s .= '%I';
break;
case 'i':
$s .= '%i';
break;
case 's':
$s .= '%s';
break;
case 'a':
case 'A':
$s .= '%p';
break;
default:
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
$s .= $ch;
break;
}
}
$s.="')";
if ($concat) $s = "CONCAT($s)";
return $s;
}
// returns concatenated string
// much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
function Concat()
{
$s = "";
$arr = func_get_args();
$first = true;
/*
foreach($arr as $a) {
if ($first) {
$s = $a;
$first = false;
} else $s .= ','.$a;
}*/
// suggestion by andrew005@mnogo.ru
$s = implode(',',$arr);
if (strlen($s) > 0) return "CONCAT($s)";
else return '';
}
function OffsetDate($dayFraction,$date=false)
{
if (!$date) $date = $this->sysDate;
return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";
}
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (ADODB_PHPVER >= 0x4300)
$this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword,
$this->forceNewConnect,$this->clientFlags);
else if (ADODB_PHPVER >= 0x4200)
$this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword,
$this->forceNewConnect);
else
$this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (ADODB_PHPVER >= 0x4300)
$this->_connectionID = @mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);
else
$this->_connectionID = @mysql_pconnect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($this->autoRollback) $this->RollbackTrans();
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->forceNewConnect = true;
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
}
function &MetaColumns($table)
{
if ($this->metaColumnsSQL) {
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return false;
$retarr = array();
while (!$rs->EOF){
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$type = $rs->fields[1];
// split type into type(length):
if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
$fld->type = $query_array[1];
$fld->max_length = $query_array[2];
} else {
$fld->max_length = -1;
$fld->type = $type;
}
$fld->not_null = ($rs->fields[2] != 'YES');
$fld->primary_key = ($rs->fields[3] == 'PRI');
$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
$fld->binary = (strpos($fld->type,'blob') !== false);
if (!$fld->binary) {
$d = $rs->fields[4];
if ($d != "" && $d != "NULL") {
$fld->has_default = true;
$fld->default_value = $d;
} else {
$fld->has_default = false;
}
}
$retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
return false;
}
// returns true or false
function SelectDB($dbName)
{
$this->databaseName = $dbName;
if ($this->_connectionID) {
return @mysql_select_db($dbName,$this->_connectionID);
}
else return false;
}
// parameters use PostgreSQL convention, not MySQL
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false,$secs=0)
{
$offsetStr =($offset>=0) ? "$offset," : '';
- return ($secs) ? $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr,$arg3)
- : $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr,$arg3);
+ if ($secs) {
+ $limit =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr,$arg3);
+ }
+ else {
+ $limit =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr,$arg3);
+ }
+ return $limit;
}
// returns queryID or false
function _query($sql,$inputarr)
{
//global $ADODB_COUNTRECS;
//if($ADODB_COUNTRECS)
return mysql_query($sql,$this->_connectionID);
//else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6
}
/* Returns: the last error message from previous database operation */
function ErrorMsg()
{
if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error();
else $this->_errorMsg = @mysql_error($this->_connectionID);
return $this->_errorMsg;
}
/* Returns: the last error number from previous database operation */
function ErrorNo()
{
if (empty($this->_connectionID)) return @mysql_errno();
else return @mysql_errno($this->_connectionID);
}
// returns true or false
function _close()
{
@mysql_close($this->_connectionID);
$this->_connectionID = false;
}
/*
* Maximum size of C field
*/
function CharMax()
{
return 255;
}
/*
* Maximum size of X field
*/
function TextMax()
{
return 4294967295;
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordSet_mysql extends ADORecordSet{
var $databaseType = "mysql";
var $canSeek = true;
function ADORecordSet_mysql($queryID,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
switch ($mode)
{
case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;
}
$this->ADORecordSet($queryID);
}
function _initrs()
{
//GLOBAL $ADODB_COUNTRECS;
// $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;
$this->_numOfRows = @mysql_num_rows($this->_queryID);
$this->_numOfFields = @mysql_num_fields($this->_queryID);
}
function &FetchField($fieldOffset = -1)
{
if ($fieldOffset != -1) {
$o = @mysql_fetch_field($this->_queryID, $fieldOffset);
$f = @mysql_field_flags($this->_queryID,$fieldOffset);
$o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com)
//$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
$o->binary = (strpos($f,'binary')!== false);
}
else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */
$o = @mysql_fetch_field($this->_queryID);
$o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com)
//$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
}
return $o;
}
function &GetRowAssoc($upper=true)
{
if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $this->fields;
return ADORecordSet::GetRowAssoc($upper);
}
/* Use associative array to get fields array */
function Fields($colname)
{
// added @ by "Michael William Miller" <mille562@pilot.msu.edu>
if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname];
if (!$this->bind) {
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
$this->bind[strtoupper($o->name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
}
function _seek($row)
{
if ($this->_numOfRows == 0) return false;
return @mysql_data_seek($this->_queryID,$row);
}
// 10% speedup to move MoveNext to child class
function MoveNext()
{
//global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return adodb_movenext($this);
if ($this->EOF) return false;
$this->_currentRow++;
$this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
if (is_array($this->fields)) return true;
$this->EOF = true;
/* -- tested raising an error -- appears pointless
$conn = $this->connection;
if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
$fn = $conn->raiseErrorFn;
$fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
}
*/
return false;
}
function _fetch()
{
$this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
return is_array($this->fields);
}
function _close() {
@mysql_free_result($this->_queryID);
$this->_queryID = false;
}
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; // mysql max_length is not accurate
switch (strtoupper($t)) {
case 'STRING':
case 'CHAR':
case 'VARCHAR':
case 'TINYBLOB':
case 'TINYTEXT':
case 'ENUM':
case 'SET':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
case 'LONGTEXT':
case 'MEDIUMTEXT':
return 'X';
// php_mysql extension always returns 'blob' even if 'text'
// so we have to check whether binary...
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':
case 'DATE': return 'D';
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP': return 'T';
case 'INT':
case 'INTEGER':
case 'BIGINT':
case 'TINYINT':
case 'MEDIUMINT':
case 'SMALLINT':
if (!empty($fieldobj->primary_key)) return 'R';
else return 'I';
default: return 'N';
}
}
}
}
?>
\ No newline at end of file
Property changes on: trunk/kernel/include/adodb/drivers/adodb-mysql.inc.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.5
\ No newline at end of property
+1.6
\ No newline at end of property
Index: trunk/kernel/include/debugger.php
===================================================================
--- trunk/kernel/include/debugger.php (revision 3814)
+++ trunk/kernel/include/debugger.php (revision 3815)
@@ -1,1037 +1,1085 @@
<?php
if( !class_exists('Debugger') )
{
function dbg_ConstOn($const_name)
{
return defined($const_name) && constant($const_name);
}
function dbg_safeDefine($const_name,$const_value)
{
if(!defined($const_name)) define($const_name,$const_value);
}
unset($_REQUEST['debug_host'], $_REQUEST['debug_fastfile']); // this var messed up whole detection stuff :(
// Detect fact, that this session beeing debugged by Zend Studio
foreach($_REQUEST as $rq_name=>$rq_value)
{
if( substr($rq_name,0,6)=='debug_' )
{
dbg_safeDefine('DBG_ZEND_PRESENT', 1);
break;
}
}
dbg_safeDefine('DBG_ZEND_PRESENT',0);
// set default values for debugger constants
$dbg_constMap=Array('DBG_OPTIONS'=>0,
'DBG_USE_HIGHLIGHT'=>1,
'DBG_USE_SHUTDOWN_FUNC'=>DBG_ZEND_PRESENT?0:1,
'DBG_HANDLE_ERRORS'=>DBG_ZEND_PRESENT?0:1,
'DBG_IGNORE_STRICT_ERRORS'=>1,
'DBG_DOMVIEWER'=>'/temp/domviewer.html',
'DOC_ROOT'=> str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT']) ), // windows hack
'DBG_LOCAL_BASE_PATH'=>'w:');
foreach($dbg_constMap as $dbg_constName=>$dbg_constValue)
{
dbg_safeDefine($dbg_constName,$dbg_constValue);
}
// only for IE, in case if no windows php script editor defined
/*if(!defined('WINDOWS_EDITOR'))
{
$dbg_editor = 0;
$dbg_editors[0] = Array('editor' => 'c:\Program Files\UltraEdit\uedit32.exe', 'params' => '%F/%L');
$dbg_editors[1] = Array('editor' => 'c:\Program Files\Zend\ZendStudio-4.0Beta\bin\ZDE.exe', 'params' => '%F');
define('WINDOWS_EDITOR',$dbg_editors[$dbg_editor]['editor'].' '.$dbg_editors[$dbg_editor]['params']);
unset($dbg_editors,$dbg_editor);
}*/
class Debugger
{
/**
* Debugger data for building report
*
* @var Array
*/
var $Data = Array();
var $ProfilerData = Array();
var $ProfilerTotals = Array();
var $ProfilerTotalCount = Array();
var $RecursionStack = Array(); // prevent recursion when processing debug_backtrace() function results
var $TraceNextError=false;
var $Options = 0;
var $OptionsMap = Array('shutdown_func' => 1, 'error_handler' => 2,
'output_buffer' => 4, 'highlight_output' => 8);
+ var $scrollbarWidth = 0;
var $longErrors=Array();
/**
* Amount of memory used by debugger itself
*
* @var Array
* @access private
*/
var $memoryUsage=Array();
var $IncludesData=Array();
var $IncludeLevel=0;
var $reportDone = false;
+ var $dummyImage = 'http://www.adamauto.lv/chevrolet/images/spacer.gif';
+
function Debugger()
{
$this->profileStart('kernel4_startup', 'Startup and Initialization of kernel4');
$this->profileStart('script_runtime', 'Script runtime');
ini_set('display_errors',dbg_ConstOn('DBG_ZEND_PRESENT')?0:1);
$this->memoryUsage['error_handling']=0; // memory amount used by error handler
+
+ $this->scrollbarWidth = $this->isGecko() ? 22 : 25;
+ dbg_safeDefine('DBG_WINDOW_WIDTH', 700);
$this->appendRequest();
}
function initOptions()
{
}
function mapLongError($msg)
{
$key=$this->generateID();
$this->longErrors[$key]=$msg;
return $key;
}
function setOption($name,$value)
{
if( !isset($this->OptionsMap[$name]) ) die('undefined debugger option: ['.$name.']<br>');
if($value)
{
$this->Options|=$this->OptionsMap[$name];
}
else
{
$this->Options=$this->Options&~$this->OptionsMap[$name];
}
}
function getOption($name)
{
if( !isset($this->OptionsMap[$name]) ) die('undefined debugger option: ['.$name.']<br>');
return ($this->Options & $this->OptionsMap[$name]) == $this->OptionsMap[$name];
}
/**
* Set's flag, that next error that occurs will
* be prepended by backtrace results
*
*/
function traceNext()
{
$this->TraceNextError=true;
}
function dumpVars()
{
$dumpVars = func_get_args();
foreach($dumpVars as $varValue)
{
$this->Data[] = Array('value' => $varValue, 'debug_type' => 'var_dump');
}
}
function prepareHTML($dataIndex)
{
$Data =& $this->Data[$dataIndex];
if($Data['debug_type'] == 'html') return $Data['html'];
switch($Data['debug_type'])
{
case 'error':
$fileLink = $this->getFileLink($Data['file'],$Data['line']);
$ret = '<b class="debug_error">'.$this->getErrorNameByCode($Data['no']).'</b>: '.$Data['str'];
$ret .= ' in <b>'.$fileLink.'</b> on line <b>'.$Data['line'].'</b>';
return $ret;
break;
case 'var_dump':
return $this->highlightString( print_r($Data['value'], true) );
break;
case 'trace':
ini_set('memory_limit','500M');
$trace =& $Data['trace'];
//return 'sorry';
//return $this->highlightString(print_r($trace,true));
$i = 0; $traceCount = count($trace);
$ret = '';
while($i < $traceCount)
{
$traceRec =& $trace[$i];
$argsID = 'trace_args_'.$dataIndex.'_'.$i;
$has_args = isset($traceRec['args']);
if(isset($traceRec['file']))
{
$func_name=isset($traceRec['class'])?$traceRec['class'].$traceRec['type'].$traceRec['function']:$traceRec['function'];
$args_link = $has_args ? '<a href="javascript:toggleTraceArgs(\''.$argsID.'\');" title="Show/Hide Function Arguments"><b>Function</b></a>' : '<b>Function</b>';
$ret .= $args_link.': '.$this->getFileLink($traceRec['file'],$traceRec['line'],$func_name);
$ret .= ' in <b>'.basename($traceRec['file']).'</b> on line <b>'.$traceRec['line'].'</b><br>';
}
else
{
$ret .= 'no file information available';
}
// ensure parameter value is not longer then 200 symbols
if($has_args)
{
$this->processTraceArguments($traceRec['args']);
$args = $this->highlightString(print_r($traceRec['args'], true));
$ret .= '<div id="'.$argsID.'" style="display: none;">'.$args.'</div>';
}
$i++;
}
return $ret;
break;
case 'profiler':
$profileKey = $Data['profile_key'];
$Data =& $this->ProfilerData[$profileKey];
$runtime = ($Data['ends'] - $Data['begins']); // in seconds
+
+
+ $totals_key = getArrayValue($Data, 'totalsKey');
+ if ($totals_key) {
+ $total_before = $Data['totalsBefore'];
+ $total = $this->ProfilerTotals[$totals_key];
+
+ $div_width = Array();
+ $div_width['before'] = ($total_before / $total) * $this->getWindowWidth();
+ $div_width['current'] = ($runtime / $total) * $this->getWindowWidth();
+ $div_width['left'] = (($total - $total_before - $runtime) / $total) * $this->getWindowWidth();
+
+ $ret = '<b>Name</b>: '.$Data['description'].'<br>';
+ $ret .= '<b>Runtime</b>: '.$runtime.'s';
+ $ret .= '<div class="dbg_profiler" style="width: '.$div_width['before'].'px; border-right: 0px; background-color: #298DDF;"><img src="'.$this->dummyImage.'" width="1" height="1"/></div>';
+ $ret .= '<div class="dbg_profiler" style="width: '.$div_width['current'].'px; border-left: 0px; border-right: 0px; background-color: #EF4A4A;"><img src="'.$this->dummyImage.'" width="1" height="1"/></div>';
+ $ret .= '<div class="dbg_profiler" style="width: '.$div_width['left'].'px; border-left: 0px; background-color: #DFDFDF;"><img src="'.$this->dummyImage.'" width="1" height="1"/></div>';
+
+ return $ret;
+ }
+ else {
return '<b>Name</b>: '.$Data['description'].'<br><b>Runtime</b>: '.$runtime.'s';
+ }
break;
default:
return 'incorrect debug data';
break;
}
}
+ function getWindowWidth()
+ {
+ return DBG_WINDOW_WIDTH - $this->scrollbarWidth;
+ }
+
function isApplication(&$object)
{
$app_class = defined('APPLICATION_CLASS') ? strtolower(APPLICATION_CLASS) : 'kApplication';
return get_class($object) == $app_class;
}
function processTraceArguments(&$traceArgs)
{
if(!$traceArgs) return '';
$array_keys = array_keys($traceArgs);
foreach($array_keys as $argID)
{
$argValue =& $traceArgs[$argID];
if( is_array($argValue) || is_object($argValue) )
{
if(is_object($argValue) && !in_array(get_class($argValue),$this->RecursionStack) )
{
array_push($this->RecursionStack, get_class($argValue));
if( get_class($argValue) == 'kfactory' || $this->isApplication($argValue) || get_class($argValue) == 'templateparser' )
{
$argValue = null;
continue;
}
// object & not in stack - ok
settype($argValue,'array');
$this->processTraceArguments($argValue);
array_pop($this->RecursionStack);
}
elseif(is_object($argValue) && in_array(get_class($argValue),$this->RecursionStack) )
{
// object & in stack - recursion
$traceArgs[$argID] = '**** RECURSION ***';
}
else
{
// normal array here
$this->processTraceArguments($argValue);
}
}
else
{
$traceArgs[$argID] = $this->cutStringForHTML($traceArgs[$argID]);
}
}
}
function cutStringForHTML($string)
{
if( strlen($string) > 200 ) $string = substr($string,0,50).' ...';
return $string;
}
/**
* Format SQL Query using predefined formatting
* and highlighting techniques
*
* @param string $sql
* @return string
*/
function formatSQL($sql)
{
$sql = preg_replace('/(\n|\t| )+/is',' ',$sql);
$sql = preg_replace('/(CREATE TABLE|DROP TABLE|SELECT|UPDATE|SET|REPLACE|INSERT|DELETE|VALUES|FROM|LEFT JOIN|INNER JOIN|LIMIT|WHERE|HAVING|GROUP BY|ORDER BY) /is', "\n\t$1 ",$sql);
return $this->highlightString($sql);
}
function highlightString($string)
{
if( dbg_ConstOn('DBG_USE_HIGHLIGHT') )
{
$string = str_replace( Array('\\', '/') , Array('_no_match_string_', '_n_m_s_'), $string);
$string = highlight_string('<?php '.$string.'?>', true);
$string = str_replace( Array('_no_match_string_', '_n_m_s_'), Array('\\', '/'), $string);
- return preg_replace('/&lt;\?(.*)php (.*)\?&gt;/s','$2',$string);
+ return preg_replace('/&lt;\?php(.*)\?&gt;/s', '\\1', $string);
}
else
{
return $string;
}
}
+ function isGecko()
+ {
+ return strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'firefox') !== false;
+ }
+
function getFileLink($file, $lineno = 1, $title = '')
{
if(!$title) $title = $file;
- $is_mozilla=strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'firefox')!==false?true:false;
- if($is_mozilla)
- {
+
+ if ($this->isGecko()) {
return '<a href="file://'.$this->getLocalFile($file).'">'.$title.'</a>';
}
- else
- {
+ else {
return '<a href="javascript:editFile(\''.$this->getLocalFile($file).'\','.$lineno.');" title="'.$file.'">'.$title.'</a>';
}
}
function getLocalFile($remoteFile)
{
return str_replace(DOC_ROOT, DBG_LOCAL_BASE_PATH, $remoteFile);
}
function appendTrace()
{
$trace = debug_backtrace();
array_shift($trace);
$this->Data[] = Array('trace' => $trace, 'debug_type' => 'trace');
}
function appendMemoryUsage($msg, $used=null)
{
if (!isset($used)) $used = round(memory_get_usage()/1024);
$this->appendHTML('<b>Memory usage</b> '.$msg.' '.$used.'Kb');
}
function appendHTML($html)
{
$this->Data[] = Array('html' => $html,'debug_type' => 'html');
}
/**
* Change debugger info that was already generated before.
* Returns true if html was set.
*
* @param int $index
* @param string $html
* @param string $type = {'append','prepend','replace'}
* @return bool
*/
function setHTMLByIndex($index,$html,$type='append')
{
if( !isset($this->Data[$index]) || $this->Data[$index]['debug_type'] != 'html' )
{
return false;
}
switch ($type)
{
case 'append':
$this->Data[$index]['html'] .= '<br>'.$html;
break;
case 'prepend':
$this->Data[$index]['html'] = $this->Data[$index]['html'].'<br>'.$html;
break;
case 'replace':
$this->Data[$index]['html'] = $html;
break;
}
return true;
}
/**
* Move $debugLineCount lines of input from debug output
* end to beginning.
*
* @param int $debugLineCount
*/
function moveToBegin($debugLineCount)
{
$lines = array_splice($this->Data,count($this->Data)-$debugLineCount,$debugLineCount);
$this->Data = array_merge($lines,$this->Data);
}
function moveAfterRow($new_row, $debugLineCount)
{
$lines = array_splice($this->Data,count($this->Data)-$debugLineCount,$debugLineCount);
$rows_before = array_splice($this->Data,0,$new_row,$lines);
$this->Data = array_merge($rows_before,$this->Data);
}
function appendRequest()
{
if (isset($_SERVER['SCRIPT_FILENAME'])) {
$script = $_SERVER['SCRIPT_FILENAME'];
}
else {
$script = $_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF'];
}
$this->appendHTML('ScriptName: <b>'.$this->getFileLink($script,1,basename($script)).'</b> (<b>'.dirname($script).'</b>)');
$this->appendHTML('<a href="http://www.brainjar.com/dhtml/domviewer/" target="_blank">DomViewer</a>: <input id="dbg_domviewer" type="text" value="window" style="border: 1px solid #000000;"/>&nbsp;<button class="button" onclick="return dbg_OpenDOMViewer();">Show</button>');
ob_start();
?>
- <table border="0" cellspacing="0" cellpadding="0" class="dbg_flat_table" style="width: 100%;">
+ <table border="0" cellspacing="0" cellpadding="0" class="dbg_flat_table" style="width: <?php echo $this->getWindowWidth(); ?>px;">
<thead style="font-weight: bold;">
<td width="20">Src</td><td>Name</td><td>Value</td>
</thead>
<?php
foreach($_REQUEST as $key => $value)
{
if( !is_array($value) && trim($value) == '' )
{
$value = '<b class="debug_error">no value</b>';
}
else
{
$value = htmlspecialchars(print_r($value, true));
}
$in_cookie = isset($_COOKIE[$key]);
$src = isset($_GET[$key]) && !$in_cookie ? 'GE' : (isset($_POST[$key]) && !$in_cookie ? 'PO' : ($in_cookie ? 'CO' : '?') );
echo '<tr><td>'.$src.'</td><td>'.$key.'</td><td>'.$value.'</td></tr>';
}
?>
</table>
<?php
$this->appendHTML( ob_get_contents() );
ob_end_clean();
}
function appendSession()
{
if( isset($_SESSION)&&$_SESSION )
{
$this->appendHTML('PHP Session: [<b>'.ini_get('session.name').'</b>]');
$this->dumpVars($_SESSION);
$this->moveToBegin(2);
}
}
function profileStart($key, $description = null)
{
$timeStamp = $this->getMoment();
$this->ProfilerData[$key] = Array('begins' => $timeStamp, 'ends' => 5000, 'debuggerRowID' => count($this->Data));
if (isset($description)) {
$this->ProfilerData[$key]['description'] = $description;
}
$this->Data[] = array('profile_key' => $key, 'debug_type' => 'profiler');
}
function profileFinish($key, $description = null)
{
$this->ProfilerData[$key]['ends'] = $this->getMoment();
if (isset($description)) {
$this->ProfilerData[$key]['description'] = $description;
}
}
function profilerAddTotal($total_key, $key=null, $value=null)
{
if (!isset($this->ProfilerTotals[$total_key])) {
$this->ProfilerTotals[$total_key] = 0;
$this->ProfilerTotalCount[$total_key] = 0;
}
if (!isset($value)) {
$value = $this->ProfilerData[$key]['ends'] - $this->ProfilerData[$key]['begins'];
}
+
+ if (isset($key)) {
+ $this->ProfilerData[$key]['totalsKey'] = $total_key;
+ $this->ProfilerData[$key]['totalsBefore'] = $this->ProfilerTotals[$total_key];
+ }
+
$this->ProfilerTotals[$total_key] += $value;
$this->ProfilerTotalCount[$total_key]++;
}
function getMoment()
{
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
function generateID()
{
list($usec, $sec) = explode(" ",microtime());
$id_part_1 = substr($usec, 4, 4);
$id_part_2 = mt_rand(1,9);
$id_part_3 = substr($sec, 6, 4);
$digit_one = substr($id_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$id_part_1 = ereg_replace("^0","",$id_part_1);
$id_part_1=$digit_one.$id_part_1;
}
return $id_part_1.$id_part_2.$id_part_3;
}
function getErrorNameByCode($errorCode)
{
switch($errorCode)
{
case E_USER_ERROR:
return 'Fatal Error';
break;
case E_WARNING:
case E_USER_WARNING:
return 'Warning';
break;
case E_NOTICE:
case E_USER_NOTICE:
return 'Notice';
break;
case E_STRICT:
return 'PHP5 Strict';
break;
default:
return '';
break;
}
}
/**
* Generates report
*
*/
function printReport($returnResult = false, $clean_output_buffer = true)
{
if($this->reportDone) return '';
if( dbg_ConstOn('DBG_SKIP_REPORTING') ) return;
$this->profileFinish('script_runtime');
if( dbg_ConstOn('DBG_ZEND_PRESENT') ) return;
dbg_safeDefine('DBG_RAISE_ON_WARNINGS',0);
- dbg_safeDefine('DBG_WINDOW_WIDTH', 700);
$this->memoryUsage['debugger_start']=memory_get_usage();
// show php session if any
$this->appendSession();
// ensure, that 1st line of debug output always is this one:
$this->appendHTML('<a href="javascript:toggleDebugLayer(27);">Hide Debugger</a>');
$this->moveToBegin(1);
if( dbg_ConstOn('DBG_SQL_PROFILE') && isset($this->ProfilerTotals['sql']) )
{
$this->appendHTML('<b>SQL Total time:</b> '.$this->ProfilerTotals['sql'].' Number of queries: '.$this->ProfilerTotalCount['sql']);
}
if( dbg_ConstOn('DBG_PROFILE_MEMORY') )
{
$this->appendHTML('<b>Memory used by Objects:</b> '.round($this->ProfilerTotals['objects']/1024, 2).'Kb');
}
if( dbg_ConstOn('DBG_INCLUDED_FILES') )
{
$files = get_included_files();
$this->appendHTML('<b>Included files:</b>');
foreach ($files as $file)
{
$this->appendHTML($this->getFileLink($this->getLocalFile($file)).' ('.round(filesize($file)/1024, 2).'Kb)');
}
}
if( dbg_ConstOn('DBG_PROFILE_INCLUDES') )
{
$this->appendHTML('<b>Included files statistics:</b>'.( dbg_ConstOn('DBG_SORT_INCLUDES_MEM') ? ' (sorted by memory usage)':''));
$totals = Array( 'mem' => 0, 'time' => 0);
$totals_configs = Array( 'mem' => 0, 'time' => 0);
if ( dbg_ConstOn('DBG_SORT_INCLUDES_MEM') ) {
array_multisort($this->IncludesData['mem'], SORT_DESC, $this->IncludesData['file'], $this->IncludesData['time'], $this->IncludesData['level']);
}
foreach ($this->IncludesData['file'] as $key => $file_name) {
$this->appendHTML( str_repeat('&nbsp;->&nbsp;', ($this->IncludesData['level'][$key] >= 0 ? $this->IncludesData['level'][$key] : 0)).$file_name.' Mem: '.sprintf("%.4f Kb", $this->IncludesData['mem'][$key]/1024).' Time: '.sprintf("%.4f", $this->IncludesData['time'][$key]));
if ($this->IncludesData['level'][$key] == 0) {
$totals['mem'] += $this->IncludesData['mem'][$key];
$totals['time'] += $this->IncludesData['time'][$key];
}
else if ($this->IncludesData['level'][$key] == -1) {
$totals_configs['mem'] += $this->IncludesData['mem'][$key];
$totals_configs['time'] += $this->IncludesData['time'][$key];
}
}
$this->appendHTML('<b>Sub-Total classes:</b> '.' Mem: '.sprintf("%.4f Kb", $totals['mem']/1024).' Time: '.sprintf("%.4f", $totals['time']));
$this->appendHTML('<b>Sub-Total configs:</b> '.' Mem: '.sprintf("%.4f Kb", $totals_configs['mem']/1024).' Time: '.sprintf("%.4f", $totals_configs['time']));
$this->appendHTML('<span class="error"><b>Grand Total:</b></span> '.' Mem: '.sprintf("%.4f Kb", ($totals['mem']+$totals_configs['mem'])/1024).' Time: '.sprintf("%.4f", $totals['time']+$totals_configs['time']));
}
$i = 0; $lineCount = count($this->Data);
if( !ob_get_length() ) ob_start();
?>
<style type="text/css">
+ .dbg_profiler {
+ margin-top: 5px;
+ height: 10px;
+ border: 1px solid #000000;
+ float: left;
+ }
+
.dbg_flat_table {
border-collapse: collapse;
width: auto;
}
.dbg_flat_table TD {
border: 1px solid buttonface;
padding: 4px;
}
.debug_layer_table {
border-collapse: collapse;
- width: <?php echo DBG_WINDOW_WIDTH - 20; ?>px;
+ width: <?php echo $this->getWindowWidth(); ?>px;
}
.debug_text, .debug_row_even TD, .debug_row_odd TD {
color: #000000;
font-family: Verdana;
font-size: 11px;
word-wrap: break-word;
}
.debug_cell {
border: 1px solid #FF0000;
padding: 4px;
word-wrap: break-word;
text-align: left;
}
.debug_row_even {
background-color: #CCCCFF;
}
.debug_row_odd {
background-color: #FFFFCC;
}
.debug_layer_container {
left: 2px;
top: 1px;
width: <?php echo DBG_WINDOW_WIDTH; ?>px;
z-index: +1000;
position: absolute;
overflow: auto;
border: 2px solid;
padding: 3px;
border-top-color: threedlightshadow;
border-left-color: threedlightshadow;
border-right-color: threeddarkshadow;
border-bottom-color: threeddarkshadow;
background-color: buttonface;
}
.debug_layer {
padding: 0px;
- width: <?php echo DBG_WINDOW_WIDTH - 20; ?>px;
+ width: <?php echo $this->getWindowWidth(); ?>px;
}
.debug_error {
color: #FF0000;
}
</style>
<div id="debug_layer" class="debug_layer_container" style="display: none;">
<div class="debug_layer">
<table width="100%" cellpadding="0" cellspacing="1" border="0" class="debug_layer_table">
<?php
while ($i < $lineCount)
{
echo '<tr class="debug_row_'.(($i % 2) ? 'odd' : 'even').'"><td class="debug_cell">'.$this->prepareHTML($i).'</td></tr>';
$i++;
}
?>
</table>
</div>
</div>
<script language="javascript">
function dbg_OpenDOMViewer()
{
var $value = document.getElementById('dbg_domviewer').value;
DOMViewerObj = ($value.indexOf('"') != -1) ? document.getElementById( $value.substring(1,$value.length-1) ) : eval($value);
window.open('<?php echo constant('DBG_DOMVIEWER'); ?>');
return false;
}
function getEventKeyCode($e)
{
var $KeyCode = 0;
if($e.keyCode) $KeyCode = $e.keyCode;
else if($e.which) $KeyCode = $e.which;
return $KeyCode;
}
function keyProcessor($e)
{
if(!$e) $e = window.event;
var $KeyCode = getEventKeyCode($e);
if($KeyCode==123||$KeyCode==27) // F12 or ESC
{
toggleDebugLayer($KeyCode);
$e.cancelBubble = true;
if($e.stopPropagation) $e.stopPropagation();
}
}
function toggleDebugLayer($KeyCode)
{
var $isVisible=false;
var $DebugLayer = document.getElementById('debug_layer');
if( typeof($DebugLayer) != 'undefined' )
{
$isVisible = ($DebugLayer.style.display == 'none')?false:true;
if(!$isVisible&&$KeyCode==27) return false;
resizeDebugLayer(null);
$DebugLayer.style.display = $isVisible?'none':'block';
}
}
function prepareSizes($Prefix)
{
var $ret = '';
$ret = eval('document.body.'+$Prefix+'Top')+'; ';
$ret += eval('document.body.'+$Prefix+'Left')+'; ';
$ret += eval('document.body.'+$Prefix+'Height')+'; ';
$ret += eval('document.body.'+$Prefix+'Width')+'; ';
return $ret;
}
function resizeDebugLayer($e)
{
if(!$e) $e = window.event;
var $DebugLayer = document.getElementById('debug_layer');
var $TopMargin = 1;
var $pageWidth = document.all ? document.body.offsetWidth - 4 : window.innerWidth;
var $pageHeight = document.all ? document.body.clientHeight : window.innerHeight; // document.body.offsetHeight - 2
var $pageTop = document.all ? document.body.offsetTop + document.body.scrollTop : window.scrollY;
if( typeof($DebugLayer) != 'undefined' )
{
if(document.all)
{
$DebugLayer.style.top = ($pageTop + 2) + 'px';
$DebugLayer.style.height = ($pageHeight - 2 - 4) + 'px';
}
else
{
$DebugLayer.style.top = ($pageTop + 2) + 'px';
$DebugLayer.style.height = ($pageHeight - 2 - 15) + 'px';
}
}
// window.parent.status = 'OFFSET: '+prepareSizes('offset')+' | SCROLL: '+prepareSizes('scroll')+' | CLIENT: '+prepareSizes('client');
// window.parent.status += 'DL Info: '+$DebugLayer.style.top+'; S.AH: '+screen.availHeight;
return true;
}
function SetClipboard(copyText)
{
if(window.clipboardData)
{
// IE send-to-clipboard method.
window.clipboardData.setData('Text', copyText);
}
else if (window.netscape)
{
// You have to sign the code to enable this or allow the action in about:config by changing user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
// Store support string in an object.
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
if (!str) return false;
str.data=copyText;
// Make transferable.
var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return false;
// Specify what datatypes we want to obtain, which is text in this case.
trans.addDataFlavor("text/unicode");
trans.setTransferData("text/unicode",str,copyText.length*2);
var clipid=Components.interfaces.nsIClipboard;
var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
function showProps($Obj, $Name)
{
var $ret = '';
for($Prop in $Obj)
{
$ret += $Name+'.'+$Prop+' = '+$Obj[$Prop]+"\n";
}
return $ret;
}
function editFile($fileName,$lineNo)
{
if(!document.all)
{
alert('Only works in IE');
return;
}
var $editorPath = '<?php echo defined('WINDOWS_EDITOR') ? addslashes(WINDOWS_EDITOR) : '' ?>';
if($editorPath)
{
var $obj = new ActiveXObject("LaunchinIE.Launch");
$editorPath = $editorPath.replace('%F',$fileName);
$editorPath = $editorPath.replace('%L',$lineNo);
$obj.LaunchApplication($editorPath);
}
else
{
alert('Editor path not defined!');
}
}
function toggleTraceArgs($ArgsLayerID)
{
var $ArgsLayer = document.getElementById($ArgsLayerID);
$ArgsLayer.style.display = ($ArgsLayer.style.display == 'none') ? 'block' : 'none';
}
document.onkeydown = keyProcessor;
window.onresize = resizeDebugLayer;
window.onscroll = resizeDebugLayer;
window.focus();
if( typeof($isFatalError) != 'undefined' && $isFatalError == 1 || <?php echo DBG_RAISE_ON_WARNINGS; ?> )
{
toggleDebugLayer();
}
if( typeof($isFatalError) != 'undefined' && $isFatalError == 1)
{
document.getElementById('debug_layer').scrollTop = 10000000;
}
</script>
<?php
dbg_safeDefine('DBG_SHOW_MEMORY_USAGE', 1);
if( dbg_ConstOn('DBG_SHOW_MEMORY_USAGE') )
{
$this->memoryUsage['debugger_finish']=memory_get_usage();
$this->memoryUsage['print_report']=$this->memoryUsage['debugger_finish']-$this->memoryUsage['debugger_start'];
$this->memoryUsage['total']=$this->memoryUsage['print_report']+$this->memoryUsage['error_handling'];
$this->memoryUsage['application']=memory_get_usage()-$this->memoryUsage['total'];
}
if($returnResult)
{
$ret = ob_get_contents();
if($clean_output_buffer) ob_clean();
if( dbg_ConstOn('DBG_SHOW_MEMORY_USAGE') ) $ret .= $this->getMemoryUsageReport();
$this->reportDone = true;
return $ret;
}
else
{
if( !dbg_ConstOn('DBG_HIDE_FULL_REPORT') )
{
ob_end_flush();
}
else
{
if($clean_output_buffer) ob_clean();
}
if( dbg_ConstOn('DBG_SHOW_MEMORY_USAGE') ) echo $this->getMemoryUsageReport();
$this->reportDone = true;
}
}
/**
* Format's memory usage report by debugger
*
* @return string
* @access private
*/
function getMemoryUsageReport()
{
if( !dbg_ConstOn('DBG_SHOW_MEMORY_USAGE') ) return '';
$info = Array('<a href="javascript:self.location.reload()">printReport</a>'=>'print_report',
'saveError'=>'error_handling',
'Total'=>'total',
'Application'=>'application');
$ret=Array();
foreach($info as $title => $value_key)
{
$ret[]='<tr><td>'.$title.':</td><td><b>'.$this->formatSize($this->memoryUsage[$value_key]).'</b></td></tr>';
}
return '<table class="dbg_flat_table">'.implode('',$ret).'</table>';
}
/**
* User-defined error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param array $errcontext
*/
function saveError($errno, $errstr, $errfile = '', $errline = '', $errcontext = '')
{
$memory_used=Array();
$memory_used['begin']=memory_get_usage();
$errorType = $this->getErrorNameByCode($errno);
if(!$errorType)
{
trigger_error('Unknown error type ['.$errno.']', E_USER_ERROR);
return false;
}
if( dbg_ConstOn('DBG_IGNORE_STRICT_ERRORS') && defined('E_STRICT') && ($errno == E_STRICT) ) return;
$long_id_pos=strrpos($errstr,'#');
if($long_id_pos!==false)
{
// replace short message with long one (due triger_error limitations on message size)
$long_id=substr($errstr,$long_id_pos+1,strlen($errstr));
$errstr=$this->longErrors[$long_id];
unset($this->longErrors[$long_id]);
}
/*in /www/kostja/in-commerce4/kernel/kernel4/parser/construct_tags.php(177) : runtime-created function on line
[PRE-PARSED block, $line 13]: Undefined variable: IdField*/
/*
if( strpos($errfile,'runtime-created') !== false ) {
$errfile = ' PRE-PARSED block <b>'.$this->CurrentPreParsedBlock.'</b> ';
}*/
if( strpos($errfile,'eval()\'d code') !== false )
{
$errstr = '[<b>EVAL</b>, line <b>'.$errline.'</b>]: '.$errstr;
$tmpStr = $errfile;
$pos = strpos($tmpStr,'(');
$errfile = substr($tmpStr,0,$pos);
$pos++;
$errline = substr($tmpStr,$pos,strpos($tmpStr,')',$pos)-$pos);
}
// if($this->TraceNextError || $errno == E_USER_ERROR)
if($this->TraceNextError)
{
$this->appendTrace();
$this->TraceNextError=false;
}
$this->Data[] = Array('no' => $errno, 'str' => $errstr, 'file' => $errfile, 'line' => $errline, 'context' => $errcontext, 'debug_type' => 'error');
$memory_used['end']=memory_get_usage();
$this->memoryUsage['error_handling']+=$memory_used['end']-$memory_used['begin'];
if( substr($errorType,0,5) == 'Fatal')
{
echo '<script language="javascript">var $isFatalError = 1;</script>';
if( !dbg_ConstOn('DBG_USE_SHUTDOWN_FUNC') ) $this->printReport();
exit;
}
}
function saveToFile($msg)
{
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/vb_debug.txt', 'a');
fwrite($fp,$msg."\n");
fclose($fp);
}
/**
* Formats file/memory size in nice way
*
* @param int $bytes
* @return string
* @access public
*/
function formatSize($bytes)
{
if ($bytes >= 1099511627776) {
$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "TB";
} elseif ($bytes >= 1073741824) {
$return = round($bytes / 1024 / 1024 / 1024, 2);
$suffix = "GB";
} elseif ($bytes >= 1048576) {
$return = round($bytes / 1024 / 1024, 2);
$suffix = "MB";
} elseif ($bytes >= 1024) {
$return = round($bytes / 1024, 2);
$suffix = "KB";
} else {
$return = $bytes;
$suffix = "Byte";
}
$return .= ' '.$suffix;
return $return;
}
}
if( !function_exists('memory_get_usage') )
{
function memory_get_usage(){ return -1; }
}
if( !dbg_ConstOn('DBG_ZEND_PRESENT') )
{
$debugger = new Debugger();
}
if( dbg_ConstOn('DBG_HANDLE_ERRORS') )
{
if( class_exists('kApplication') )
{
$application =& kApplication::Instance();
$application->Debugger =& $debugger;
$application->errorHandlers[] = Array(&$debugger, 'saveError');
}
else
{
set_error_handler( Array(&$debugger, 'saveError') );
}
}
if( dbg_ConstOn('DBG_USE_SHUTDOWN_FUNC') ) register_shutdown_function( Array(&$debugger, 'printReport') );
}
?>
\ No newline at end of file
Property changes on: trunk/kernel/include/debugger.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.49
\ No newline at end of property
+1.50
\ No newline at end of property
Index: trunk/core/kernel/utility/debugger.php
===================================================================
--- trunk/core/kernel/utility/debugger.php (revision 3814)
+++ trunk/core/kernel/utility/debugger.php (revision 3815)
@@ -1,1038 +1,1085 @@
<?php
if( !class_exists('Debugger') )
{
function dbg_ConstOn($const_name)
{
return defined($const_name) && constant($const_name);
}
function dbg_safeDefine($const_name,$const_value)
{
if(!defined($const_name)) define($const_name,$const_value);
}
unset($_REQUEST['debug_host'], $_REQUEST['debug_fastfile']); // this var messed up whole detection stuff :(
// Detect fact, that this session beeing debugged by Zend Studio
foreach($_REQUEST as $rq_name=>$rq_value)
{
if( substr($rq_name,0,6)=='debug_' )
{
dbg_safeDefine('DBG_ZEND_PRESENT', 1);
break;
}
}
dbg_safeDefine('DBG_ZEND_PRESENT',0);
// set default values for debugger constants
$dbg_constMap=Array('DBG_OPTIONS'=>0,
'DBG_USE_HIGHLIGHT'=>1,
'DBG_USE_SHUTDOWN_FUNC'=>DBG_ZEND_PRESENT?0:1,
'DBG_HANDLE_ERRORS'=>DBG_ZEND_PRESENT?0:1,
'DBG_IGNORE_STRICT_ERRORS'=>1,
'DBG_DOMVIEWER'=>'/temp/domviewer.html',
'DOC_ROOT'=> str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT']) ), // windows hack
'DBG_LOCAL_BASE_PATH'=>'w:');
foreach($dbg_constMap as $dbg_constName=>$dbg_constValue)
{
dbg_safeDefine($dbg_constName,$dbg_constValue);
}
// only for IE, in case if no windows php script editor defined
/*if(!defined('WINDOWS_EDITOR'))
{
$dbg_editor = 0;
$dbg_editors[0] = Array('editor' => 'c:\Program Files\UltraEdit\uedit32.exe', 'params' => '%F/%L');
$dbg_editors[1] = Array('editor' => 'c:\Program Files\Zend\ZendStudio-4.0Beta\bin\ZDE.exe', 'params' => '%F');
define('WINDOWS_EDITOR',$dbg_editors[$dbg_editor]['editor'].' '.$dbg_editors[$dbg_editor]['params']);
unset($dbg_editors,$dbg_editor);
}*/
class Debugger
{
/**
* Debugger data for building report
*
* @var Array
*/
var $Data = Array();
var $ProfilerData = Array();
var $ProfilerTotals = Array();
var $ProfilerTotalCount = Array();
var $RecursionStack = Array(); // prevent recursion when processing debug_backtrace() function results
var $TraceNextError=false;
var $Options = 0;
var $OptionsMap = Array('shutdown_func' => 1, 'error_handler' => 2,
'output_buffer' => 4, 'highlight_output' => 8);
-
- var $longErrors=Array();
+ var $scrollbarWidth = 0;
+
+ var $longErrors = Array();
/**
* Amount of memory used by debugger itself
*
* @var Array
* @access private
*/
- var $memoryUsage=Array();
+ var $memoryUsage = Array();
- var $IncludesData=Array();
- var $IncludeLevel=0;
+ var $IncludesData = Array();
+ var $IncludeLevel = 0;
var $reportDone = false;
+ var $dummyImage = 'http://www.adamauto.lv/chevrolet/images/spacer.gif';
+
function Debugger()
{
$this->profileStart('kernel4_startup', 'Startup and Initialization of kernel4');
$this->profileStart('script_runtime', 'Script runtime');
- ini_set('display_errors',dbg_ConstOn('DBG_ZEND_PRESENT')?0:1);
- $this->memoryUsage['error_handling']=0; // memory amount used by error handler
+ ini_set('display_errors', dbg_ConstOn('DBG_ZEND_PRESENT') ? 0 : 1);
+ $this->memoryUsage['error_handling'] = 0; // memory amount used by error handler
+
+ $this->scrollbarWidth = $this->isGecko() ? 22 : 25;
+ dbg_safeDefine('DBG_WINDOW_WIDTH', 700);
$this->appendRequest();
}
function initOptions()
{
}
function mapLongError($msg)
{
$key=$this->generateID();
$this->longErrors[$key]=$msg;
return $key;
}
function setOption($name,$value)
{
if( !isset($this->OptionsMap[$name]) ) die('undefined debugger option: ['.$name.']<br>');
if($value)
{
$this->Options|=$this->OptionsMap[$name];
}
else
{
$this->Options=$this->Options&~$this->OptionsMap[$name];
}
}
function getOption($name)
{
if( !isset($this->OptionsMap[$name]) ) die('undefined debugger option: ['.$name.']<br>');
return ($this->Options & $this->OptionsMap[$name]) == $this->OptionsMap[$name];
}
/**
* Set's flag, that next error that occurs will
* be prepended by backtrace results
*
*/
function traceNext()
{
- $this->TraceNextError=true;
+ $this->TraceNextError = true;
}
function dumpVars()
{
$dumpVars = func_get_args();
foreach($dumpVars as $varValue)
{
$this->Data[] = Array('value' => $varValue, 'debug_type' => 'var_dump');
}
}
function prepareHTML($dataIndex)
{
$Data =& $this->Data[$dataIndex];
if($Data['debug_type'] == 'html') return $Data['html'];
switch($Data['debug_type'])
{
case 'error':
$fileLink = $this->getFileLink($Data['file'],$Data['line']);
$ret = '<b class="debug_error">'.$this->getErrorNameByCode($Data['no']).'</b>: '.$Data['str'];
$ret .= ' in <b>'.$fileLink.'</b> on line <b>'.$Data['line'].'</b>';
return $ret;
break;
case 'var_dump':
return $this->highlightString( print_r($Data['value'], true) );
break;
case 'trace':
ini_set('memory_limit','500M');
$trace =& $Data['trace'];
//return 'sorry';
//return $this->highlightString(print_r($trace,true));
$i = 0; $traceCount = count($trace);
$ret = '';
while($i < $traceCount)
{
$traceRec =& $trace[$i];
$argsID = 'trace_args_'.$dataIndex.'_'.$i;
$has_args = isset($traceRec['args']);
if(isset($traceRec['file']))
{
$func_name=isset($traceRec['class'])?$traceRec['class'].$traceRec['type'].$traceRec['function']:$traceRec['function'];
$args_link = $has_args ? '<a href="javascript:toggleTraceArgs(\''.$argsID.'\');" title="Show/Hide Function Arguments"><b>Function</b></a>' : '<b>Function</b>';
$ret .= $args_link.': '.$this->getFileLink($traceRec['file'],$traceRec['line'],$func_name);
$ret .= ' in <b>'.basename($traceRec['file']).'</b> on line <b>'.$traceRec['line'].'</b><br>';
}
else
{
$ret .= 'no file information available';
}
// ensure parameter value is not longer then 200 symbols
if($has_args)
{
$this->processTraceArguments($traceRec['args']);
$args = $this->highlightString(print_r($traceRec['args'], true));
$ret .= '<div id="'.$argsID.'" style="display: none;">'.$args.'</div>';
}
$i++;
}
return $ret;
break;
case 'profiler':
$profileKey = $Data['profile_key'];
$Data =& $this->ProfilerData[$profileKey];
$runtime = ($Data['ends'] - $Data['begins']); // in seconds
- return '<b>Name</b>: '.$Data['description'].'<br><b>Runtime</b>: '.$runtime.'s';
+
+
+ $totals_key = getArrayValue($Data, 'totalsKey');
+ if ($totals_key) {
+ $total_before = $Data['totalsBefore'];
+ $total = $this->ProfilerTotals[$totals_key];
+
+ $div_width = Array();
+ $div_width['before'] = ($total_before / $total) * $this->getWindowWidth();
+ $div_width['current'] = ($runtime / $total) * $this->getWindowWidth();
+ $div_width['left'] = (($total - $total_before - $runtime) / $total) * $this->getWindowWidth();
+
+ $ret = '<b>Name</b>: '.$Data['description'].'<br>';
+ $ret .= '<b>Runtime</b>: '.$runtime.'s';
+ $ret .= '<div class="dbg_profiler" style="width: '.$div_width['before'].'px; border-right: 0px; background-color: #298DDF;"><img src="'.$this->dummyImage.'" width="1" height="1"/></div>';
+ $ret .= '<div class="dbg_profiler" style="width: '.$div_width['current'].'px; border-left: 0px; border-right: 0px; background-color: #EF4A4A;"><img src="'.$this->dummyImage.'" width="1" height="1"/></div>';
+ $ret .= '<div class="dbg_profiler" style="width: '.$div_width['left'].'px; border-left: 0px; background-color: #DFDFDF;"><img src="'.$this->dummyImage.'" width="1" height="1"/></div>';
+
+ return $ret;
+ }
+ else {
+ return '<b>Name</b>: '.$Data['description'].'<br><b>Runtime</b>: '.$runtime.'s';
+ }
break;
default:
return 'incorrect debug data';
break;
}
}
+ function getWindowWidth()
+ {
+ return DBG_WINDOW_WIDTH - $this->scrollbarWidth;
+ }
+
function isApplication(&$object)
{
$app_class = defined('APPLICATION_CLASS') ? strtolower(APPLICATION_CLASS) : 'kApplication';
return get_class($object) == $app_class;
}
function processTraceArguments(&$traceArgs)
{
if(!$traceArgs) return '';
$array_keys = array_keys($traceArgs);
foreach($array_keys as $argID)
{
$argValue =& $traceArgs[$argID];
if( is_array($argValue) || is_object($argValue) )
{
if(is_object($argValue) && !in_array(get_class($argValue),$this->RecursionStack) )
{
array_push($this->RecursionStack, get_class($argValue));
if( get_class($argValue) == 'kfactory' || $this->isApplication($argValue) || get_class($argValue) == 'templateparser' )
{
$argValue = null;
continue;
}
// object & not in stack - ok
settype($argValue,'array');
$this->processTraceArguments($argValue);
array_pop($this->RecursionStack);
}
elseif(is_object($argValue) && in_array(get_class($argValue),$this->RecursionStack) )
{
// object & in stack - recursion
$traceArgs[$argID] = '**** RECURSION ***';
}
else
{
// normal array here
$this->processTraceArguments($argValue);
}
}
else
{
$traceArgs[$argID] = $this->cutStringForHTML($traceArgs[$argID]);
}
}
}
function cutStringForHTML($string)
{
if( strlen($string) > 200 ) $string = substr($string,0,50).' ...';
return $string;
}
/**
* Format SQL Query using predefined formatting
* and highlighting techniques
*
* @param string $sql
* @return string
*/
function formatSQL($sql)
{
$sql = preg_replace('/(\n|\t| )+/is',' ',$sql);
$sql = preg_replace('/(CREATE TABLE|DROP TABLE|SELECT|UPDATE|SET|REPLACE|INSERT|DELETE|VALUES|FROM|LEFT JOIN|INNER JOIN|LIMIT|WHERE|HAVING|GROUP BY|ORDER BY) /is', "\n\t$1 ",$sql);
return $this->highlightString($sql);
}
function highlightString($string)
{
if( dbg_ConstOn('DBG_USE_HIGHLIGHT') )
{
$string = str_replace( Array('\\', '/') , Array('_no_match_string_', '_n_m_s_'), $string);
$string = highlight_string('<?php '.$string.'?>', true);
$string = str_replace( Array('_no_match_string_', '_n_m_s_'), Array('\\', '/'), $string);
- return preg_replace('/&lt;\?(.*)php (.*)\?&gt;/s', '$2', $string);
+ return preg_replace('/&lt;\?php(.*)\?&gt;/s', '\\1', $string);
}
else
{
return $string;
}
}
-
+
+ function isGecko()
+ {
+ return strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'firefox') !== false;
+ }
+
function getFileLink($file, $lineno = 1, $title = '')
{
- if(!$title) $title = $file;
- $is_mozilla=strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'firefox')!==false?true:false;
- if($is_mozilla)
- {
+ if (!$title) $title = $file;
+
+ if ($this->isGecko()) {
return '<a href="file://'.$this->getLocalFile($file).'">'.$title.'</a>';
}
- else
- {
+ else {
return '<a href="javascript:editFile(\''.$this->getLocalFile($file).'\','.$lineno.');" title="'.$file.'">'.$title.'</a>';
}
}
function getLocalFile($remoteFile)
{
return str_replace(DOC_ROOT, DBG_LOCAL_BASE_PATH, $remoteFile);
}
function appendTrace()
{
$trace = debug_backtrace();
array_shift($trace);
$this->Data[] = Array('trace' => $trace, 'debug_type' => 'trace');
}
function appendMemoryUsage($msg, $used=null)
{
if (!isset($used)) $used = round(memory_get_usage()/1024);
$this->appendHTML('<b>Memory usage</b> '.$msg.' '.$used.'Kb');
}
function appendHTML($html)
{
$this->Data[] = Array('html' => $html,'debug_type' => 'html');
}
/**
* Change debugger info that was already generated before.
* Returns true if html was set.
*
* @param int $index
* @param string $html
* @param string $type = {'append','prepend','replace'}
* @return bool
*/
function setHTMLByIndex($index,$html,$type='append')
{
if( !isset($this->Data[$index]) || $this->Data[$index]['debug_type'] != 'html' )
{
return false;
}
switch ($type)
{
case 'append':
$this->Data[$index]['html'] .= '<br>'.$html;
break;
case 'prepend':
$this->Data[$index]['html'] = $this->Data[$index]['html'].'<br>'.$html;
break;
case 'replace':
$this->Data[$index]['html'] = $html;
break;
}
return true;
}
/**
* Move $debugLineCount lines of input from debug output
* end to beginning.
*
* @param int $debugLineCount
*/
function moveToBegin($debugLineCount)
{
$lines = array_splice($this->Data,count($this->Data)-$debugLineCount,$debugLineCount);
$this->Data = array_merge($lines,$this->Data);
}
function moveAfterRow($new_row, $debugLineCount)
{
$lines = array_splice($this->Data,count($this->Data)-$debugLineCount,$debugLineCount);
$rows_before = array_splice($this->Data,0,$new_row,$lines);
$this->Data = array_merge($rows_before,$this->Data);
}
function appendRequest()
{
- dbg_safeDefine('DBG_WINDOW_WIDTH', 700);
-
if (isset($_SERVER['SCRIPT_FILENAME'])) {
$script = $_SERVER['SCRIPT_FILENAME'];
}
else {
$script = $_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF'];
}
$this->appendHTML('ScriptName: <b>'.$this->getFileLink($script,1,basename($script)).'</b> (<b>'.dirname($script).'</b>)');
$this->appendHTML('<a href="http://www.brainjar.com/dhtml/domviewer/" target="_blank">DomViewer</a>: <input id="dbg_domviewer" type="text" value="window" style="border: 1px solid #000000;"/>&nbsp;<button class="button" onclick="return dbg_OpenDOMViewer();">Show</button>');
ob_start();
?>
- <table border="0" cellspacing="0" cellpadding="0" class="dbg_flat_table" style="width: <?php echo DBG_WINDOW_WIDTH; ?>px;">
+ <table border="0" cellspacing="0" cellpadding="0" class="dbg_flat_table" style="width: <?php echo $this->getWindowWidth(); ?>px;">
<thead style="font-weight: bold;">
<td width="20">Src</td><td>Name</td><td>Value</td>
</thead>
<?php
foreach($_REQUEST as $key => $value)
{
if( !is_array($value) && trim($value) == '' )
{
$value = '<b class="debug_error">no value</b>';
}
else
{
$value = htmlspecialchars(print_r($value, true));
}
$in_cookie = isset($_COOKIE[$key]);
$src = isset($_GET[$key]) && !$in_cookie ? 'GE' : (isset($_POST[$key]) && !$in_cookie ? 'PO' : ($in_cookie ? 'CO' : '?') );
echo '<tr><td>'.$src.'</td><td>'.$key.'</td><td>'.$value.'</td></tr>';
}
?>
</table>
<?php
$this->appendHTML( ob_get_contents() );
ob_end_clean();
}
function appendSession()
{
if( isset($_SESSION)&&$_SESSION )
{
$this->appendHTML('PHP Session: [<b>'.ini_get('session.name').'</b>]');
$this->dumpVars($_SESSION);
$this->moveToBegin(2);
}
}
function profileStart($key, $description = null)
{
$timeStamp = $this->getMoment();
$this->ProfilerData[$key] = Array('begins' => $timeStamp, 'ends' => 5000, 'debuggerRowID' => count($this->Data));
if (isset($description)) {
$this->ProfilerData[$key]['description'] = $description;
}
$this->Data[] = array('profile_key' => $key, 'debug_type' => 'profiler');
}
function profileFinish($key, $description = null)
{
$this->ProfilerData[$key]['ends'] = $this->getMoment();
if (isset($description)) {
$this->ProfilerData[$key]['description'] = $description;
}
}
function profilerAddTotal($total_key, $key=null, $value=null)
{
if (!isset($this->ProfilerTotals[$total_key])) {
$this->ProfilerTotals[$total_key] = 0;
$this->ProfilerTotalCount[$total_key] = 0;
}
if (!isset($value)) {
$value = $this->ProfilerData[$key]['ends'] - $this->ProfilerData[$key]['begins'];
}
+
+ if (isset($key)) {
+ $this->ProfilerData[$key]['totalsKey'] = $total_key;
+ $this->ProfilerData[$key]['totalsBefore'] = $this->ProfilerTotals[$total_key];
+ }
+
$this->ProfilerTotals[$total_key] += $value;
$this->ProfilerTotalCount[$total_key]++;
}
function getMoment()
{
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
function generateID()
{
list($usec, $sec) = explode(" ",microtime());
$id_part_1 = substr($usec, 4, 4);
$id_part_2 = mt_rand(1,9);
$id_part_3 = substr($sec, 6, 4);
$digit_one = substr($id_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$id_part_1 = ereg_replace("^0","",$id_part_1);
$id_part_1=$digit_one.$id_part_1;
}
return $id_part_1.$id_part_2.$id_part_3;
}
function getErrorNameByCode($errorCode)
{
switch($errorCode)
{
case E_USER_ERROR:
return 'Fatal Error';
break;
case E_WARNING:
case E_USER_WARNING:
return 'Warning';
break;
case E_NOTICE:
case E_USER_NOTICE:
return 'Notice';
break;
case E_STRICT:
return 'PHP5 Strict';
break;
default:
return '';
break;
}
}
/**
* Generates report
*
*/
function printReport($returnResult = false, $clean_output_buffer = true)
{
if($this->reportDone) return '';
if( dbg_ConstOn('DBG_SKIP_REPORTING') ) return;
$this->profileFinish('script_runtime');
if( dbg_ConstOn('DBG_ZEND_PRESENT') ) return;
dbg_safeDefine('DBG_RAISE_ON_WARNINGS',0);
$this->memoryUsage['debugger_start']=memory_get_usage();
// show php session if any
$this->appendSession();
// ensure, that 1st line of debug output always is this one:
$this->appendHTML('<a href="javascript:toggleDebugLayer(27);">Hide Debugger</a>');
$this->moveToBegin(1);
if( dbg_ConstOn('DBG_SQL_PROFILE') && isset($this->ProfilerTotals['sql']) )
{
$this->appendHTML('<b>SQL Total time:</b> '.$this->ProfilerTotals['sql'].' Number of queries: '.$this->ProfilerTotalCount['sql']);
}
if( dbg_ConstOn('DBG_PROFILE_MEMORY') )
{
$this->appendHTML('<b>Memory used by Objects:</b> '.round($this->ProfilerTotals['objects']/1024, 2).'Kb');
}
if( dbg_ConstOn('DBG_INCLUDED_FILES') )
{
$files = get_included_files();
$this->appendHTML('<b>Included files:</b>');
foreach ($files as $file)
{
$this->appendHTML($this->getFileLink($this->getLocalFile($file)).' ('.round(filesize($file)/1024, 2).'Kb)');
}
}
if( dbg_ConstOn('DBG_PROFILE_INCLUDES') )
{
$this->appendHTML('<b>Included files statistics:</b>'.( dbg_ConstOn('DBG_SORT_INCLUDES_MEM') ? ' (sorted by memory usage)':''));
$totals = Array( 'mem' => 0, 'time' => 0);
$totals_configs = Array( 'mem' => 0, 'time' => 0);
if ( dbg_ConstOn('DBG_SORT_INCLUDES_MEM') ) {
array_multisort($this->IncludesData['mem'], SORT_DESC, $this->IncludesData['file'], $this->IncludesData['time'], $this->IncludesData['level']);
}
foreach ($this->IncludesData['file'] as $key => $file_name) {
$this->appendHTML( str_repeat('&nbsp;->&nbsp;', ($this->IncludesData['level'][$key] >= 0 ? $this->IncludesData['level'][$key] : 0)).$file_name.' Mem: '.sprintf("%.4f Kb", $this->IncludesData['mem'][$key]/1024).' Time: '.sprintf("%.4f", $this->IncludesData['time'][$key]));
if ($this->IncludesData['level'][$key] == 0) {
$totals['mem'] += $this->IncludesData['mem'][$key];
$totals['time'] += $this->IncludesData['time'][$key];
}
else if ($this->IncludesData['level'][$key] == -1) {
$totals_configs['mem'] += $this->IncludesData['mem'][$key];
$totals_configs['time'] += $this->IncludesData['time'][$key];
}
}
$this->appendHTML('<b>Sub-Total classes:</b> '.' Mem: '.sprintf("%.4f Kb", $totals['mem']/1024).' Time: '.sprintf("%.4f", $totals['time']));
$this->appendHTML('<b>Sub-Total configs:</b> '.' Mem: '.sprintf("%.4f Kb", $totals_configs['mem']/1024).' Time: '.sprintf("%.4f", $totals_configs['time']));
$this->appendHTML('<span class="error"><b>Grand Total:</b></span> '.' Mem: '.sprintf("%.4f Kb", ($totals['mem']+$totals_configs['mem'])/1024).' Time: '.sprintf("%.4f", $totals['time']+$totals_configs['time']));
}
$i = 0; $lineCount = count($this->Data);
if( !ob_get_length() ) ob_start();
?>
<style type="text/css">
+ .dbg_profiler {
+ margin-top: 5px;
+ height: 10px;
+ border: 1px solid #000000;
+ float: left;
+ }
+
.dbg_flat_table {
border-collapse: collapse;
width: auto;
}
.dbg_flat_table TD {
border: 1px solid buttonface;
padding: 4px;
}
.debug_layer_table {
border-collapse: collapse;
- width: <?php echo DBG_WINDOW_WIDTH - 20; ?>px;
+ width: <?php echo $this->getWindowWidth(); ?>px;
}
.debug_text, .debug_row_even TD, .debug_row_odd TD {
color: #000000;
font-family: Verdana;
font-size: 11px;
word-wrap: break-word;
}
.debug_cell {
border: 1px solid #FF0000;
padding: 4px;
word-wrap: break-word;
text-align: left;
}
.debug_row_even {
background-color: #CCCCFF;
}
.debug_row_odd {
background-color: #FFFFCC;
}
.debug_layer_container {
left: 2px;
top: 1px;
width: <?php echo DBG_WINDOW_WIDTH; ?>px;
z-index: +1000;
position: absolute;
overflow: auto;
border: 2px solid;
padding: 3px;
border-top-color: threedlightshadow;
border-left-color: threedlightshadow;
border-right-color: threeddarkshadow;
border-bottom-color: threeddarkshadow;
background-color: buttonface;
}
.debug_layer {
padding: 0px;
- width: <?php echo DBG_WINDOW_WIDTH - 20; ?>px;
+ width: <?php echo $this->getWindowWidth(); ?>px;
}
.debug_error {
color: #FF0000;
}
</style>
<div id="debug_layer" class="debug_layer_container" style="display: none;">
<div class="debug_layer">
<table width="100%" cellpadding="0" cellspacing="1" border="0" class="debug_layer_table">
<?php
while ($i < $lineCount)
{
echo '<tr class="debug_row_'.(($i % 2) ? 'odd' : 'even').'"><td class="debug_cell">'.$this->prepareHTML($i).'</td></tr>';
$i++;
}
?>
</table>
</div>
</div>
<script language="javascript">
function dbg_OpenDOMViewer()
{
var $value = document.getElementById('dbg_domviewer').value;
DOMViewerObj = ($value.indexOf('"') != -1) ? document.getElementById( $value.substring(1,$value.length-1) ) : eval($value);
window.open('<?php echo constant('DBG_DOMVIEWER'); ?>');
return false;
}
function getEventKeyCode($e)
{
var $KeyCode = 0;
if($e.keyCode) $KeyCode = $e.keyCode;
else if($e.which) $KeyCode = $e.which;
return $KeyCode;
}
function keyProcessor($e)
{
if(!$e) $e = window.event;
var $KeyCode = getEventKeyCode($e);
if($KeyCode==123||$KeyCode==27) // F12 or ESC
{
toggleDebugLayer($KeyCode);
$e.cancelBubble = true;
if($e.stopPropagation) $e.stopPropagation();
}
}
function toggleDebugLayer($KeyCode)
{
var $isVisible=false;
var $DebugLayer = document.getElementById('debug_layer');
if( typeof($DebugLayer) != 'undefined' )
{
$isVisible = ($DebugLayer.style.display == 'none')?false:true;
if(!$isVisible&&$KeyCode==27) return false;
resizeDebugLayer(null);
$DebugLayer.style.display = $isVisible?'none':'block';
}
}
function prepareSizes($Prefix)
{
var $ret = '';
$ret = eval('document.body.'+$Prefix+'Top')+'; ';
$ret += eval('document.body.'+$Prefix+'Left')+'; ';
$ret += eval('document.body.'+$Prefix+'Height')+'; ';
$ret += eval('document.body.'+$Prefix+'Width')+'; ';
return $ret;
}
function resizeDebugLayer($e)
{
if(!$e) $e = window.event;
var $DebugLayer = document.getElementById('debug_layer');
var $TopMargin = 1;
var $pageWidth = document.all ? document.body.offsetWidth - 4 : window.innerWidth;
var $pageHeight = document.all ? document.body.clientHeight : window.innerHeight; // document.body.offsetHeight - 2
var $pageTop = document.all ? document.body.offsetTop + document.body.scrollTop : window.scrollY;
if( typeof($DebugLayer) != 'undefined' )
{
if(document.all)
{
$DebugLayer.style.top = ($pageTop + 2) + 'px';
$DebugLayer.style.height = ($pageHeight - 2 - 4) + 'px';
}
else
{
$DebugLayer.style.top = ($pageTop + 2) + 'px';
$DebugLayer.style.height = ($pageHeight - 2 - 15) + 'px';
}
}
// window.parent.status = 'OFFSET: '+prepareSizes('offset')+' | SCROLL: '+prepareSizes('scroll')+' | CLIENT: '+prepareSizes('client');
// window.parent.status += 'DL Info: '+$DebugLayer.style.top+'; S.AH: '+screen.availHeight;
return true;
}
function SetClipboard(copyText)
{
if(window.clipboardData)
{
// IE send-to-clipboard method.
window.clipboardData.setData('Text', copyText);
}
else if (window.netscape)
{
// You have to sign the code to enable this or allow the action in about:config by changing user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
// Store support string in an object.
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
if (!str) return false;
str.data=copyText;
// Make transferable.
var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return false;
// Specify what datatypes we want to obtain, which is text in this case.
trans.addDataFlavor("text/unicode");
trans.setTransferData("text/unicode",str,copyText.length*2);
var clipid=Components.interfaces.nsIClipboard;
var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
function showProps($Obj, $Name)
{
var $ret = '';
for($Prop in $Obj)
{
$ret += $Name+'.'+$Prop+' = '+$Obj[$Prop]+"\n";
}
return $ret;
}
function editFile($fileName,$lineNo)
{
if(!document.all)
{
alert('Only works in IE');
return;
}
var $editorPath = '<?php echo defined('WINDOWS_EDITOR') ? addslashes(WINDOWS_EDITOR) : '' ?>';
if($editorPath)
{
var $obj = new ActiveXObject("LaunchinIE.Launch");
$editorPath = $editorPath.replace('%F',$fileName);
$editorPath = $editorPath.replace('%L',$lineNo);
$obj.LaunchApplication($editorPath);
}
else
{
alert('Editor path not defined!');
}
}
function toggleTraceArgs($ArgsLayerID)
{
var $ArgsLayer = document.getElementById($ArgsLayerID);
$ArgsLayer.style.display = ($ArgsLayer.style.display == 'none') ? 'block' : 'none';
}
document.onkeydown = keyProcessor;
window.onresize = resizeDebugLayer;
window.onscroll = resizeDebugLayer;
window.focus();
if( typeof($isFatalError) != 'undefined' && $isFatalError == 1 || <?php echo DBG_RAISE_ON_WARNINGS; ?> )
{
toggleDebugLayer();
}
if( typeof($isFatalError) != 'undefined' && $isFatalError == 1)
{
document.getElementById('debug_layer').scrollTop = 10000000;
}
</script>
<?php
dbg_safeDefine('DBG_SHOW_MEMORY_USAGE', 1);
if( dbg_ConstOn('DBG_SHOW_MEMORY_USAGE') )
{
$this->memoryUsage['debugger_finish']=memory_get_usage();
$this->memoryUsage['print_report']=$this->memoryUsage['debugger_finish']-$this->memoryUsage['debugger_start'];
$this->memoryUsage['total']=$this->memoryUsage['print_report']+$this->memoryUsage['error_handling'];
$this->memoryUsage['application']=memory_get_usage()-$this->memoryUsage['total'];
}
if($returnResult)
{
$ret = ob_get_contents();
if($clean_output_buffer) ob_clean();
if( dbg_ConstOn('DBG_SHOW_MEMORY_USAGE') ) $ret .= $this->getMemoryUsageReport();
$this->reportDone = true;
return $ret;
}
else
{
if( !dbg_ConstOn('DBG_HIDE_FULL_REPORT') )
{
ob_end_flush();
}
else
{
if($clean_output_buffer) ob_clean();
}
if( dbg_ConstOn('DBG_SHOW_MEMORY_USAGE') ) echo $this->getMemoryUsageReport();
$this->reportDone = true;
}
}
/**
* Format's memory usage report by debugger
*
* @return string
* @access private
*/
function getMemoryUsageReport()
{
if( !dbg_ConstOn('DBG_SHOW_MEMORY_USAGE') ) return '';
$info = Array('<a href="javascript:self.location.reload()">printReport</a>'=>'print_report',
'saveError'=>'error_handling',
'Total'=>'total',
'Application'=>'application');
$ret=Array();
foreach($info as $title => $value_key)
{
$ret[]='<tr><td>'.$title.':</td><td><b>'.$this->formatSize($this->memoryUsage[$value_key]).'</b></td></tr>';
}
return '<table class="dbg_flat_table">'.implode('',$ret).'</table>';
}
/**
* User-defined error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param array $errcontext
*/
function saveError($errno, $errstr, $errfile = '', $errline = '', $errcontext = '')
{
$memory_used=Array();
$memory_used['begin']=memory_get_usage();
$errorType = $this->getErrorNameByCode($errno);
if(!$errorType)
{
trigger_error('Unknown error type ['.$errno.']', E_USER_ERROR);
return false;
}
if( dbg_ConstOn('DBG_IGNORE_STRICT_ERRORS') && defined('E_STRICT') && ($errno == E_STRICT) ) return;
$long_id_pos=strrpos($errstr,'#');
if($long_id_pos!==false)
{
// replace short message with long one (due triger_error limitations on message size)
$long_id=substr($errstr,$long_id_pos+1,strlen($errstr));
$errstr=$this->longErrors[$long_id];
unset($this->longErrors[$long_id]);
}
/*in /www/kostja/in-commerce4/kernel/kernel4/parser/construct_tags.php(177) : runtime-created function on line
[PRE-PARSED block, $line 13]: Undefined variable: IdField*/
/*
if( strpos($errfile,'runtime-created') !== false ) {
$errfile = ' PRE-PARSED block <b>'.$this->CurrentPreParsedBlock.'</b> ';
}*/
if( strpos($errfile,'eval()\'d code') !== false )
{
$errstr = '[<b>EVAL</b>, line <b>'.$errline.'</b>]: '.$errstr;
$tmpStr = $errfile;
$pos = strpos($tmpStr,'(');
$errfile = substr($tmpStr,0,$pos);
$pos++;
$errline = substr($tmpStr,$pos,strpos($tmpStr,')',$pos)-$pos);
}
// if($this->TraceNextError || $errno == E_USER_ERROR)
if($this->TraceNextError)
{
$this->appendTrace();
$this->TraceNextError=false;
}
$this->Data[] = Array('no' => $errno, 'str' => $errstr, 'file' => $errfile, 'line' => $errline, 'context' => $errcontext, 'debug_type' => 'error');
$memory_used['end']=memory_get_usage();
$this->memoryUsage['error_handling']+=$memory_used['end']-$memory_used['begin'];
if( substr($errorType,0,5) == 'Fatal')
{
echo '<script language="javascript">var $isFatalError = 1;</script>';
if( !dbg_ConstOn('DBG_USE_SHUTDOWN_FUNC') ) $this->printReport();
exit;
}
}
function saveToFile($msg)
{
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/vb_debug.txt', 'a');
fwrite($fp,$msg."\n");
fclose($fp);
}
/**
* Formats file/memory size in nice way
*
* @param int $bytes
* @return string
* @access public
*/
function formatSize($bytes)
{
if ($bytes >= 1099511627776) {
$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "TB";
} elseif ($bytes >= 1073741824) {
$return = round($bytes / 1024 / 1024 / 1024, 2);
$suffix = "GB";
} elseif ($bytes >= 1048576) {
$return = round($bytes / 1024 / 1024, 2);
$suffix = "MB";
} elseif ($bytes >= 1024) {
$return = round($bytes / 1024, 2);
$suffix = "KB";
} else {
$return = $bytes;
$suffix = "Byte";
}
$return .= ' '.$suffix;
return $return;
}
}
if( !function_exists('memory_get_usage') )
{
function memory_get_usage(){ return -1; }
}
if( !dbg_ConstOn('DBG_ZEND_PRESENT') )
{
$debugger = new Debugger();
}
if( dbg_ConstOn('DBG_HANDLE_ERRORS') )
{
if( class_exists('kApplication') )
{
$application =& kApplication::Instance();
$application->Debugger =& $debugger;
$application->errorHandlers[] = Array(&$debugger, 'saveError');
}
else
{
set_error_handler( Array(&$debugger, 'saveError') );
}
}
if( dbg_ConstOn('DBG_USE_SHUTDOWN_FUNC') ) register_shutdown_function( Array(&$debugger, 'printReport') );
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/utility/debugger.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.34
\ No newline at end of property
+1.35
\ No newline at end of property

Event Timeline