Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Fri, Feb 7, 6:13 AM

in-portal

Index: branches/RC/core/kernel/utility/debugger/debugger.js
===================================================================
--- branches/RC/core/kernel/utility/debugger/debugger.js (revision 10576)
+++ branches/RC/core/kernel/utility/debugger/debugger.js (revision 10577)
@@ -1,430 +1,448 @@
function DebugReq() {}
DebugReq.timeout = 5000; //5 seconds
DebugReq.makeRequest = function(p_url, p_busyReq, p_progId, p_successCallBack, p_errorCallBack, p_pass, p_object) {
//p_url: the web service url
//p_busyReq: is a request for this object currently in progress?
//p_progId: element id where progress HTML should be shown
//p_successCallBack: callback function for successful response
//p_errorCallBack: callback function for erroneous response
//p_pass: string of params to pass to callback functions
//p_object: object of params to pass to callback functions
if (p_busyReq) {
return;
}
var req = DebugReq.getRequest();
if (req != null) {
p_busyReq = true;
DebugReq.showProgress(p_progId);
req.onreadystatechange = function() {
if (req.readyState == 4) {
p_busyReq = false;
window.clearTimeout(toId);
if (req.status == 200) {
p_successCallBack(req,p_pass,p_object);
} else {
p_errorCallBack(req,p_pass,p_object);
}
}
}
- req.open('GET', p_url, true);
+ var $ajax_mark = (p_url.indexOf('?') ? '&' : '?') + 'ajax=yes';
+ req.open('GET', p_url + $ajax_mark, true);
req.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');
req.send(null);
var toId = window.setTimeout( function() {if (p_busyReq) req.abort();}, DebugReq.timeout );
}
}
DebugReq.getRequest = function() {
var xmlHttp;
try { xmlHttp = new ActiveXObject('MSXML2.XMLHTTP'); return xmlHttp; } catch (e) {}
try { xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); return xmlHttp; } catch (e) {}
try { xmlHttp = new XMLHttpRequest(); return xmlHttp; } catch(e) {}
return null;
}
DebugReq.showProgress = function(p_id) {
$Debugger.AppendRow(DebugReq.getProgressHtml());
}
DebugReq.getProgressHtml = function() {
return 'Loading ...';
}
DebugReq.getErrorHtml = function(p_req) {
//TODO: implement accepted way to handle request error
return "<p>" + "(" + p_req.status + ") " + p_req.statusText + "</p>"
}
// Debugger
function Debugger($row_separator, $errors_count, $fatal_error, $sql_count) {
this.RowSeparator = $row_separator;
this.IsFatalError = $fatal_error;
this.ErrorsCount = parseInt($errors_count);
this.SQLCount = parseInt($sql_count);
this.IsQueried = false;
this.IsVisible = false;
this.DebuggerDIV = document.getElementById('debug_layer');
this.DebuggerTable = document.getElementById('debug_table');
this.RowCount = 0;
this.busyRequest = false;
this.DragObject = null;
this.LastDragObject = null;
this.MouseOffset = [0,0];
this.ResizeHappening = false;
this.ResizeTimer = null;
this.InitialPos = null;
// window.$Debugger = this; // this should be uncommented in case if debugger variable is not $Debugger
this.AddEvent(window, 'scroll', function (ev) { window.$Debugger.Resize(ev); });
this.AddEvent(window, 'resize', function (ev) { window.$Debugger.Resize(ev); });
// this.AddEvent(window, 'keydown', function (ev) { window.$Debugger.KeyDown(ev); }); // don't work in IE
document.onkeydown = function(ev) { window.$Debugger.KeyDown(ev); }
}
Debugger.prototype.SetOpacity = function(opacity)
{
this.DebuggerToolbar.style.opacity = (opacity / 100);
this.DebuggerToolbar.style.MozOpacity = (opacity / 100);
this.DebuggerToolbar.style.KhtmlOpacity = (opacity / 100);
this.DebuggerToolbar.style.filter = "alpha(opacity=" + opacity + ")";
}
Debugger.prototype.ToolbarClick = function ($button) {
switch ($button.id) {
case 'dbg_ReloadFrame':
self.location.reload();
break;
case 'dbg_ShowDebugger':
this.Toggle();
break;
}
}
Debugger.prototype.AddToolbar = function($var_name) {
var $span = document.createElement('SPAN');
$span.style.position = 'absolute';
$span.style.zIndex= 99;
$span.style.top = '0px';
$span.style.left = '0px';
$span.id = 'debug_toolbar_span';
document.body.style.textAlign = 'left';
var $toolbar_content = '<td class="dbg-button" id="dbg_ReloadFrame" onclick="' + $var_name + '.ToolbarClick(this);">Reload Frame</td>';
if (this.ErrorsCount > 0) {
$toolbar_content += '<td class="dbg-separator"></td><td class="dbg-button debug_error" style="font-weight: bold;" id="dbg_ShowDebugger" onclick="' + $var_name + '.ToolbarClick(this);">Show Debugger (' + this.ErrorsCount + ' errors)</td>';
}
else {
$toolbar_content += '<td class="dbg-button" id="dbg_ShowDebugger" onclick="' + $var_name + '.ToolbarClick(this);">Show Debugger</td>';
}
if (this.SQLCount > 0) {
$toolbar_content += '<td class="dbg-separator"></td><td style="cursor: move">' + this.SQLCount + ' sqls</td>';
}
$span.innerHTML = '<table style="height: 30px" cellpadding="0" cellspacing="3" class="dbg-toolbar"><tr>' + $toolbar_content + '</tr></table>';
this.DebuggerToolbar = $span;
this.SetOpacity(20);
$span.onmouseover = function() {
$Debugger.SetOpacity(100);
}
$span.onmouseout = function() {
$Debugger.SetOpacity(20);
}
var $body = document.getElementsByTagName('BODY')[0];
$body.insertBefore($span, $body.firstChild);
// alert($span.offsetWidth)
this.MakeDragable('debug_toolbar_span', function() {}, function() {}, function() {});
}
Debugger.prototype.AppendRow = function($html) {
this.RowCount++;
var $tr = document.createElement('TR');
this.DebuggerTable.appendChild($tr);
$tr.className = 'debug_row_' + (this.RowCount % 2 ? 'odd' : 'even');
$tr.id = 'debug_row_' + this.RowCount;
var $td = document.createElement('TD');
$td.className = 'debug_cell';
$td.innerHTML = $html;
$tr.appendChild($td);
}
Debugger.prototype.RemoveRow = function($row_index) {
this.DebuggerTable.deleteRow($row_index);
this.RowCount--;
}
Debugger.prototype.Clear = function() {
if (!this.IsQueried) return false;
this.IsQueried = false;
while (this.DebuggerTable.rows.length) {
this.RemoveRow(0);
}
}
Debugger.prototype.KeyDown = function($e) {
var $KeyCode = this.GetKeyCode($e);
if ($KeyCode == 123 || $KeyCode == 27) {// F12 or ESC
this.Toggle($KeyCode);
this.StopEvent($e);
}
}
Debugger.prototype.OpenDOMViewer = function() {
var $value = document.getElementById('dbg_domviewer').value;
DOMViewerObj = ($value.indexOf('"') != -1) ? document.getElementById( $value.substring(1,$value.length-1) ) : eval($value);
window.open(this.DOMViewerURL);
return false;
}
Debugger.prototype.GetKeyCode = function($e) {
$e = ($e) ? $e : event;
var target = ($e.target) ? $e.target : $e.scrElement;
var charCode = ($e.charCode) ? $e.charCode : (($e.which) ? $e.which : $e.keyCode);
return charCode;
}
Debugger.prototype.StopEvent = function($e) {
$e = ($e) ? $e : event;
$e.cancelBubble = true;
if ($e.stopPropagation) $e.stopPropagation();
}
Debugger.prototype.Toggle = function($KeyCode) {
if(!this.DebuggerDIV) return false;
this.IsVisible = this.DebuggerDIV.style.display == 'none' ? false : true;
if (!this.IsVisible && $KeyCode == 27) {
return false;
}
this.Resize(null);
if (!this.IsQueried) {
this.Query();
}
this.DebuggerDIV.style.display = this.IsVisible ? 'none' : 'block';
}
Debugger.prototype.Query = function() {
DebugReq.makeRequest(this.DebugURL, this.busyRequest, '', this.successCallback, this.errorCallback, '', this);
}
Debugger.prototype.successCallback = function(p_req, p_pass, p_object) {
+ if (p_pass == 'resetCache') {
+ alert('Requested action performed.');
+ return ;
+ }
+
var contents = p_req.responseText;
contents = contents.split(p_object.RowSeparator);
if (contents.length == 1) {
alert('error: '+p_req.responseText);
p_object.IsQueried = true;
return ;
}
for (var $i = 0; $i < contents.length - 1; $i++) {
p_object.AppendRow(contents[$i]);
}
p_object.Refresh();
}
Debugger.prototype.errorCallback = function(p_req, p_pass, p_object) {
alert('AJAX ERROR: '+DebugReq.getErrorHtml(p_req));
p_object.Refresh();
}
Debugger.prototype.Refresh = function() {
// progress mether row
this.RemoveRow(0);
this.IsQueried = true;
this.DebuggerDIV.scrollTop = this.IsFatalError ? 10000000 : 0;
this.DebuggerDIV.scrollLeft = 0;
}
Debugger.prototype.Resize = function($e) {
if (!this.DebuggerDIV) return false;
var $pageTop = document.all ? document.body.offsetTop + document.body.scrollTop : window.scrollY;
this.DebuggerDIV.style.top = $pageTop + 'px';
this.DebuggerDIV.style.height = GetWindowHeight() + 'px';
return true;
}
function GetWindowHeight() {
var currWinHeight;
// if (document.body.clientHeight) {
// currWinHeight = document.body.clientHeight;
if (window.innerHeight) {//FireFox with correction for status bar at bottom of window
currWinHeight = window.innerHeight;
} else if (document.documentElement.clientHeight) {//IE 7 with correction for address bar
currWinHeight = document.documentElement.clientHeight;
} else if (document.body.offsetHeight) {//IE 4+
currWinHeight = document.body.offsetHeight + 10;
}
return currWinHeight - 10; // 10 - horizontal scrollbar height
}
/*function GetWinHeight() {
if (window.innerHeight) return window.innerHeight;
else if (document.documentElement.clientHeight) return document.documentElement.clientHeight;
else if (document.body.offsetHeight) return document.body.offsetHeight;
else return _winHeight;
}*/
Debugger.prototype.SetClipboard = function(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);
}
}
Debugger.prototype.ShowProps = function($Obj, $Name) {
var $ret = '';
for ($Prop in $Obj) {
$ret += $Name + '.' + $Prop + ' = ' + $Obj[$Prop] + "\n";
}
return alert($ret);
}
Debugger.prototype.editFile = function($fileName, $lineNo) {
if (!document.all) {
alert('Only works in IE');
return;
}
if (!this.EditorPath) {
alert('Editor path not defined!');
return;
}
var $launch_object = new ActiveXObject('LaunchinIE.Launch');
var $editor_path = this.EditorPath;
$editor_path = $editor_path.replace('%F', $fileName);
$editor_path = $editor_path.replace('%L',$lineNo);
$launch_object.LaunchApplication($editor_path);
}
Debugger.prototype.ToggleTraceArgs = function($arguments_layer_id) {
var $arguments_layer = document.getElementById($arguments_layer_id);
$arguments_layer.style.display = ($arguments_layer.style.display == 'none') ? 'block' : 'none';
}
Debugger.prototype.AddEvent = function (el, evname, func) {
var $status = false;
if (document.all) {
$status = el.attachEvent('on' + evname, func);
} else {
$status = el.addEventListener(evname, func, true);
}
}
+Debugger.prototype.resetCache = function ($event_source) {
+ var $events = document.getElementById($event_source);
+ var $event = $events.options[$events.selectedIndex].value;
+
+ if (!$event) {
+ alert('Please select action to perform first!');
+ }
+ else if (confirm('Really perform "' + $events.options[$events.selectedIndex].innerHTML + '"?')) {
+ DebugReq.makeRequest(this.EventURL + '&' + $event, this.busyRequest, '', this.successCallback, this.errorCallback, 'resetCache', this);
+ }
+}
+
Debugger.prototype.mouseCoords = function(ev)
{
if(ev.pageX || ev.pageY){
var res = {x:ev.pageX, y:ev.pageY};
}
else {
var res = {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
return res;
}
Debugger.prototype.MakeDragable = function(object_id, startCallback, moveCallback, endCallback, options)
{
var drag_object = document.getElementById(object_id);
var cur_options = {'VerticalDrag': 1, 'HorizontalDrag': 1};
if (options) {
for(var i in options) {
cur_options[i] = options[i];
}
}
var the_debugger = this;
this.AddEvent(drag_object, 'mousedown', function(ev){
ev = ev || window.event;
the_debugger.InitialPos = dbg_findPos(drag_object);
var coords = the_debugger.mouseCoords(ev);
var pos = dbg_findPos(drag_object);
the_debugger.MouseOffset = [coords.x - pos[0], coords.y - pos[1]];
the_debugger.DragObject = drag_object;
the_debugger.LastDragObject = drag_object;
the_debugger.DragObject.style.position = 'absolute';
the_debugger.Options = cur_options;
startCallback(drag_object);
});
this.AddEvent(document, 'mousemove', function(ev) {
// window.status = 'mouse at: '+coords.x+','+coords.y;
if(the_debugger.DragObject){
ev = ev || window.event;
var coords = the_debugger.mouseCoords(ev);
if (the_debugger.Options.VerticalDrag) {
the_debugger.DragObject.style.top = (coords.y - the_debugger.MouseOffset[1] ) + 'px' // ;
}
if (the_debugger.Options.HorizontalDrag) {
the_debugger.DragObject.style.left = (coords.x - the_debugger.MouseOffset[0] ) + 'px' // ;
}
moveCallback(drag_object, coords)
return false;
}
});
this.AddEvent(document, 'mouseup', function(ev){
var tmp = the_debugger.DragObject;
the_debugger.DragObject = null;
if(tmp){
endCallback(tmp);
}
var pos = dbg_findPos(drag_object);
});
}
function dbg_findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft,curtop];
}
\ No newline at end of file
Property changes on: branches/RC/core/kernel/utility/debugger/debugger.js
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.13.2.4
\ No newline at end of property
+1.13.2.5
\ No newline at end of property
Index: branches/RC/core/kernel/utility/debugger.php
===================================================================
--- branches/RC/core/kernel/utility/debugger.php (revision 10576)
+++ branches/RC/core/kernel/utility/debugger.php (revision 10577)
@@ -1,1348 +1,1411 @@
<?php
if( !class_exists('Debugger') ) {
class Debugger {
/**
* Holds reference to global KernelApplication instance
*
* @access public
* @var kApplication
*/
var $Application = null;
/**
* Set to true if fatal error occured
*
* @var bool
*/
var $IsFatalError = false;
/**
* Debugger data for building report
*
* @var Array
*/
var $Data = Array();
var $ProfilerData = Array();
var $ProfilerTotals = Array();
var $ProfilerTotalCount = Array();
var $ProfilePoints = Array();
/**
* Prevent recursion when processing debug_backtrace() function results
*
* @var Array
*/
var $RecursionStack = Array();
var $scrollbarWidth = 0;
/**
* Long errors are saved here, because trigger_error doesn't support error messages over 1KB in size
*
* @var Array
*/
var $longErrors = Array();
var $IncludesData = Array();
var $IncludeLevel = 0;
var $reportDone = false;
/**
* Transparent spacer image used in case of none spacer image defined via SPACER_URL contant.
* Used while drawing progress bars (memory usage, time usage, etc.)
*
* @var string
*/
var $dummyImage = '';
/**
* Temporary files created by debugger will be stored here
*
* @var string
*/
var $tempFolder = '';
/**
* Debug rows will be separated using this string before writing to debug file
*
* @var string
*/
var $rowSeparator = '@@';
/**
* Base URL for debugger includes
*
* @var string
*/
var $baseURL = '';
function Debugger()
{
global $start, $dbg_options;
// check if user haven't defined DEBUG_MODE contant directly
if (defined('DEBUG_MODE') && DEBUG_MODE) {
die('error: contant DEBUG_MODE defined directly, please use <strong>$dbg_options</strong> array instead');
}
// check IP before enabling debug mode
$ip_match = $this->ipMatch(isset($dbg_options['DBG_IP']) ? $dbg_options['DBG_IP'] : '');
if (!$ip_match) {
define('DEBUG_MODE', 0);
return ;
}
// debug is allowed for user, continue initialization
$this->InitDebugger();
$this->profileStart('kernel4_startup', 'Startup and Initialization of kernel4', $start);
$this->profileStart('script_runtime', 'Script runtime', $start);
error_reporting(E_ALL);
ini_set('display_errors', $this->constOn('DBG_ZEND_PRESENT') ? 0 : 1); // show errors on screen in case if not in Zend Studio debugging
$this->scrollbarWidth = $this->isGecko() ? 22 : 25; // vertical scrollbar width differs in Firefox and other browsers
$this->appendRequest();
}
/**
* Checks, that user IP address is within allowed range
*
* @param string $ip_list semi-column (by default) separated ip address list
* @param string $separator ip address separator (default ";")
*
* @return bool
*/
function ipMatch($ip_list, $separator = ';')
{
$ip_match = false;
$ip_addresses = $ip_list ? explode($separator, $ip_list) : Array ();
foreach ($ip_addresses as $ip_address) {
if ($this->netMatch($ip_address, $_SERVER['REMOTE_ADDR'])) {
$ip_match = true;
break;
}
}
return $ip_match;
}
/**
* Set's default values to constants debugger uses
*
*/
function InitDebugger()
{
global $dbg_options;
unset($_REQUEST['debug_host'], $_REQUEST['debug_fastfile'], $dbg_options['DBG_IP']); // 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_') {
$this->safeDefine('DBG_ZEND_PRESENT', 1);
break;
}
}
$this->safeDefine('DBG_ZEND_PRESENT', 0); // set this constant value to 0 (zero) to debug debugger using Zend Studio
// set default values for debugger constants
$dbg_constMap = Array(
'DBG_USE_HIGHLIGHT' => 1, // highlight output same as php code using "highlight_string" function
'DBG_WINDOW_WIDTH' => 700, // set width of debugger window (in pixels) for better viewing large amount of debug data
'DBG_USE_SHUTDOWN_FUNC' => DBG_ZEND_PRESENT ? 0 : 1, // use shutdown function to include debugger code into output
'DBG_HANDLE_ERRORS' => DBG_ZEND_PRESENT ? 0 : 1, // handle all allowed by php (see php manual) errors instead of default handler
'DBG_IGNORE_STRICT_ERRORS' => 1, // ignore PHP5 errors about private/public view modified missing in class declarations
'DBG_DOMVIEWER' => '/temp/domviewer.html', // path to DOMViewer on website
'DOC_ROOT' => str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT']) ), // windows hack
'DBG_LOCAL_BASE_PATH' => 'w:', // replace DOC_ROOT in filenames (in errors) using this path
);
// only for IE, in case if no windows php script editor defined
if (!defined('DBG_EDITOR')) {
// $dbg_constMap['DBG_EDITOR'] = 'c:\Program Files\UltraEdit\uedit32.exe %F/%L';
$dbg_constMap['DBG_EDITOR'] = 'c:\Program Files\Zend\ZendStudio-5.2.0\bin\ZDE.exe %F';
}
if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] && constOn('DBG_SKIP_AJAX')) {
$this->safeDefine('DBG_SKIP_REPORTING', 1);
}
// user defined options override debugger defaults
$dbg_constMap = $this->array_merge_recursive2($dbg_constMap, $dbg_options);
// when validation configs, don't show sqls for better validation error displaying
if (array_key_exists('DBG_VALIDATE_CONFIGS', $dbg_constMap) && $dbg_constMap['DBG_VALIDATE_CONFIGS']) {
$dbg_constMap['DBG_SQL_PROFILE'] = 0;
}
// when showing explain make shure, that debugger window is large enough
if (array_key_exists('DBG_SQL_EXPLAIN', $dbg_constMap) && $dbg_constMap['DBG_SQL_EXPLAIN']) {
$dbg_constMap['DBG_WINDOW_WIDTH'] = 1000;
}
foreach ($dbg_constMap as $dbg_constName => $dbg_constValue) {
$this->safeDefine($dbg_constName, $dbg_constValue);
}
}
function constOn($const_name)
{
return defined($const_name) && constant($const_name);
}
function safeDefine($const_name, $const_value) {
if (!defined($const_name)) {
define($const_name, $const_value);
}
}
function array_merge_recursive2($paArray1, $paArray2)
{
if (!is_array($paArray1) or !is_array($paArray2)) {
return $paArray2;
}
foreach ($paArray2 AS $sKey2 => $sValue2) {
$paArray1[$sKey2] = isset($paArray1[$sKey2]) ? array_merge_recursive2($paArray1[$sKey2], $sValue2) : $sValue2;
}
return $paArray1;
}
function netMatch($network, $ip) {
$network = trim($network);
$ip = trim($ip);
if ($network == $ip) {
// comparing 2 ip addresses directly
return true;
}
$d = strpos($network, '-');
if ($d === false) {
// sigle subnet specified
$ip_arr = explode('/', $network);
if (!preg_match("@\d*\.\d*\.\d*\.\d*@", $ip_arr[0], $matches)) {
$ip_arr[0] .= '.0'; // Alternate form 194.1.4/24
}
$network_long = ip2long($ip_arr[0]);
$x = ip2long($ip_arr[1]);
$mask = long2ip($x) == $ip_arr[1] ? $x : (0xffffffff << (32 - $ip_arr[1]));
$ip_long = ip2long($ip);
return ($ip_long & $mask) == ($network_long & $mask);
}
else {
// ip address range specified
$from = ip2long(trim(substr($network, 0, $d)));
$to = ip2long(trim(substr($network, $d + 1)));
$ip = ip2long($ip);
return ($ip >= $from && $ip <= $to);
}
}
function InitReport()
{
if (!class_exists('kApplication')) return false;
$application =& kApplication::Instance();
// string used to separate debugger records while in file (used in debugger dump filename too)
$this->rowSeparator = '@'.(is_object($application->Factory) ? $application->GetSID() : 0).'@';
// include debugger files from this url
$reg_exp = '/^'.preg_quote(FULL_PATH, '/').'/';
$kernel_path = preg_replace($reg_exp, '', KERNEL_PATH, 1);
$this->baseURL = PROTOCOL.SERVER_NAME.rtrim(BASE_PATH, '/').$kernel_path.'/utility/debugger';
// save debug output in this folder
$this->tempFolder = defined('WRITEABLE') ? WRITEABLE.'/cache' : FULL_PATH.'/kernel/cache';
}
function mapLongError($msg)
{
$key = $this->generateID();
$this->longErrors[$key] = $msg;
return $key;
}
/**
* Appends all passed variable values (wihout variable names) to debug output
*
*/
function dumpVars()
{
$dump_mode = 'var_dump';
$dumpVars = func_get_args();
if ($dumpVars[count($dumpVars) - 1] === 'STRICT') {
$dump_mode = 'strict_var_dump';
array_pop($dumpVars);
}
foreach ($dumpVars as $varValue) {
$this->Data[] = Array('value' => $varValue, 'debug_type' => $dump_mode);
}
}
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( $this->print_r($Data['value'], true) );
break;
case 'strict_var_dump':
return $this->highlightString( var_export($Data['value'], true) );
break;
case 'trace':
ini_set('memory_limit', '500M');
$trace =& $Data['trace'];
$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:$Debugger.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';
}
if ($has_args) {
// if parameter value is longer then 200 symbols, then leave only first 50
$args = $this->highlightString($this->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();
$total_width = ($this->getWindowWidth() - 10);
$div_width['before'] = round(($total_before / $total) * $total_width);
$div_width['current'] = round(($runtime / $total) * $total_width);
$div_width['left'] = round((($total - $total_before - $runtime) / $total) * $total_width);
$ret = '<b>Name</b>: '.$Data['description'].'<br />';
$additional = isset($Data['additional']) ? $Data['additional'] : Array ();
if (isset($Data['file'])) {
array_unshift($additional, Array('name' => 'File', 'value' => $this->getFileLink($Data['file'], $Data['line'], basename($Data['file']).':'.$Data['line'])));
}
array_unshift($additional, Array('name' => 'Runtime', 'value' => $runtime.'s'));
foreach ($additional as $mixed_param) {
$ret .= '[<strong>'.$mixed_param['name'].'</strong>: '.$mixed_param['value'].'] ';
}
/*if (isset($Data['file'])) {
$ret .= '[<b>Runtime</b>: '.$runtime.'s] [<b>File</b>: '.$this->getFileLink($Data['file'], $Data['line'], basename($Data['file']).':'.$Data['line']).']<br />';
}
else {
$ret .= '<b>Runtime</b>: '.$runtime.'s<br />';
}*/
$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 - 8;
}
/**
* Tells debugger to skip objects that are heavy in plan of memory usage while printing debug_backtrace results
*
* @param Object $object
* @return bool
*/
function IsBigObject(&$object)
{
$skip_classes = Array(
defined('APPLICATION_CLASS') ? APPLICATION_CLASS : 'kApplication',
'kFactory',
'kUnitConfigReader',
'TemplateParser',
);
foreach ($skip_classes as $class_name) {
if (strtolower(get_class($object)) == strtolower($class_name)) {
return true;
}
}
return false;
}
/**
* Advanced version of print_r (for debugger only). Don't print objects recursively
*
* @param Array $array
* @param bool $return_output return output or print it out
* @param int $tab_count offset in tabs
* @return string
*/
function print_r(&$array, $return_output = false, $tab_count = -1)
{
static $first_line = true;
// not an array at all
if (!is_array($array)) {
switch (gettype($array)) {
case 'NULL':
return 'NULL'."\n";
break;
case 'object':
return $this->processObject($array, $tab_count);
break;
default:
// number or string
- if (mb_strlen($array) > 200) {
- $array = mb_substr($array, 0, 50).' ...';
+ if (strlen($array) > 200) {
+ $array = substr($array, 0, 50).' ...';
}
return $array."\n";
break;
}
}
$output = '';
$tab_count++;
$output .= "Array\n".str_repeat(' ', $tab_count)."(\n";
$tab_count++;
$tabsign = $tab_count ? str_repeat(' ', $tab_count) : '';
$array_keys = array_keys($array);
foreach ($array_keys as $key) {
switch (gettype($array[$key])) {
case 'array':
$output .= $tabsign.'['.$key.'] = '.$this->print_r($array[$key], true, $tab_count);
break;
case 'boolean':
$output .= $tabsign.'['.$key.'] = '.($array[$key] ? 'true' : 'false')."\n";
break;
case 'integer':
case 'double':
case 'string':
- if (mb_strlen($array[$key]) > 200) {
- $array[$key] = mb_substr($array[$key], 0, 50).' ...';
+ if (strlen($array[$key]) > 200) {
+ $array[$key] = substr($array[$key], 0, 50).' ...';
}
$output .= $tabsign.'['.$key.'] = '.$array[$key]."\n";
break;
case 'NULL':
$output .= $tabsign.'['.$key."] = NULL\n";
break;
case 'object':
$output .= $tabsign.'['.$key."] = ";
$output .= "Object (".get_class($array[$key]).") = \n".str_repeat(' ', $tab_count + 1)."(\n";
$output .= $this->processObject($array[$key], $tab_count + 2);
$output .= str_repeat(' ', $tab_count + 1).")\n";
break;
default:
$output .= $tabsign.'['.$key.'] unknown = '.gettype($array[$key])."\n";
break;
}
}
$tab_count--;
$output .= str_repeat(' ', $tab_count).")\n";
if ($first_line) {
$first_line = false;
$output .= "\n";
}
$tab_count--;
if ($return_output) {
return $output;
}
else {
echo $output;
}
return true;
}
function processObject(&$object, $tab_count)
{
$object_class = get_class($object);
if (!in_array($object_class, $this->RecursionStack)) {
if ($this->IsBigObject($object)) {
return 'SKIPPED (class: '.$object_class.")\n";
}
$attribute_names = get_class_vars($object_class);
if (!$attribute_names) {
return "NO_ATTRIBUTES\n";
}
else {
$output = '';
array_push($this->RecursionStack, $object_class);
$tabsign = $tab_count ? str_repeat(' ', $tab_count) : '';
foreach ($attribute_names as $attribute_name => $attribute_value) {
if (is_object($object->$attribute_name)) {
// it is object
$output .= $tabsign.'['.$attribute_name.'] = '.$this->processObject($object->$attribute_name, $tab_count + 1);
}
else {
$output .= $tabsign.'['.$attribute_name.'] = '.$this->print_r($object->$attribute_name, true, $tab_count);
}
}
array_pop($this->RecursionStack);
return $output;
}
}
else {
// object [in recursion stack]
return '*** RECURSION *** (class: '.$object_class.")\n";
}
}
/**
* Format SQL Query using predefined formatting
* and highlighting techniques
*
* @param string $sql
* @return string
*/
function formatSQL($sql)
{
$sql = trim( preg_replace('/(\n|\t| )+/is', ' ', $sql) );
$formatted_sql = preg_replace('/\s(CREATE TABLE|DROP TABLE|SELECT|UPDATE|SET|REPLACE|INSERT|DELETE|VALUES|FROM|LEFT JOIN|INNER JOIN|LIMIT|WHERE|HAVING|GROUP BY|ORDER BY)\s/is', "\n\t$1 ", ' ' . $sql);
$formatted_sql = $this->highlightString($formatted_sql);
if (defined('DBG_SQL_EXPLAIN') && DBG_SQL_EXPLAIN) {
if (substr($sql, 0, 6) == 'SELECT') {
$formatted_sql .= '<br/>' . '<strong>Explain</strong>:<br /><br />';
$explain_result = $this->Application->Conn->Query('EXPLAIN ' . $sql, null, true);
$explain_table = '';
foreach ($explain_result as $explain_row) {
if (!$explain_table) {
// first row -> draw header
$explain_table .= '<tr class="explain_header"><td>' . implode('</td><td>', array_keys($explain_row)) . '</td></tr>';
}
$explain_table .= '<tr><td>' . implode('</td><td>', $explain_row) . '</td></tr>';
}
$formatted_sql .= '<table class="dbg_explain_table">' . $explain_table . '</table>';
}
}
return $formatted_sql;
}
function highlightString($string)
{
if (!(defined('DBG_USE_HIGHLIGHT') && DBG_USE_HIGHLIGHT)) {
return $string;
}
$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;/Us', '\\2', $string);
}
/**
* Determine by php type of browser used to show debugger
*
* @return bool
*/
function isGecko()
{
// we need isset because we may run scripts from shell with no user_agent at all
- return isset($_SERVER['HTTP_USER_AGENT']) && mb_strpos(mb_strtolower($_SERVER['HTTP_USER_AGENT']), 'firefox') !== false;
+ return isset($_SERVER['HTTP_USER_AGENT']) && strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'firefox') !== false;
}
/**
* Returns link for editing php file (from error) in external editor
*
* @param string $file filename with path from root folder
* @param int $lineno line number in file where error is found
* @param string $title text to show on file edit link
* @return string
*/
function getFileLink($file, $lineno = 1, $title = '')
{
if (!$title) {
$title = str_replace('/', '\\', $this->getLocalFile($file));
}
if ($this->isGecko()) {
return '<a href="file://'.$this->getLocalFile($file).'">'.$title.'</a>';
}
else {
return '<a href="javascript:$Debugger.editFile(\''.$this->getLocalFile($file).'\', '.$lineno.');" title="'.$file.'">'.$title.'</a>';
}
}
/**
* Converts filepath on server to filepath in mapped DocumentRoot on developer pc
*
* @param string $remoteFile
* @return string
*/
function getLocalFile($remoteFile)
{
return preg_replace('/^'.preg_quote(DOC_ROOT, '/').'/', DBG_LOCAL_BASE_PATH, $remoteFile, 1);
}
/**
* Appends call trace till this method call
*
*/
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');
}
/**
* Appends HTML code whithout transformations
*
* @param string $html
*/
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>)');
if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] == 'yes') {
- $this->appendHTML('RequestURI: '.$_SERVER['REQUEST_URI'].' (QS Length:'.mb_strlen($_SERVER['QUERY_STRING']).')');
+ $this->appendHTML('RequestURI: '.$_SERVER['REQUEST_URI'].' (QS Length:'.strlen($_SERVER['QUERY_STRING']).')');
}
- $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 $Debugger.OpenDOMViewer();">Show</button>');
+
+ $tools_html = ' <table style="width: ' . $this->getWindowWidth() . 'px;">
+ <tr>
+ <td>' . $this->_getDomViewerHTML() . '</td>
+ <td>' . $this->_getToolsHTML() . '</td>
+ </tr>
+ </table>';
+ $this->appendHTML($tools_html);
ob_start();
?>
<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($this->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();
}
/**
* Appends php session content to debugger output
*
*/
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 = null)
{
if (!isset($timeStamp)) {
$timeStamp = $this->getMoment();
}
$this->ProfilerData[$key] = Array('begins' => $timeStamp, 'ends' => 5000, 'debuggerRowID' => count($this->Data));
if (isset($description)) {
$this->ProfilerData[$key]['description'] = $description;
}
if (substr($key, 0, 4) == 'sql_') {
// append place from what was called
$trace_results = debug_backtrace();
$trace_count = count($trace_results);
$i = 0;
while ($i < $trace_count) {
$trace_file = basename($trace_results[$i]['file']);
if ($trace_file != 'db_connection.php' && $trace_file != 'adodb.inc.php') {
break;
}
$i++;
}
$this->ProfilerData[$key]['file'] = $trace_results[$i]['file'];
$this->ProfilerData[$key]['line'] = $trace_results[$i]['line'];
unset($trace_results);
}
$this->Data[] = Array('profile_key' => $key, 'debug_type' => 'profiler');
}
function profileFinish($key, $description = null, $timeStamp = null)
{
if (!isset($timeStamp)) {
$timeStamp = $this->getMoment();
}
$this->ProfilerData[$key]['ends'] = $timeStamp;
if (isset($description)) {
$this->ProfilerData[$key]['description'] = $description;
}
if (substr($key, 0, 4) == 'sql_') {
$func_arguments = func_get_args();
$rows_affected = $func_arguments[3];
$additional = Array ();
if ($rows_affected > 0) {
$additional[] = Array ('name' => 'Affected Rows', 'value' => $rows_affected);
if (isset($func_arguments[4])) {
$additional[] = Array ('name' => 'Result', 'value' => $func_arguments[4]);
}
}
$additional[] = Array ('name' => 'Query Number', 'value' => $func_arguments[5]);
$this->ProfilerData[$key]['additional'] =& $additional;
}
}
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($error_code)
{
$error_map = Array(
'Fatal Error' => Array(E_USER_ERROR),
'Warning' => Array(E_WARNING, E_USER_WARNING),
'Notice' => Array(E_NOTICE, E_USER_NOTICE),
);
if (defined('E_STRICT')) {
$error_map['PHP5 Strict'] = Array(E_STRICT);
}
if (defined('E_RECOVERABLE_ERROR')) {
$error_map['Fatal Error (recoverable)'] = Array(E_RECOVERABLE_ERROR);
}
foreach ($error_map as $error_name => $error_codes) {
if (in_array($error_code, $error_codes)) {
return $error_name;
}
}
return '';
}
/**
* Returns profile total key (check against unexisting key too)
*
* @param string $key
* @return int
*/
function getProfilerTotal($key)
{
if (isset($this->ProfilerTotalCount[$key])) {
return (int)$this->ProfilerTotalCount[$key];
}
return 0;
}
function ProfilePoint($title, $level=1)
{
$trace_results = debug_backtrace();
$level = min($level,count($trace_results)-1);
do {
$point = $trace_results[$level];
$location = $point['file'].':'.$point['line'];
$level++;
$has_more = isset($trace_results[$level]);
} while ($has_more && $point['function'] == $trace_results[$level]['function'] );
if ($location == ':') {
echo '';
}
if (!isset($this->ProfilePoints[$title])) {
$this->ProfilePoints[$title] = array();
}
if (!isset($this->ProfilePoints[$title][$location])) {
$this->ProfilePoints[$title][$location] = 0;
}
$this->ProfilePoints[$title][$location]++;
}
/**
* Generates report
*
*/
function printReport($returnResult = false, $clean_output_buffer = true)
{
if ($this->reportDone) {
// don't print same report twice (in case if shutdown function used + compression + fatal error)
return '';
}
$this->profileFinish('script_runtime');
$this->breakOutofBuffering();
$debugger_start = memory_get_usage();
if (defined('SPACER_URL')) {
$this->dummyImage = SPACER_URL;
}
$this->InitReport(); // set parameters required by AJAX
// defined here, because user can define this contant while script is running, not event before debugger is started
$this->safeDefine('DBG_RAISE_ON_WARNINGS', 0);
$this->safeDefine('DBG_TOOLBAR_BUTTONS', 1);
$this->appendSession(); // show php session if any
// ensure, that 1st line of debug output always is this one:
$top_line = '<table cellspacing="0" cellpadding="0" style="width: '.$this->getWindowWidth().'px; margin: 0px;"><tr><td align="left" width="50%">[<a href="javascript:window.location.reload();">Reload Frame</a>] [<a href="javascript:$Debugger.Toggle(27);">Hide Debugger</a>]</td><td align="right" width="50%">[Current Time: <b>'.date('H:i:s').'</b>] [File Size: <b>#DBG_FILESIZE#</b>]</td></tr></table>';
$this->appendHTML($top_line);
$this->moveToBegin(1);
if (count($this->ProfilePoints)>0) {
foreach($this->ProfilePoints as $point => $locations) {
arsort($this->ProfilePoints[$point]);
}
$this->appendHTML($this->highlightString($this->print_r($this->ProfilePoints, true)));
/*foreach ($this->ProfilePoints as $point => $locations) {
foreach ($locations as $location => $occurences) {
}
}*/
}
if ($this->constOn('DBG_SQL_PROFILE') && isset($this->ProfilerTotals['sql'])) {
// sql query profiling was enabled -> show totals
$this->appendHTML('<b>SQL Total time:</b> '.$this->ProfilerTotals['sql'].' <b>Number of queries</b>: '.$this->ProfilerTotalCount['sql']);
}
if ($this->constOn('DBG_PROFILE_INCLUDES') && isset($this->ProfilerTotals['includes'])) {
// included file profiling was enabled -> show totals
$this->appendHTML('<b>Included Files Total time:</b> '.$this->ProfilerTotals['includes'].' Number of includes: '.$this->ProfilerTotalCount['includes']);
}
if ($this->constOn('DBG_PROFILE_MEMORY')) {
// detailed memory usage reporting by objects was enabled -> show totals
$this->appendHTML('<b>Memory used by Objects:</b> '.round($this->ProfilerTotals['objects'] / 1024, 2).'Kb');
}
if ($this->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 ($this->constOn('DBG_PROFILE_INCLUDES')) {
$this->appendHTML('<b>Included files statistics:</b>'.( $this->constOn('DBG_SORT_INCLUDES_MEM') ? ' (sorted by memory usage)':''));
$totals = Array( 'mem' => 0, 'time' => 0);
$totals_configs = Array( 'mem' => 0, 'time' => 0);
if (is_array($this->IncludesData['mem'])) {
if ( $this->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']));
}
}*/
$is_ajax = isset($_GET['ajax']) && $_GET['ajax'] == 'yes';
$skip_reporting = $this->constOn('DBG_SKIP_REPORTING') || $this->constOn('DBG_ZEND_PRESENT');
if (($is_ajax && !constOn('DBG_SKIP_AJAX')) || !$skip_reporting) {
$debug_file = $this->tempFolder.'/debug_'.$this->rowSeparator.'.txt';
if (file_exists($debug_file)) unlink($debug_file);
$i = 0;
$fp = fopen($debug_file, 'a');
$lineCount = count($this->Data);
while ($i < $lineCount) {
fwrite($fp, $this->prepareHTML($i).$this->rowSeparator);
$i++;
}
fclose($fp);
}
if ($skip_reporting) {
// let debugger write report and then don't output anything
$this->reportDone = true;
return '';
}
+ $application =& kApplication::Instance();
$dbg_path = str_replace(FULL_PATH, '', $this->tempFolder);
+
ob_start();
// the <script .. /script> and hidden div helps browser to break out of script tag or attribute esacped
// with " or ' in case fatal error (or user-error) occurs inside it in compiled template,
// otherwise it has no effect
?>
<div style="display: none" x='nothing'><script></script></div><html><body></body></html>
<script type="text/javascript" src="<?php echo $this->baseURL; ?>/debugger.js"></script>
<link rel="stylesheet" rev="stylesheet" href="<?php echo $this->baseURL; ?>/debugger.css" type="text/css" media="screen" />
<div id="debug_layer" class="debug_layer_container" style="display: none; width: <?php echo DBG_WINDOW_WIDTH; ?>px;">
<div class="debug_layer" style="width: <?php echo $this->getWindowWidth(); ?>px;">
<table width="100%" cellpadding="0" cellspacing="1" border="0" class="debug_layer_table" style="width: <?php echo $this->getWindowWidth(); ?>px;" align="left">
<tbody id="debug_table"></tbody>
</table>
</div>
</div>
<script type="text/javascript">
var $Debugger = new Debugger(<?php echo "'".$this->rowSeparator."', ".$this->getProfilerTotal('error_handling').', '.($this->IsFatalError ? 'true' : 'false').', '.$this->getProfilerTotal('sql'); ?>);
$Debugger.DOMViewerURL = '<?php echo constant('DBG_DOMVIEWER'); ?>';
$Debugger.EditorPath = '<?php echo defined('DBG_EDITOR') ? addslashes(DBG_EDITOR) : '' ?>';
$Debugger.DebugURL = '<?php echo $this->baseURL.'/debugger_responce.php?sid='.$this->rowSeparator.'&path='.urlencode($dbg_path); ?>';
-
+ $Debugger.EventURL = '<?php echo $application->HREF('dummy', '', Array ('pass' => 'm')); ?>';
<?php
if ($this->IsFatalError || DBG_RAISE_ON_WARNINGS) {
echo '$Debugger.Toggle();';
}
if (DBG_TOOLBAR_BUTTONS) {
echo '$Debugger.AddToolbar("$Debugger");';
}
?>
window.focus();
</script>
<?php
if (!isset($this->ProfilerTotals['error_handling'])) {
$memory_used = $debugger_start;
$this->ProfilerTotalCount['error_handling'] = 0;
}
else {
$memory_used = $debugger_start - $this->ProfilerTotals['error_handling'];
}
if ($returnResult) {
$ret = ob_get_contents();
if ($clean_output_buffer) {
ob_end_clean();
}
$ret .= $this->getShortReport($memory_used);
$this->reportDone = true;
return $ret;
}
else {
if (!$this->constOn('DBG_HIDE_FULL_REPORT')) {
$this->breakOutofBuffering();
}
elseif ($clean_output_buffer) {
ob_clean();
}
echo $this->getShortReport($memory_used);
$this->reportDone = true;
}
}
/**
* Format's memory usage report by debugger
*
* @return string
* @access private
*/
function getShortReport($memory_used)
{
if ($this->constOn('DBG_TOOLBAR_BUTTONS')) {
// we have sql & error count in toolbar, don't duplicate here
$info = Array(
'Script Runtime' => 'PROFILE:script_runtime',
'SQL\'s Runtime' => 'PROFILE_T:sql',
);
}
else {
// toolbar not visible, then show sql & error count too
$info = Array (
'Script Runtime' => 'PROFILE:script_runtime',
'SQL\'s Runtime' => 'PROFILE_T:sql',
'-' => 'SEP:-',
'Notice / Warning' => 'PROFILE_TC:error_handling',
'SQLs Count' => 'PROFILE_TC:sql',
);
}
$ret = '<tr><td>Application:</td><td><b>'.$this->formatSize($memory_used).'</b> ('.$memory_used.')</td></tr>';
foreach ($info as $title => $value_key) {
list ($record_type, $record_data) = explode(':', $value_key, 2);
switch ($record_type) {
case 'PROFILE': // profiler totals value
$Data =& $this->ProfilerData[$record_data];
$profile_time = ($Data['ends'] - $Data['begins']); // in seconds
$ret .= '<tr><td>'.$title.':</td><td><b>'.sprintf('%.5f', $profile_time).' s</b></td></tr>';
break;
case 'PROFILE_TC': // profile totals record count
$record_cell = '<td>';
if ($record_data == 'error_handling' && $this->ProfilerTotalCount[$record_data] > 0) {
$record_cell = '<td class="debug_error">';
}
$ret .= '<tr>'.$record_cell.$title.':</td>'.$record_cell.'<b>'.$this->ProfilerTotalCount[$record_data].'</b></td></tr>';
break;
case 'PROFILE_T': // profile total
$record_cell = '<td>';
$total = array_key_exists($record_data, $this->ProfilerTotals) ? $this->ProfilerTotals[$record_data] : 0;
$ret .= '<tr>'.$record_cell.$title.':</td>'.$record_cell.'<b>'.sprintf('%.5f', $total).' s</b></td></tr>';
break;
case 'SEP':
$ret .= '<tr><td colspan="2" style="height: 1px; background-color: #000000; padding: 0px;"><img src="'.$this->dummyImage.'" height="1" alt=""/></td></tr>';
break;
}
}
return '<br /><table class="dbg_stats_table"><tr><td style="border-color: #FFFFFF;"><table class="dbg_stats_table" align="left">'.$ret.'</table></td></tr></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 = '')
{
$this->ProfilerData['error_handling']['begins'] = memory_get_usage();
$errorType = $this->getErrorNameByCode($errno);
if (!$errorType) {
trigger_error('Unknown error type ['.$errno.']', E_USER_ERROR);
return false;
}
if ($this->constOn('DBG_IGNORE_STRICT_ERRORS') && defined('E_STRICT') && ($errno == E_STRICT)) return;
if (preg_match('/(.*)#([\d]+)$/', $errstr, $rets) ) {
// replace short message with long one (due triger_error limitations on message size)
$long_id = $rets[2];
$errstr = $this->longErrors[$long_id];
unset($this->longErrors[$long_id]);
}
- if (mb_strpos($errfile,'eval()\'d code') !== false) {
+ if (strpos($errfile,'eval()\'d code') !== false) {
$errstr = '[<b>EVAL</b>, line <b>'.$errline.'</b>]: '.$errstr;
$tmpStr = $errfile;
- $pos = mb_strpos($tmpStr,'(');
- $errfile = mb_substr($tmpStr, 0, $pos);
+ $pos = strpos($tmpStr,'(');
+ $errfile = substr($tmpStr, 0, $pos);
$pos++;
- $errline = mb_substr($tmpStr,$pos,mb_strpos($tmpStr,')',$pos)-$pos);
+ $errline = substr($tmpStr,$pos,strpos($tmpStr,')',$pos)-$pos);
}
$this->Data[] = Array('no' => $errno, 'str' => $errstr, 'file' => $errfile, 'line' => $errline, 'context' => $errcontext, 'debug_type' => 'error');
$this->ProfilerData['error_handling']['ends'] = memory_get_usage();
$this->profilerAddTotal('error_handling', 'error_handling');
if (substr($errorType, 0, 5) == 'Fatal') {
$this->IsFatalError = true;
// append debugger report to data in buffer & clean buffer afterwards
die( $this->breakOutofBuffering(false) . $this->printReport(true) );
}
}
function breakOutofBuffering($flush = true)
{
$buffer_content = Array();
while (ob_get_level()) {
$buffer_content[] = ob_get_clean();
}
$ret = implode('', array_reverse($buffer_content));
if ($flush) {
echo $ret;
flush();
}
return $ret;
}
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;
}
function printConstants($constants)
{
if (!is_array($constants)) {
$constants = explode(',', $constants);
}
$contant_tpl = '<tr><td>%s</td><td><b>%s</b></td></tr>';
$ret = '<table class="dbg_flat_table" style="width: '.$this->getWindowWidth().'px;">';
foreach ($constants as $constant_name) {
$ret .= sprintf($contant_tpl, $constant_name, constant($constant_name));
}
$ret .= '</table>';
$this->appendHTML($ret);
}
function AttachToApplication() {
if (!$this->constOn('DBG_HANDLE_ERRORS')) {
return true;
}
if (class_exists('kApplication')) {
restore_error_handler();
$this->Application =& kApplication::Instance();
$this->Application->Debugger =& $this;
$this->Application->errorHandlers[] = Array(&$this, 'saveError');
}
else {
set_error_handler(Array(&$this, 'saveError'));
}
}
+
+ /**
+ * Returns HTML for tools section
+ *
+ * @return string
+ */
+ function _getToolsHTML()
+ {
+ $html = '<table>
+ <tr>
+ <td>System Tools:</td>
+ <td>
+ <select id="reset_cache" style="border: 1px solid #000000;">
+ <option value=""></option>
+ <option value="events[adm][OnResetModRwCache]">Reset mod_rewrite Cache</option>
+ <option value="events[adm][OnResetCMSMenuCache]">Reset SMS Menu Cache</option>
+ <option value="events[adm][OnResetSections]">Reset Sections Cache</option>
+ <option value="events[adm][OnResetConfigsCache]">Reset Configs Cache</option>
+ <option value="events[adm][OnRebuildThemes]">Re-build Themes Files</option>
+ <option value="events[lang][OnReflectMultiLingualFields]">Re-build Multilanguage Fields</option>
+ </select>
+ </td>
+ <td>
+ <input type="button" class="button" onclick="$Debugger.resetCache(\'reset_cache\');" value="Go"/>
+ </td>
+ </tr>
+ </table>';
+
+ return $html;
+ }
+
+ /**
+ * Returns HTML for dom viewer section
+ *
+ * @return string
+ */
+ function _getDomViewerHTML()
+ {
+ $html = '<table>
+ <tr>
+ <td>
+ <a href="http://www.brainjar.com/dhtml/domviewer/" target="_blank">DomViewer</a>:
+ </td>
+ <td>
+ <input id="dbg_domviewer" type="text" value="window" style="border: 1px solid #000000;"/>
+ </td>
+ <td>
+ <button class="button" onclick="return $Debugger.OpenDOMViewer();">Show</button>
+ </td>
+ </tr>
+ </table>';
+
+ return $html;
+ }
}
if (!function_exists('memory_get_usage')) {
function memory_get_usage(){ return -1; }
}
if (!Debugger::constOn('DBG_ZEND_PRESENT')) {
$debugger = new Debugger();
}
if (Debugger::constOn('DBG_USE_SHUTDOWN_FUNC')) {
register_shutdown_function( Array(&$debugger, 'printReport') );
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/utility/debugger.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.76.2.5
\ No newline at end of property
+1.76.2.6
\ No newline at end of property
Index: branches/RC/core/units/admin/admin_events_handler.php
===================================================================
--- branches/RC/core/units/admin/admin_events_handler.php (revision 10576)
+++ branches/RC/core/units/admin/admin_events_handler.php (revision 10577)
@@ -1,493 +1,514 @@
<?php
class AdminEventsHandler extends kDBEventHandler {
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnSaveColumns' => array('self' => true),
'OnClosePopup' => array('self' => true),
'OnSaveSetting' => array('self' => true),
// export/import permissions is checked within events
'OnExportCSV' => Array('self' => true),
'OnGetCSV' => Array('self' => true),
'OnCSVImportBegin' => Array('self' => true),
'OnCSVImportStep' => Array('self' => true),
'OnDropTempTablesByWID' => array('self' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Checks permissions of user
*
* @param kEvent $event
*/
function CheckPermission(&$event)
{
$system_events = Array (
'OnResetModRwCache', 'OnResetCMSMenuCache', 'OnResetSections',
'OnResetConfigsCache', 'OnCompileTemplates', 'OnGenerateTableStructure',
'OnRebuildThemes', 'OnCheckPrefixConfig',
);
if ($this->Application->isDebugMode(false) && in_array($event->Name, $system_events)) {
return true;
}
return parent::CheckPermission($event);
}
+ /**
+ * Enter description here...
+ *
+ * @param kEvent $event
+ */
function OnResetModRwCache(&$event)
{
+ if ($this->Application->GetVar('ajax') == 'yes') {
+ $event->status = erSTOP;
+ }
$this->Conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName LIKE "mod_rw%"');
}
function OnResetCMSMenuCache(&$event)
{
+ if ($this->Application->GetVar('ajax') == 'yes') {
+ $event->status = erSTOP;
+ }
$this->Conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = "cms_menu"');
}
function OnResetSections(&$event)
{
+ if ($this->Application->GetVar('ajax') == 'yes') {
+ $event->status = erSTOP;
+ }
$this->Conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = "sections_parsed"');
}
function OnResetConfigsCache(&$event)
{
+ if ($this->Application->GetVar('ajax') == 'yes') {
+ $event->status = erSTOP;
+ }
$this->Conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = "config_files" OR VarName = "configs_parsed" OR VarName = "sections_parsed"');
}
function OnCompileTemplates(&$event)
{
$compiler =& $this->Application->recallObject('NParserCompiler');
/* @var $compiler NParserCompiler */
$compiler->CompileTemplatesStep();
$event->status = erSTOP;
}
/**
* Generates sturcture for specified table
*
* @param kEvent $event
* @author Alex
*/
function OnGenerateTableStructure(&$event)
{
$types_hash = Array(
'string' => 'varchar|text|mediumtext|longtext|date|datetime|time|timestamp|char|year|enum|set',
'int' => 'smallint|mediumint|int|bigint|tinyint',
'float' => 'float|double|decimal',
);
$table_name = $this->Application->GetVar('table_name');
if (!$table_name) {
echo 'error: no table name specified';
return ;
}
if (TABLE_PREFIX && !preg_match('/^'.preg_quote(TABLE_PREFIX, '/').'(.*)/', $table_name)) {
// table name without prefix, then add it
$table_name = TABLE_PREFIX.$table_name;
}
if (!$this->Conn->TableFound($table_name)) {
// table with prefix doesn't exist, assume that just config prefix passed -> resolve table name from it
$table_name = $this->Application->getUnitOption(substr($table_name, strlen(TABLE_PREFIX)), 'TableName');
}
$table_info = $this->Conn->Query('DESCRIBE '.$table_name);
// 1. prepare config keys
$id_field = '';
$fields = Array();
$float_types = Array ('float', 'double', 'numeric');
foreach ($table_info as $field_info) {
if (preg_match('/l[\d]+_.*/', $field_info['Field'])) {
// don't put multilingual fields in config
continue;
}
$field_options = Array ();
// 1. get php field type by mysql field type
foreach ($types_hash as $php_type => $db_types) {
if (preg_match('/'.$db_types.'/', $field_info['Type'])) {
$field_options['type'] = $php_type;
break;
}
}
$default_value = $field_info['Default'];
if (in_array($php_type, $float_types)) {
// this is float number
if (preg_match('/'.$db_types.'\([\d]+,([\d]+)\)/i', $field_info['Type'], $regs)) {
// size is described in structure -> add formatter
$field_options['formatter'] = 'kFormatter';
$field_options['format'] = '%01.'.$regs[1].'f';
if ($field_info['Null'] != 'YES') {
// null fields, will most likely have NULL as default value
$default_value = 0;
}
}
else {
// no size information, just convert to float
if ($field_info['Null'] != 'YES') {
// null fields, will most likely have NULL as default value
$default_value = (float)$default_value;
}
}
}
if (preg_match('/varchar\(([\d]+)\)/i', $field_info['Type'], $regs)) {
$field_options['max_len'] = (int)$regs[1];
}
if ($field_info['Null'] != 'YES') {
$field_options['not_null'] = 1;
}
if ($field_info['Key'] == 'PRI') {
$default_value = 0;
$id_field = $field_info['Field'];
}
if ($php_type == 'int' && ($field_info['Null'] != 'YES' || is_numeric($default_value))) {
// is integer field AND not null
$field_options['default'] = (int)$default_value;
}
else {
$field_options['default'] = $default_value;
}
$fields[ $field_info['Field'] ] = $this->transformDump($field_options);
}
$ret = stripslashes(var_export($fields, true));
$ret = preg_replace("/'(.*?)' => 'Array \((.*?), \)',/", "'\\1' => Array (\\2),", $ret);
$ret = preg_replace("/\n '/", "\n\t'", $ret);
$ret = "'IDField' => '".$id_field."',\n'Fields' => A".substr($ret, 1).',';
ob_start();
?>
<html>
<head>
<title>Table "<?php echo $table_name; ?>" Structure</title>
</head>
<body bgcolor="#E7E7E7">
<a href="javascript:window.close();">Close Window</a><br />
<?php echo $GLOBALS['debugger']->highlightString($ret); ?>
<br /><a href="javascript:window.close();">Close Window</a><br />
</body>
</html>
<?php
echo ob_get_clean();
$event->status = erSTOP;
}
function transformDump($dump)
{
if (is_array($dump)) {
$dump = var_export($dump, true);
}
$dump = preg_replace("/,\n[ ]*/", ', ', $dump);
$dump = preg_replace("/array \(\n[ ]*/", 'Array (', $dump); // replace array start
$dump = preg_replace("/,\n[ ]*\),/", "),", $dump); // replace array end
return $dump;
}
/**
* Refreshes ThemeFiles & Theme tables by actual content on HDD
*
* @param kEvent $event
*/
function OnRebuildThemes(&$event)
{
+ if ($this->Application->GetVar('ajax') == 'yes') {
+ $event->status = erSTOP;
+ }
+
$themes_helper =& $this->Application->recallObject('ThemesHelper');
/* @var $themes_helper kThemesHelper */
$themes_helper->refreshThemes();
}
function OnSaveColumns(&$event)
{
$picker_helper =& $this->Application->recallObject('ColumnPickerHelper');
/* @var $picker_helper kColumnPickerHelper */
$picker_helper->SetGridName($this->Application->GetLinkedVar('grid_name'));
$picked = trim($this->Application->GetVar('picked_str'), '|');
$hidden = trim($this->Application->GetVar('hidden_str'), '|');
$main_prefix = $this->Application->GetVar('main_prefix');
$picker_helper->SaveColumns($main_prefix, $picked, $hidden);
$this->finalizePopup($event);
}
/**
* Saves various admin settings via ajax
*
* @param kEvent $event
*/
function OnSaveSetting(&$event)
{
if ($this->Application->GetVar('ajax') != 'yes') {
return ;
}
$var_name = $this->Application->GetVar('var_name');
$var_value = $this->Application->GetVar('var_value');
$this->Application->StorePersistentVar($var_name, $var_value);
$event->status = erSTOP;
}
/**
* Just closes popup & deletes last_template & opener_stack if popup, that is closing
*
* @param kEvent $event
*/
function OnClosePopup(&$event)
{
$event->SetRedirectParam('opener', 'u');
}
/**
* Occurs right after initialization of the kernel, used mainly as hook-to event
*
* @param kEvent $event
*/
function OnStartup(&$event)
{
}
/**
* Occurs right before echoing the output, in Done method of application, used mainly as hook-to event
*
* @param kEvent $event
*/
function OnBeforeShutdown(&$event)
{
}
/**
* Is called after tree was build (when not from cache)
*
* @param kEvent $event
*/
function OnAfterBuildTree(&$event)
{
}
/**
* Called by AJAX to perform CSV export
*
* @param kEvent $event
*/
function OnExportCSV(&$event)
{
$export_helper =& $this->Application->recallObject('CSVHelper');
/* @var $export_helper kCSVHelper */
$prefix_special = $this->Application->GetVar('PrefixSpecial');
if(!$prefix_special) {
$prefix_special = $export_helper->ExportData('prefix');
}
$prefix_elems = split('\.|_', $prefix_special, 2);
$perm_sections = $this->Application->getUnitOption($prefix_elems[0], 'PermSection');
if(!$this->Application->CheckPermission($perm_sections['main'].'.view')) {
$this->Application->Redirect('no_permission');
}
$export_helper->PrefixSpecial = $prefix_special;
$export_helper->grid = $this->Application->GetVar('grid');
$export_helper->ExportStep();
$event->status = erSTOP;
}
/**
* Returning created by AJAX CSV file
*
* @param kEvent $event
*/
function OnGetCSV(&$event)
{
$export_helper =& $this->Application->recallObject('CSVHelper');
/* @var $export_helper kCSVHelper */
$prefix_special = $export_helper->ExportData('prefix');
$prefix_elems = split('\.|_', $prefix_special, 2);
$perm_sections = $this->Application->getUnitOption($prefix_elems[0], 'PermSection');
if(!$this->Application->CheckPermission($perm_sections['main'].'.view')) {
$this->Application->Redirect('no_permission');
}
$export_helper->GetCSV();
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnCSVImportBegin(&$event)
{
$prefix_special = $this->Application->GetVar('PrefixSpecial');
$prefix_elems = split('\.|_', $prefix_special, 2);
$perm_sections = $this->Application->getUnitOption($prefix_elems[0], 'PermSection');
if(!$this->Application->CheckPermission($perm_sections['main'].'.add') && !$this->Application->CheckPermission($perm_sections['main'].'.edit')) {
$this->Application->Redirect('no_permission');
}
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object kDBItem */
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
$field_values = array_shift($items_info);
$object->SetFieldsFromHash($field_values);
$event->redirect = false;
$result = 'required';
if($object->GetDBField('ImportFile')) {
$import_helper =& $this->Application->recallObject('CSVHelper');
/* @var $import_helper kCSVHelper */
$import_helper->PrefixSpecial = $this->Application->GetVar('PrefixSpecial');
$import_helper->grid = $this->Application->GetVar('grid');
$result = $import_helper->ImportStart( $object->GetField('ImportFile', 'file_paths') );
if($result === true) {
$event->redirect = $this->Application->GetVar('next_template');
$event->SetRedirectParam('PrefixSpecial', $this->Application->GetVar('PrefixSpecial'));
$event->SetRedirectParam('grid', $this->Application->GetVar('grid'));
}
}
if($event->redirect === false) {
$object->SetError('ImportFile', $result);
$event->status = erFAIL;
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnCSVImportStep(&$event)
{
$import_helper =& $this->Application->recallObject('CSVHelper');
/* @var $export_helper kCSVHelper */
$prefix_special = $import_helper->ImportData('prefix');
$prefix_elems = split('\.|_', $prefix_special, 2);
$perm_sections = $this->Application->getUnitOption($prefix_elems[0], 'PermSection');
if(!$this->Application->CheckPermission($perm_sections['main'].'.add') && !$this->Application->CheckPermission($perm_sections['main'].'.edit')) {
$this->Application->Redirect('no_permission');
}
$import_helper->ImportStep();
$event->status = erSTOP;
}
/**
* Shows unit config filename, where requested prefix is defined
*
* @param kEvent $event
*/
function OnCheckPrefixConfig(&$event)
{
$prefix = $this->Application->GetVar('config_prefix');
$config_file = $this->Application->UnitConfigReader->prefixFiles[$prefix];
ob_start();
?>
<html>
<head>
<title>Unit Config of "<?php echo $prefix; ?>" prefix</title>
</head>
<body bgcolor="#E7E7E7">
<a href="javascript:window.close();">Close Window</a><br /><br />
<strong>Prefix:</strong> <?php echo $prefix; ?><br />
<strong>Unit Config:</strong> <?php echo $GLOBALS['debugger']->highlightString($config_file); ?><br />
<br /><a href="javascript:window.close();">Close Window</a><br />
</body>
</html>
<?php
echo ob_get_clean();
$event->status = erSTOP;
}
function OnUploadFile(&$event)
{
// Flash uploader does NOT send correct cookies, so we need to make our own check
$cookie_name = 'adm_'.$this->Application->ConfigValue('SessionCookieName');
$this->Application->HttpQuery->Cookie['cookies_on'] = 1;
$this->Application->HttpQuery->Cookie[$cookie_name] = $this->Application->GetVar('flashsid');
$admin_ses =& $this->Application->recallObject('Session.admin');
/* @var $admin_ses Session */
$user = $admin_ses->RecallVar('user_id');
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
/*if() {
$prefix_special = $this->Application->GetVar('PrefixSpecial');
$prefix_elems = split('\.|_', $prefix_special, 2);
$perm_sections = $this->Application->getUnitOption($prefix_elems[0], 'PermSection');
$section = $perm_sections['main'];
}
else {*/
$section = $event->getSection();
/*}*/
if ($this->Application->GetVar('t') != 'import/import_start' && !$perm_helper->CheckUserPermission($user, $section.'.add') && !$perm_helper->CheckUserPermission($user, $section.'.edit')) {
$event->status = erPERM_FAIL;
header('HTTP/1.0 403 You don\'t have permissions to upload');
exit;
return;
}
if (!$cookie_name) $cookie_name = 'sid';
$value = $this->Application->GetVar('Filedata');
if (!$value) return ;
$tmp_path = WRITEABLE.'/tmp/';
$fname = $value['name'];
$id = $this->Application->GetVar('id');
if ($id) $fname = $id.'_'.$fname;
if (!is_writable($tmp_path)) {
header('HTTP/1.0 500 Write permissions not set on the server');
exit;
}
move_uploaded_file($value['tmp_name'], $tmp_path.$fname);
exit;
}
function OnDropTempTablesByWID(&$event)
{
$sid = $this->Application->GetSID();
$wid = $this->Application->GetVar('m_wid');
$tables = $this->Conn->GetCol('SHOW TABLES');
$mask_edit_table = '/'.TABLE_PREFIX.'ses_'.$sid.'_'.$wid.'_edit_(.*)$/';
foreach($tables as $table)
{
if( preg_match($mask_edit_table,$table,$rets) )
{
$this->Conn->Query('DROP TABLE IF EXISTS '.$table);
}
}
echo 'OK';
$event->status = erSTOP;
return ;
}
}
\ No newline at end of file
Property changes on: branches/RC/core/units/admin/admin_events_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.8.2.12
\ No newline at end of property
+1.8.2.13
\ No newline at end of property
Index: branches/RC/core/units/languages/languages_event_handler.php
===================================================================
--- branches/RC/core/units/languages/languages_event_handler.php (revision 10576)
+++ branches/RC/core/units/languages/languages_event_handler.php (revision 10577)
@@ -1,479 +1,484 @@
<?php
class LanguagesEventHandler extends kDBEventHandler
{
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnChangeLanguage' => Array('self' => true),
'OnSetPrimary' => Array('self' => 'advanced:set_primary|add|edit'),
'OnImportLanguage' => Array('self' => 'advanced:import'),
'OnImportProgress' => Array('self' => 'advanced:import'),
'OnExportLanguage' => Array('self' => 'advanced:export'),
'OnExportProgress' => Array('self' => 'advanced:export'),
+ 'OnReflectMultiLingualFields' => Array ('self' => 'view'),
'OnItemBuild' => Array('self' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* [HOOK] Updates table structure on new language adding/removing language
*
* @param kEvent $event
*/
function OnReflectMultiLingualFields(&$event)
{
+ if ($this->Application->GetVar('ajax') == 'yes') {
+ $event->status = erSTOP;
+ }
+
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$this->Application->UnitConfigReader->ReReadConfigs();
foreach ($this->Application->UnitConfigReader->configData as $prefix => $config_data) {
$ml_helper->createFields($prefix);
}
}
/**
* Allows to set selected language as primary
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$this->StoreSelectedIDs($event);
$ids = $this->getSelectedIDs($event);
if ($ids) {
$id = array_shift($ids);
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object LanguagesItem */
$object->Load($id);
$object->setPrimary();
}
}
/**
* [HOOK] Reset primary status of other languages if we are saving primary language
*
* @param kEvent $event
*/
function OnUpdatePrimary(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object LanguagesItem */
$object->SwitchToLive();
// set primary for each languages, that have this checkbox checked
$ids = explode(',', $event->MasterEvent->getEventParam('ids'));
foreach ($ids as $id) {
$object->Load($id);
if ($object->GetDBField('PrimaryLang')) {
$object->setPrimary(true, false);
}
if ($object->GetDBField('AdminInterfaceLang')) {
$object->setPrimary(true, true);
}
}
// if no primary language left, then set primary last language (not to load again) from edited list
$sql = 'SELECT '.$object->IDField.'
FROM '.$object->TableName.'
WHERE PrimaryLang = 1';
$primary_language = $this->Conn->GetOne($sql);
if (!$primary_language) {
$object->setPrimary(false, false); // set primary language
}
$sql = 'SELECT '.$object->IDField.'
FROM '.$object->TableName.'
WHERE AdminInterfaceLang = 1';
$primary_language = $this->Conn->GetOne($sql);
if (!$primary_language) {
$object->setPrimary(false, true); // set admin interface language
}
}
/**
* Occurse before updating item
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemUpdate(&$event)
{
$object =& $event->getObject();
$status_field = array_shift( $this->Application->getUnitOption($event->Prefix, 'StatusField') );
if ($object->GetDBField('PrimaryLang') == 1 && $object->GetDBField($status_field) == 0) {
$object->SetDBField($status_field, 1);
}
}
/**
* Shows only enabled languages on front
*
* @param kEvent $event
*/
function SetCustomQuery(&$event)
{
if($event->Special == 'enabled')
{
$object =& $event->getObject();
$object->addFilter('enabled_filter', '%1$s.Enabled = 1');
}
}
/**
* Copy labels from another language
*
* @param kEvent $event
*/
function OnCopyLabels(&$event)
{
$object =& $event->getObject();
$from_lang_id = $object->GetDBField('CopyFromLanguage');
if( ($event->MasterEvent->status == erSUCCESS) && $object->GetDBField('CopyLabels') == 1 && ($from_lang_id > 0) )
{
$lang_id = $object->GetID();
// 1. phrases import
$phrases_live = $this->Application->getUnitOption('phrases','TableName');
$phrases_temp = $this->Application->GetTempName($phrases_live, 'prefix:phrases');
$sql = 'INSERT INTO '.$phrases_temp.'
SELECT Phrase, Translation, PhraseType, 0-PhraseId, '.$lang_id.', '.adodb_mktime().', "", Module
FROM '.$phrases_live.'
WHERE LanguageId='.$from_lang_id;
$this->Conn->Query($sql);
// 2. events import
$em_table_live = $this->Application->getUnitOption('emailmessages','TableName');
$em_table_temp = $this->Application->GetTempName($em_table_live, 'prefix:emailmessages');
$sql = 'SELECT * FROM '.$em_table_live.' WHERE LanguageId = '.$from_lang_id;
$email_messages = $this->Conn->Query($sql);
if($email_messages)
{
$id = $this->Conn->GetOne('SELECT MIN(EmailMessageId) FROM '.$em_table_live);
if($id > 0) $id = 0;
$id--;
$sqls = Array();
foreach($email_messages as $email_message)
{
$sqls[] = $id.','.$this->Conn->qstr($email_message['Template']).','.$this->Conn->qstr($email_message['MessageType']).','.$lang_id.','.$email_message['EventId'];
$id--;
}
$sql = 'INSERT INTO '.$em_table_temp.'(EmailMessageId,Template,MessageType,LanguageId,EventId) VALUES ('.implode('),(',$sqls).')';
$this->Conn->Query($sql);
}
$object->SetDBField('CopyLabels', 0);
}
}
/**
* Prepare temp tables for creating new item
* but does not create it. Actual create is
* done in OnPreSaveCreated
*
* @param kEvent $event
*/
function OnPreCreate(&$event)
{
parent::OnPreCreate($event);
$object =& $event->getObject();
$object->SetDBField('CopyLabels', 1);
$live_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$primary_lang_id = $this->Conn->GetOne('SELECT '.$object->IDField.' FROM '.$live_table.' WHERE PrimaryLang = 1');
$object->SetDBField('CopyFromLanguage', $primary_lang_id);
}
function OnChangeLanguage(&$event)
{
$this->Application->SetVar('m_lang', $this->Application->GetVar('language'));
//$this->Application->LinkVar('language', 'm_lang');
}
/**
* Parse language XML file into temp tables and redirect to progress bar screen
*
* @param kEvent $event
*/
function OnImportLanguage(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$items_info = $this->Application->GetVar('phrases_import');
if($items_info)
{
list($id,$field_values) = each($items_info);
$object =& $this->Application->recallObject('phrases.import', 'phrases', Array('skip_autoload' => true) );
$object->SetFieldsFromHash($field_values);
$filename = getArrayValue($field_values, 'LangFile', 'tmp_name');
if( filesize($filename) )
{
$modules = getArrayValue($field_values,'Module');
$lang_xml =& $this->Application->recallObject('LangXML');
/* @var $lang_xml LangXML_Parser */
$lang_xml->Parse($filename, $field_values['PhraseType'], $modules, $field_values['ImportOverwrite']);
$event->redirect = true;
$event->SetRedirectParams( Array('lang_event' => 'OnImportProgress', 'pass' => 'all,lang', 'mode'=>$field_values['ImportOverwrite']) );
}
else
{
$object =& $this->Application->recallObject('phrases.import');
$object->SetError('LangFile', 'la_empty_file', 'la_EmptyFile');
$event->redirect = false;
}
}
}
/**
* Copies imported from xml file from temp table to live table
*
* @param kEvent $event
*/
function OnImportProgress(&$event)
{
define('IMPORT_BY', 300); // import this much records per step
$template_name = 'regional/languages_import_step2';
$import_mode = (int)$this->Application->GetVar('mode'); // 1 - overwrite existing phrases, 0 - don't overwrite existing phrases
$import_source = (int)$this->Application->GetVar('source');
$import_steps = Array(0 => 'lang', 1 => 'phrases', 2 => 'emailmessages', 3 => 'finish');
$key_fields = Array(0 => 'PackName', 1 => 'Phrase', 2 => 'EventId'); // by what field should we search record match
$import_titles = Array(0 => 'la_ImportingLanguages', 1 => 'la_ImportingPhrases', 2 => 'la_ImportingEmailEvents', 3 => 'la_Done');
// --- BEFORE ---
$import_prefix = $import_steps[$import_source];
$import_start = (int)$this->Application->GetVar('start');
$id_field = $this->Application->getUnitOption($import_prefix,'IDField');
$dst_table = $this->Application->getUnitOption($import_prefix,'TableName');
$src_table = $this->Application->GetTempName($dst_table);
$import_total = $this->Application->GetVar('total');
if(!$import_total) $import_total = $this->Conn->GetOne('SELECT COUNT(*) FROM '.$src_table);
// --- AFTER ---
if($import_start == $import_total)
{
$import_source++;
$import_prefix = $import_steps[$import_source];
if($import_prefix == 'finish')
{
$event->SetRedirectParam('opener','u');
return true;
}
$import_start = 0;
$id_field = $this->Application->getUnitOption($import_prefix,'IDField');
$dst_table = $this->Application->getUnitOption($import_prefix,'TableName');
$src_table = $this->Application->GetTempName($dst_table);
$import_total = $this->Conn->GetOne('SELECT COUNT(*) FROM '.$src_table);
}
if($import_total > 0)
{
$done_percent = ($import_start * 100) / $import_total;
}
else
{
$done_percent = 100;
}
$block_params = Array( 'name' => $template_name,
'title' => $import_titles[$import_source],
'percent_done' => $done_percent,
'percent_left' => 100 - $done_percent);
$this->Application->InitParser();
$this->Application->setUnitOption('phrases','AutoLoad',false);
echo $this->Application->ParseBlock($block_params);
//break out of buffering
$buffer_content = Array();
while (ob_get_level()) {
$buffer_content[] = ob_get_clean();
}
$ret = implode('', array_reverse($buffer_content));
echo $ret;
flush();
$sql = 'SELECT * FROM %s LIMIT %s,%s';
$rows = $this->Conn->Query( sprintf($sql,$src_table,$import_start,IMPORT_BY) );
$values_sql = '';
// if found and mode = 1 (overwrite)
$search_sql = 'SELECT '.$id_field.' FROM '.$dst_table.' WHERE '.$key_fields[$import_source].' = %s AND LanguageId = %s';
$update_sql = 'UPDATE '.$dst_table.' SET %s WHERE '.$id_field.' = %s';
foreach($rows as $row)
{
$tmp_sql = sprintf($search_sql, $this->Conn->qstr($row[ $key_fields[$import_source] ]), $row['LanguageId'] );
$tmp_id = $this->Conn->GetOne($tmp_sql);
if($tmp_id > 0 && $import_mode == 1)
{
// update
$update_fields = '';
foreach($row as $field_name => $field_value)
{
if($field_name == $id_field) continue;
$update_fields .= '`'.$field_name.'` = '.$this->Conn->qstr($field_value).',';
}
$update_fields = preg_replace('/(.*),$/', '\\1', $update_fields);
$this->Conn->Query( sprintf($update_sql, $update_fields, $tmp_id) );
}
elseif(!$tmp_id)
{
$values_sql .= '(';
foreach($row as $field_value)
{
$values_sql .= $this->Conn->qstr($field_value).',';
}
$values_sql = preg_replace('/(.*),$/', '\\1', $values_sql).'),';
}
}
if($values_sql)
{
$fields_sql = '';
$fields = array_keys( $this->Application->getUnitOption($import_prefix,'Fields') );
foreach($fields as $field_name)
{
$fields_sql .= '`'.$field_name.'`,';
}
$fields_sql = preg_replace('/(.*),$/', '\\1', $fields_sql);
$values_sql = preg_replace('/(.*),$/', '\\1', $values_sql);
$sql = sprintf('INSERT INTO %s (%s) VALUES %s', $dst_table, $fields_sql, $values_sql);
$this->Conn->Query($sql);
}
$event->setRedirectParams( Array('lang_event' => 'OnImportProgress', 'pass' => 'all,lang', 'start' => $import_start += count($rows), 'total' => $import_total, 'source' => $import_source, 'mode' => $import_mode) );
}
/**
* Stores ids of selected languages and redirects to export language step 1
*
* @param kEvent $event
*/
function OnExportLanguage(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$this->Application->setUnitOption('phrases','AutoLoad',false);
$this->StoreSelectedIDs($event);
$this->Application->StoreVar('export_language_ids', implode(',', $this->getSelectedIDs($event)) );
$event->setRedirectParams( Array('m_opener'=>'d','phrases.export_event'=>'OnNew','pass'=>'all,phrases.export') );
$event->redirect = 'regional/languages_export';
}
/**
* Saves selected languages to xml file passed
*
* @param kEvent $event
*/
function OnExportProgress(&$event)
{
$items_info = $this->Application->GetVar('phrases_export');
if($items_info)
{
list($id,$field_values) = each($items_info);
$object =& $this->Application->recallObject('phrases.export', 'phrases', Array('skip_autoload' => true) );
$object->SetFieldsFromHash($field_values);
$lang_ids = explode(',', $this->Application->RecallVar('export_language_ids') );
if( !getArrayValue($field_values,'LangFile') )
{
$object->SetError('LangFile', 'required');
$event->redirect = false;
return false;
}
if( !is_writable(EXPORT_PATH) )
{
$object->SetError('LangFile', 'write_error', 'la_ExportFolderNotWritable');
$event->redirect = false;
return false;
}
if( substr($field_values['LangFile'], -5) != '.lang' ) $field_values['LangFile'] .= '.lang';
$filename = EXPORT_PATH.'/'.$field_values['LangFile'];
$lang_xml =& $this->Application->recallObject('LangXML');
if ($object->GetDBField('DoNotEncode')) {
$lang_xml->SetEncoding('plain');
}
$lang_xml->Create($filename, $field_values['PhraseType'], $lang_ids, $field_values['Module']);
}
$event->redirect = 'regional/languages_export_step2';
$event->SetRedirectParam('export_file', $field_values['LangFile']);
}
/**
* Returns to previous template in opener stack
*
* @param kEvent $event
*/
function OnGoBack(&$event)
{
$event->redirect_params['opener'] = 'u';
}
function OnScheduleTopFrameReload(&$event)
{
$this->Application->StoreVar('RefreshTopFrame',1);
}
/**
* Do now allow deleting current language
*
* @param kEvent $event
*/
function OnBeforeItemDelete(&$event)
{
$del_id = $event->getEventParam('id');
$object =& $event->getObject(array('skip_autload' => true));
$object->Load($del_id);
if ($object->GetDBField('PrimaryLang') || $object->GetDBField('AdminInterfaceLang') || $del_id == $this->Application->GetVar('m_lang')) {
$event->status = erFAIL;
}
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/languages/languages_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.33.2.2
\ No newline at end of property
+1.33.2.3
\ No newline at end of property

Event Timeline