Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sat, Feb 1, 9:32 AM

in-portal

Index: branches/unlabeled/unlabeled-1.1.2/kernel/admin_templates/advanced_view.tpl
===================================================================
--- branches/unlabeled/unlabeled-1.1.2/kernel/admin_templates/advanced_view.tpl (revision 5734)
+++ branches/unlabeled/unlabeled-1.1.2/kernel/admin_templates/advanced_view.tpl (revision 5735)
@@ -1,107 +1,107 @@
<inp2:m_RequireLogin permissions="in-portal:advanced_view.view" system="1" ajax="yes"/>
<inp2:m_include t="incs/header" nobody="yes" noform="yes"/>
<body topmargin="0" leftmargin="8" marginheight="0" marginwidth="8" bgcolor="#FFFFFF" onload="$Catalog.Init();">
<inp2:m_ParseBlock name="section_header" prefix="c" icon="icon46_catalog" module="in-portal" title="!la_title_AdvancedView!"/>
<inp2:m_ParseBlock name="blue_bar" prefix="c" title_preset="advanced_view" module="in-portal"/>
<!-- main kernel_form: begin -->
<inp2:m_RenderElement name="kernel_form"/>
<!-- ToolBar --->
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<input type="hidden" name="m_cat_id" value="<inp2:m_get name="m_cat_id"/>"/>
<script type="text/javascript" src="incs/fw_menu.js"></script>
<script type="text/javascript" src="incs/ajax.js"></script>
<script type="text/javascript" src="incs/catalog.js"></script>
<script type="text/javascript">
Request.progressText = '<inp2:m_phrase name="la_title_Loading" escape="1"/>';
Catalog.prototype.AfterInit = function() {
this.switchTab();
}
- var $Catalog = new Catalog('<inp2:m_Link template="#TEMPLATE_NAME#" tab_special="showall" m_cat_id="#CATEGORY_ID#" no_amp="1"/>', 'advanced_view_', 0);
+ var $Catalog = new Catalog('<inp2:m_Link template="#TEMPLATE_NAME#" pass_through="ts,td" ts="showall" td="no" m_cat_id="#CATEGORY_ID#" no_amp="1"/>', 'advanced_view_', 0);
var a_toolbar = new ToolBar();
a_toolbar.AddButton( new ToolBarButton('edit', '<inp2:m_phrase label="la_ToolTip_Edit" escape="1"/>', edit) );
a_toolbar.AddButton( new ToolBarButton('delete', '<inp2:m_phrase label="la_ToolTip_Delete" escape="1"/>',
function() {
var $template = $Catalog.queryTabRegistry('prefix', $Catalog.getCurrentPrefix(), 'view_template');
std_delete_items($Catalog.getCurrentPrefix(), $template, 1);
} ) );
a_toolbar.AddButton( new ToolBarSeparator('sep2') );
a_toolbar.AddButton( new ToolBarButton('approve', '<inp2:m_phrase label="la_ToolTip_Approve" escape="1"/>', function() {
$Catalog.submit_event(null, 'OnMassApprove');
}
) );
a_toolbar.AddButton( new ToolBarButton('decline', '<inp2:m_phrase label="la_ToolTip_Decline" escape="1"/>', function() {
$Catalog.submit_event(null, 'OnMassDecline');
}
) );
a_toolbar.AddButton( new ToolBarSeparator('sep3') );
a_toolbar.AddButton( new ToolBarButton('view', '<inp2:m_phrase label="la_ToolTip_View" escape="1"/>', function() {
show_viewmenu(a_toolbar, 'view');
}
) );
a_toolbar.Render();
function edit()
{
$form_name = $Catalog.queryTabRegistry('prefix', $Catalog.ActivePrefix, 'tab_id') + '_form';
set_hidden_field('remove_specials[' + $Catalog.ActivePrefix + '.showall]', 1);
std_edit_item($Catalog.ActivePrefix, $Catalog.queryTabRegistry('prefix', $Catalog.ActivePrefix, 'edit_template'));
}
</script>
</td>
</tr>
</tbody>
</table>
<inp2:m_RenderElement name="kernel_form_end"/>
<!-- main kernel_form: end -->
<br />
<!-- item tabs: begin -->
<table cellpadding="0" cellspacing="0">
<tr>
<inp2:m_DefineElement name="item_tab" title="">
<td nowrap="nowrap" width="140">
<table id="<inp2:m_param name="prefix"/>_tab" cellpadding="0" cellspacing="0" width="100%" class="catalog-tab-unselected" onclick="$Catalog.switchTab('<inp2:m_param name="prefix"/>');">
<tr>
<td class="catalog-tab-left">
<img src="img/spacer.gif" height="22" width="9" />
</td>
<td class="catalog-tab-middle" width="100%" valign="middle" nowrap="nowrap">
<inp2:m_phrase name="$title"/> <span class="cats_stats">(<span id="<inp2:m_param name="prefix"/>_item_count">?</span>)</span>
</td>
<td class="catalog-tab-right">
<img src="img/spacer.gif" height="22" width="9" />
</td>
<td style="background-color: #FFFFFF;">
<img src="img/spacer.gif" height="1" width="5" />
</td>
</tr>
</table>
</td>
</inp2:m_DefineElement>
<inp2:adm_ListCatalogTabs render_as="item_tab" title_property="ViewMenuPhrase" replace_m="yes"/>
</tr>
</table>
<!-- item tabs: end -->
<inp2:m_ModuleInclude template="catalog_tab" tab_init="2"/>
<inp2:m_include t="incs/footer" noform="yes"/>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.1.2/kernel/admin_templates/advanced_view.tpl
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1.2.1
\ No newline at end of property
+1.1.2.2
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.1.2/core/admin_templates/catalog/advanced_view.tpl
===================================================================
--- branches/unlabeled/unlabeled-1.1.2/core/admin_templates/catalog/advanced_view.tpl (revision 5734)
+++ branches/unlabeled/unlabeled-1.1.2/core/admin_templates/catalog/advanced_view.tpl (revision 5735)
@@ -1,107 +1,107 @@
<inp2:m_RequireLogin permissions="in-portal:advanced_view.view" system="1" ajax="yes"/>
<inp2:m_include t="incs/header" nobody="yes" noform="yes"/>
<body topmargin="0" leftmargin="8" marginheight="0" marginwidth="8" bgcolor="#FFFFFF" onload="$Catalog.Init();">
<inp2:m_ParseBlock name="section_header" prefix="c" icon="icon46_catalog" module="in-portal" title="!la_title_AdvancedView!"/>
<inp2:m_ParseBlock name="blue_bar" prefix="c" title_preset="advanced_view" module="in-portal"/>
<!-- main kernel_form: begin -->
<inp2:m_RenderElement name="kernel_form"/>
<!-- ToolBar --->
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<input type="hidden" name="m_cat_id" value="<inp2:m_get name="m_cat_id"/>"/>
<script type="text/javascript" src="incs/fw_menu.js"></script>
<script type="text/javascript" src="incs/ajax.js"></script>
<script type="text/javascript" src="incs/catalog.js"></script>
<script type="text/javascript">
Request.progressText = '<inp2:m_phrase name="la_title_Loading" escape="1"/>';
Catalog.prototype.AfterInit = function() {
this.switchTab();
}
- var $Catalog = new Catalog('<inp2:m_Link template="#TEMPLATE_NAME#" tab_special="showall" m_cat_id="#CATEGORY_ID#" no_amp="1"/>', 'advanced_view_', 0);
+ var $Catalog = new Catalog('<inp2:m_Link template="#TEMPLATE_NAME#" pass_through="ts,td" ts="showall" td="no" m_cat_id="#CATEGORY_ID#" no_amp="1"/>', 'advanced_view_', 0);
var a_toolbar = new ToolBar();
a_toolbar.AddButton( new ToolBarButton('edit', '<inp2:m_phrase label="la_ToolTip_Edit" escape="1"/>', edit) );
a_toolbar.AddButton( new ToolBarButton('delete', '<inp2:m_phrase label="la_ToolTip_Delete" escape="1"/>',
function() {
var $template = $Catalog.queryTabRegistry('prefix', $Catalog.getCurrentPrefix(), 'view_template');
std_delete_items($Catalog.getCurrentPrefix(), $template, 1);
} ) );
a_toolbar.AddButton( new ToolBarSeparator('sep2') );
a_toolbar.AddButton( new ToolBarButton('approve', '<inp2:m_phrase label="la_ToolTip_Approve" escape="1"/>', function() {
$Catalog.submit_event(null, 'OnMassApprove');
}
) );
a_toolbar.AddButton( new ToolBarButton('decline', '<inp2:m_phrase label="la_ToolTip_Decline" escape="1"/>', function() {
$Catalog.submit_event(null, 'OnMassDecline');
}
) );
a_toolbar.AddButton( new ToolBarSeparator('sep3') );
a_toolbar.AddButton( new ToolBarButton('view', '<inp2:m_phrase label="la_ToolTip_View" escape="1"/>', function() {
show_viewmenu(a_toolbar, 'view');
}
) );
a_toolbar.Render();
function edit()
{
$form_name = $Catalog.queryTabRegistry('prefix', $Catalog.ActivePrefix, 'tab_id') + '_form';
set_hidden_field('remove_specials[' + $Catalog.ActivePrefix + '.showall]', 1);
std_edit_item($Catalog.ActivePrefix, $Catalog.queryTabRegistry('prefix', $Catalog.ActivePrefix, 'edit_template'));
}
</script>
</td>
</tr>
</tbody>
</table>
<inp2:m_RenderElement name="kernel_form_end"/>
<!-- main kernel_form: end -->
<br />
<!-- item tabs: begin -->
<table cellpadding="0" cellspacing="0">
<tr>
<inp2:m_DefineElement name="item_tab" title="">
<td nowrap="nowrap" width="140">
<table id="<inp2:m_param name="prefix"/>_tab" cellpadding="0" cellspacing="0" width="100%" class="catalog-tab-unselected" onclick="$Catalog.switchTab('<inp2:m_param name="prefix"/>');">
<tr>
<td class="catalog-tab-left">
<img src="img/spacer.gif" height="22" width="9" />
</td>
<td class="catalog-tab-middle" width="100%" valign="middle" nowrap="nowrap">
<inp2:m_phrase name="$title"/> <span class="cats_stats">(<span id="<inp2:m_param name="prefix"/>_item_count">?</span>)</span>
</td>
<td class="catalog-tab-right">
<img src="img/spacer.gif" height="22" width="9" />
</td>
<td style="background-color: #FFFFFF;">
<img src="img/spacer.gif" height="1" width="5" />
</td>
</tr>
</table>
</td>
</inp2:m_DefineElement>
<inp2:adm_ListCatalogTabs render_as="item_tab" title_property="ViewMenuPhrase" replace_m="yes"/>
</tr>
</table>
<!-- item tabs: end -->
<inp2:m_ModuleInclude template="catalog_tab" tab_init="2"/>
<inp2:m_include t="incs/footer" noform="yes"/>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.1.2/core/admin_templates/catalog/advanced_view.tpl
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1.2.1
\ No newline at end of property
+1.1.2.2
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.59.2/core/kernel/utility/debugger.php
===================================================================
--- branches/unlabeled/unlabeled-1.59.2/core/kernel/utility/debugger.php (revision 5734)
+++ branches/unlabeled/unlabeled-1.59.2/core/kernel/utility/debugger.php (revision 5735)
@@ -1,982 +1,982 @@
<?php
if( !class_exists('Debugger') ) {
class Debugger {
/**
* 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();
/**
* 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 = 'http://www.adamauto.lv/chevrolet/images/spacer.gif';
/**
* 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;
$this->InitDebugger();
$this->profileStart('kernel4_startup', 'Startup and Initialization of kernel4', $start);
$this->profileStart('script_runtime', 'Script runtime', $start);
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();
}
/**
* Set's default values to constants debugger uses
*
*/
function InitDebugger()
{
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_') {
$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';
}
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 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 = '@'.$application->GetSID().'@';
// 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 = 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()
{
$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'];
$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';
}
// 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();
$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 />';
$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',
'TemplateParser',
);
foreach ($skip_classes as $class_name) {
if (strtolower(get_class($object)) == strtolower($class_name)) {
return true;
}
}
return false;
}
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 ($this->IsBigObject($argValue)) {
$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]);
}
}
}
/**
* Returns only first 200 chars of string, this allow to save amount of data sent to browser
*
* @param string $string
* @return string
*/
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 (!$this->constOn('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()
{
return 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 = $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 str_replace(DOC_ROOT, DBG_LOCAL_BASE_PATH, $remoteFile);
}
/**
* 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']);
+ $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>');
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(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;
}
$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;
}
}
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);
}
foreach ($error_map as $error_name => $error_codes) {
if (in_array($error_code, $error_codes)) {
return $error_name;
}
}
return '';
}
/**
* 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" width="'.$this->getWindowWidth().'"><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 ($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 || !$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 '';
}
ob_start();
?>
<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" />
<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();
$Debugger.IsFatalError = <?php echo $this->IsFatalError ? 'true' : 'false'; ?>;
$Debugger.DOMViewerURL = '<?php echo constant('DBG_DOMVIEWER'); ?>';
$Debugger.EditorPath = '<?php echo defined('DBG_EDITOR') ? addslashes(DBG_EDITOR) : '' ?>';
$Debugger.RowSeparator = '<?php echo $this->rowSeparator; ?>';
$Debugger.DebugURL = '<?php echo $this->baseURL.'/debugger_responce.php?sid='.$this->rowSeparator; ?>';
<?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)
{
$info = Array(
'Script Runtime' => 'PROFILE:script_runtime',
'-' => '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
$ret .= '<tr><td>'.$title.':</td><td><b>'.$this->ProfilerTotalCount[$record_data].'</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">'.$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 = '')
{
$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 (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);
}
$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
$buffer_content = $this->breakOutofBuffering(false) . $this->printReport(true);
echo $this->constOn('DBG_COMPRESS_OUTPUT') ? gzencode($buffer_content, DBG_COMPRESSION_LEVEL) : $buffer_content;
exit;
}
}
function breakOutofBuffering($flush = true)
{
$buffer_content = Array();
while (ob_get_level()) {
if ($flush) {
ob_end_flush();
}
else {
$buffer_content[] = ob_get_clean();
// ob_end_clean();
}
}
return implode('', array_reverse($buffer_content));
}
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();
$application =& kApplication::Instance();
$application->Debugger =& $this;
$application->errorHandlers[] = Array(&$this, 'saveError');
}
else {
set_error_handler(Array(&$this, 'saveError'));
}
}
}
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/unlabeled/unlabeled-1.59.2/core/kernel/utility/debugger.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.59.2.6
\ No newline at end of property
+1.59.2.7
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.11.2/kernel/units/general/cat_tag_processor.php
===================================================================
--- branches/unlabeled/unlabeled-1.11.2/kernel/units/general/cat_tag_processor.php (revision 5734)
+++ branches/unlabeled/unlabeled-1.11.2/kernel/units/general/cat_tag_processor.php (revision 5735)
@@ -1,155 +1,167 @@
<?php
class kCatDBTagProcessor extends kDBTagProcessor {
function ItemIcon($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$grids = $this->Application->getUnitOption($this->Prefix,'Grids');
$icons =& $grids[ $params['grid'] ]['Icons'];
$status_fields = $this->Application->getUnitOption($this->Prefix,'StatusField');
if (!$status_fields) return $icons['default'];
$value = $object->GetDBField($status_fields[0]); // sets base status icon
if ($value == STATUS_ACTIVE) {
if( $object->GetDBField('IsPop') ) $value = 'POP';
if( $object->GetDBField('IsHot') ) $value = 'HOT';
if( $object->GetDBField('IsNew') ) $value = 'NEW';
if( $object->GetDBField('EditorsPick') ) $value = 'PICK';
}
return isset($icons[$value]) ? $icons[$value] : $icons['default'];
}
function ItemLink($params)
{
// 'p_id'=>'0', ??
$params = array_merge($params, array('pass'=>'m,'.$this->Prefix));
$item_id = getArrayValue($params,$this->Prefix.'_id');
if (!$item_id) {
$item_id = $this->Application->GetVar($this->Prefix.'_id');
}
$params[$this->Prefix.'_id'] = $item_id;
$item =& $this->Application->recallObject($this->getPrefixSpecial());
$params['m_cat_id'] = $item->GetDBField('CategoryId');
$main_processor =& $this->Application->recallObject('m_TagProcessor');
return $main_processor->T($params);
}
/**
* Returns path where exported category items should be saved
*
* @param Array $params
*/
function ExportPath($params)
{
$ret = EXPORT_PATH.'/';
if( getArrayValue($params, 'as_url') )
{
$ret = str_replace( FULL_PATH.'/', $this->Application->BaseURL(), $ret);
}
$export_options = unserialize($this->Application->RecallVar($this->getPrefixSpecial().'_options'));
$ret .= $export_options['ExportFilename'].'.'.($export_options['ExportFormat'] == 1 ? 'csv' : 'xml');
return $ret;
}
function CategoryPath($params)
{
if (!isset($params['cat_id'])) {
$params['cat_id'] = $this->Application->RecallVar($params['session_var'], 0);
}
return $this->Application->ProcessParsedTag('c', 'CategoryPath', $params);
}
function BuildListSpecial($params)
{
if ($this->Special != '') return $this->Special;
if ( isset($params['parent_cat_id']) ) {
$parent_cat_id = $params['parent_cat_id'];
}
else {
$parent_cat_id = $this->Application->GetVar('c_id');
if (!$parent_cat_id) {
$parent_cat_id = $this->Application->GetVar('m_cat_id');
}
}
$recursive = isset($params['recursive']);
$types = $this->SelectParam($params, 'types');
$except = $this->SelectParam($params, 'except');
if ($types.$except.$recursive == '') {
return parent::BuildListSpecial($params);
}
$special = crc32($parent_cat_id.$types.$except.$recursive);
return $special;
}
function ExportStatus($params)
{
$export_object =& $this->Application->recallObject('CatItemExportHelper');
$event = new kEvent($this->getPrefixSpecial().':OnDummy');
$action_method = 'perform'.ucfirst($this->Special);
$field_values = $export_object->$action_method($event);
// finish code is done from JS now
if ($field_values['start_from'] == $field_values['total_records'])
{
if ($this->Special == 'import') {
$this->Application->StoreVar('PermCache_UpdateRequired', 1);
$this->Application->Redirect('categories/cache_updater', Array('pass' => 'm', 'continue' => 1, 'no_amp' => 1));
}
elseif ($this->Special == 'export') {
$template = $this->Application->getUnitOption($this->Prefix, 'ModuleFolder').'/'.$this->Special.'_finish';
$this->Application->Redirect($template, Array('pass' => 'all'));
}
}
$export_options = $export_object->loadOptions($event);
return $export_options['start_from'] * 100 / $export_options['total_records'];
}
function CatalogItemCount($params)
{
$object =& $this->GetList($params);
if (!$object->Counted) {
$object->CountRecs();
}
return $object->NoFilterCount != $object->RecordsCount ? $object->RecordsCount.' / '.$object->NoFilterCount : $object->RecordsCount;
}
function ListReviews($params)
{
$prefix = $this->Prefix.'-rev';
$review_tag_processor =& $this->Application->recallObject($prefix.'.item_TagProcessor');
return $review_tag_processor->PrintList($params);
}
function ReviewCount($params)
{
$review_tag_processor =& $this->Application->recallObject('rev.item_TagProcessor');
return $review_tag_processor->TotalRecords($params);
}
function InitCatalogTab($params)
{
- $tab_special = $this->Application->GetVar('tab_special');
+ $tab_params['mode'] = $this->Application->GetVar('tm'); // single/multi selection possible
+ $tab_params['special'] = $this->Application->GetVar('ts'); // use special for this tab
+ $tab_params['dependant'] = $this->Application->GetVar('td'); // is grid dependant on categories grid
+
+ // set default params (same as in catalog)
+ if ($tab_params['mode'] === false) $tab_params['mode'] = 'multi';
+ if ($tab_params['special'] === false) $tab_params['special'] = '';
+ if ($tab_params['dependant'] === false) $tab_params['dependant'] = 'yes';
+
+ // pass params to block with tab content
$params['name'] = $params['render_as'];
- $params['prefix'] = trim($this->Prefix.'.'.($tab_special !== false ? $tab_special : $this->Special), '.');
+ $params['prefix'] = trim($this->Prefix.'.'.($tab_params['special'] ? $tab_params['special'] : $this->Special), '.');
+ $params['cat_prefix'] = trim('c.'.($tab_params['special'] ? $tab_params['special'] : $this->Special), '.');
+ $params['tab_mode'] = $tab_params['mode'];
+ $params['tab_dependant'] = $tab_params['dependant'];
return $this->Application->ParseBlock($params, 1);
}
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.11.2/kernel/units/general/cat_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.11.2.5
\ No newline at end of property
+1.11.2.6
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.11.2/kernel/admin_templates/incs/grid.js
===================================================================
--- branches/unlabeled/unlabeled-1.11.2/kernel/admin_templates/incs/grid.js (revision 5734)
+++ branches/unlabeled/unlabeled-1.11.2/kernel/admin_templates/incs/grid.js (revision 5735)
@@ -1,389 +1,389 @@
var $GridManager = new GridManager();
function GridManager () {
this.Grids = Grids; // get all from global variable, in future replace all references to it with $GridManager.Grids
this.AlternativeGrids = new Array();
}
GridManager.prototype.AddAlternativeGrid = function ($source_grid, $destination_grid, $reciprocal)
{
if ($source_grid == $destination_grid) {
return false;
}
if (typeof(this.AlternativeGrids[$source_grid]) == 'undefined') {
// alternative grids not found, create empty list
this.AlternativeGrids[$source_grid] = new Array();
}
if (!in_array($destination_grid, this.AlternativeGrids[$source_grid])) {
// alternative grids found, check if not added already
this.AlternativeGrids[$source_grid].push($destination_grid);
}
if ($reciprocal) {
this.AddAlternativeGrid($destination_grid, $source_grid);
}
}
GridManager.prototype.ClearAlternativeGridsSelection = function ($source_prefix)
{
if (!this.AlternativeGrids[$source_prefix]) return false;
var $i = 0;
var $destination_prefix = '';
while ($i < this.AlternativeGrids[$source_prefix].length) {
$destination_prefix = this.AlternativeGrids[$source_prefix][$i];
if (this.Grids[$destination_prefix]) {
// alternative grid set, but not yet loaded by ajax
this.Grids[$destination_prefix].ClearSelection();
}
$i++;
}
}
GridManager.prototype.CheckDependencies = function ($prefix) {
if (typeof(this.Grids[$prefix]) != 'undefined') {
this.Grids[$prefix].CheckDependencies('GridManager.CheckDependencies');
}
}
function GridItem(grid, an_element, cb, item_id, class_on, class_off)
{
this.Grid = grid;
this.selected = false;
this.id = an_element.id;
this.ItemId = item_id;
this.sequence = parseInt(an_element.getAttribute('sequence'));
this.class_on = class_on;
if (class_off == ':original') {
this.class_off = an_element.className;
}
else
this.class_off = class_off;
this.HTMLelement = an_element;
this.CheckBox = cb;
this.value = this.ItemId;
this.ItemType = 11;
}
GridItem.prototype.Init = function ()
{
this.HTMLelement.GridItem = this;
this.HTMLelement.onclick = function(ev) {
this.GridItem.Click(ev);
};
this.HTMLelement.ondblclick = function(ev) {
this.GridItem.DblClick(ev);
}
if ( isset(this.CheckBox) ) {
this.CheckBox.GridItem = this;
this.CheckBox.onclick = function(ev) {
this.GridItem.cbClick(ev);
};
this.CheckBox.ondblclick = function(ev) {
this.GridItem.DblClick(ev);
}
}
}
GridItem.prototype.DisableClicking = function ()
{
this.HTMLelement.onclick = function(ev) {
return false;
};
this.HTMLelement.ondblclick = function(ev) {
return false;
}
if ( isset(this.CheckBox) ) {
this.CheckBox.onclick = function(ev) {
return false;
};
}
}
GridItem.prototype.Select = function ()
{
if (this.selected) return;
this.selected = true;
this.HTMLelement.className = this.class_on;
if ( isset(this.CheckBox) ) {
this.CheckBox.checked = true;
}
this.Grid.LastSelectedId = this.ItemId;
this.Grid.SelectedCount++;
// this is for in-portal only (used in relation select)
LastCheckedItem = this;
if (typeof (this.Grid.OnSelect) == 'function' ) {
this.Grid.OnSelect(this.ItemId);
}
}
GridItem.prototype.UnSelect = function ( force )
{
if ( !this.selected && !force) return;
this.selected = false;
this.HTMLelement.className = this.class_off;
if ( isset(this.CheckBox) ) {
this.CheckBox.checked = false;
}
this.Grid.SelectedCount--;
if (typeof (this.Grid.OnUnSelect) == 'function' ) {
this.Grid.OnUnSelect(this.ItemId);
}
}
GridItem.prototype.ClearBrowserSelection = function() {
if (window.getSelection) {
// removeAllRanges will be supported by Opera from v 9+, do nothing by now
var selection = window.getSelection();
if (selection.removeAllRanges) { // Mozilla & Opera 9+
window.getSelection().removeAllRanges();
}
} else if (document.selection && !is.opera) { // IE
document.selection.empty();
}
}
GridItem.prototype.Click = function (ev)
{
this.ClearBrowserSelection();
this.Grid.ClearAlternativeGridsSelection('GridItem.Click');
var e = !is.ie ? ev : window.event;
if (e.shiftKey && !this.Grid.RadioMode) {
this.Grid.SelectRangeUpTo(this.sequence);
}
else {
if (e.ctrlKey && !this.Grid.RadioMode) {
this.Toggle()
}
else {
- if (!(this.Grid.RadioMode && this.Grid.LastSelectedId == this.ItemId)) {
+ if (!(this.Grid.RadioMode && this.Grid.LastSelectedId == this.ItemId && this.selected)) {
// don't clear selection if item same as current is selected
this.Grid.ClearSelection(null,'GridItem.Click');
this.Toggle();
}
}
}
this.Grid.CheckDependencies('GridItem.Click');
e.cancelBubble = true;
}
GridItem.prototype.cbClick = function (ev)
{
var e = is.ie ? window.event : ev;
if (this.Grid.RadioMode) this.Grid.ClearSelection(null,'GridItem.cbClick');
this.Grid.ClearAlternativeGridsSelection('GridItem.cbClick');
this.Toggle();
this.Grid.CheckDependencies('GridItem.cbClick');
e.cancelBubble = true;
}
GridItem.prototype.DblClick = function (ev)
{
var e = is.ie ? window.event : ev;
this.Grid.Edit();
}
GridItem.prototype.Toggle = function ()
{
if (this.selected) this.UnSelect()
else {
this.Grid.LastSelectedSequence = this.sequence;
this.Select();
}
}
GridItem.prototype.FallsInRange = function (from, to)
{
return (from <= to) ?
(this.sequence >= from && this.sequence <= to) :
(this.sequence >= to && this.sequence <= from);
}
function Grid(prefix, class_on, class_off, dbl_click, toolbar)
{
this.prefix = prefix;
this.class_on = class_on;
this.class_off = class_off;
this.Items = new Array();
this.LastSelectedSequence = 1;
this.LastSelectedId = null;
this.DblClick = dbl_click;
this.ToolBar = toolbar;
this.SelectedCount = 0;
this.AlternativeGrids = new Array();
this.DependantButtons = new Array();
this.RadioMode = false;
}
Grid.prototype.AddItem = function( an_item ) {
this.Items[an_item.id] = an_item;
}
Grid.prototype.AddItemsByIdMask = function ( tag, mask, cb_mask ) {
var $item_id=0;
elements = document.getElementsByTagName(tag.toUpperCase());
for (var i=0; i < elements.length; i++) {
if ( typeof(elements[i].id) == 'undefined') {
continue;
}
if ( !elements[i].id.match(mask)) continue;
$item_id=RegExp.$1;
cb_name = cb_mask.replace('$$ID$$',$item_id);
cb = document.getElementById(cb_name);
if (typeof(cb) == 'undefined') alert ('No Checkbox defined for item '+elements[i].id);
this.AddItem( new GridItem( this, elements[i], cb, $item_id, this.class_on, this.class_off ) );
}
}
Grid.prototype.InitItems = function() {
for (var i in this.Items) {
this.Items[i].Init();
}
this.ClearSelection( true,'Grid.InitItems' );
}
Grid.prototype.DisableClicking = function() {
for (var i in this.Items) {
this.Items[i].DisableClicking();
}
this.ClearSelection( true, 'Grid.DisableClicking' );
}
Grid.prototype.ClearSelection = function( force, called_from ) {
// alert('selection clear. force: '+force+'; called_from: '+called_from);
if (typeof(force) == 'undefined') force = false;
if (this.CountSelected() == 0 && !force) return;
for (var i in this.Items) {
this.Items[i].UnSelect(force);
}
this.SelectedCount = 0;
this.CheckDependencies('Grid.ClearSelection');
}
Grid.prototype.GetSelected = function() {
var $ret = new Array();
for (var i in this.Items) {
if (this.Items[i].selected) {
$ret[$ret.length] = this.Items[i].ItemId;
}
}
return $ret;
}
Grid.prototype.InvertSelection = function() {
for (var i in this.Items)
{
if( this.Items[i].selected )
{
this.Items[i].UnSelect();
}
else
{
this.Items[i].Select();
}
}
this.CheckDependencies('Grid.InvertSelection');
}
Grid.prototype.SelectAll = function() {
for (var i in this.Items) {
this.Items[i].Select();
}
this.CheckDependencies('Grid.SelectAll');
this.ClearAlternativeGridsSelection('Grid.SelectAll');
}
Grid.prototype.SelectRangeUpTo = function( last_sequence ) {
for (var i in this.Items) {
if (this.Items[i].FallsInRange(this.LastSelectedSequence, last_sequence)) {
this.Items[i].Select();
}
}
}
Grid.prototype.CountSelected = function ()
{
return this.SelectedCount;
}
Grid.prototype.Edit = function() {
if ( this.CountSelected() == 0 ) return;
this.DblClick();
}
Grid.prototype.SetDependantToolbarButtons = function($buttons, $direct, $mode) {
if (!isset($direct)) $direct = true; // direct (use false for invert mode)
if (!isset($mode)) $mode = 1; // enable/disable (use 2 for show/hide mode)
for (var i in $buttons) {
this.DependantButtons.push(new Array($buttons[i], $direct, $mode));
}
//this.DependantButtons = buttons;
this.CheckDependencies('Grid.SetDependantToolbarButtons');
}
Grid.prototype.CheckDependencies = function($called_from)
{
// alert('prefix: ' + this.prefix + '; ' + $called_from + ' -> Grid.CheckDependencies');
var enabling = (this.CountSelected() > 0);
for (var i in this.DependantButtons) {
if (this.DependantButtons[i][0].match("portal:(.*)")) {
button_name = RegExp.$1;
if (toolbar) {
if (enabling == this.DependantButtons[i][1]) {
toolbar.enableButton(button_name, true);
}
else
{
toolbar.disableButton(button_name, true);
}
}
}
else {
if (this.DependantButtons[i][2] == 1) {
this.ToolBar.SetEnabled(this.DependantButtons[i][0], enabling == this.DependantButtons[i][1]);
}
else {
this.ToolBar.SetVisible(this.DependantButtons[i][0], enabling == this.DependantButtons[i][1]);
}
}
}
//if (enabling) this.ClearAlternativeGridsSelection('Grid.CheckDependencies');
}
Grid.prototype.ClearAlternativeGridsSelection = function (called_from)
{
$GridManager.ClearAlternativeGridsSelection(this.prefix);
}
Grid.prototype.AddAlternativeGrid = function (alt_grid, reciprocal)
{
var $dst_prefix = typeof('alt_grid') == 'string' ? alt_grid : alt_grid.prefix;
$GridManager.AddAlternativeGrid(this.prefix, $dst_prefix, reciprocal);
}
Grid.prototype.FirstSelected = function ()
{
min_sequence = null;
var res = null
for (var i in this.Items) {
if (!this.Items[i].selected) continue;
if (min_sequence == null)
min_sequence = this.Items[i].sequence;
if (this.Items[i].sequence <= min_sequence) {
res = this.Items[i].ItemId;
min_sequence = this.Items[i].sequence;
}
}
return res;
}
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.11.2/kernel/admin_templates/incs/grid.js
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.11.2.1
\ No newline at end of property
+1.11.2.2
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.11.2/core/units/general/cat_tag_processor.php
===================================================================
--- branches/unlabeled/unlabeled-1.11.2/core/units/general/cat_tag_processor.php (revision 5734)
+++ branches/unlabeled/unlabeled-1.11.2/core/units/general/cat_tag_processor.php (revision 5735)
@@ -1,155 +1,167 @@
<?php
class kCatDBTagProcessor extends kDBTagProcessor {
function ItemIcon($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$grids = $this->Application->getUnitOption($this->Prefix,'Grids');
$icons =& $grids[ $params['grid'] ]['Icons'];
$status_fields = $this->Application->getUnitOption($this->Prefix,'StatusField');
if (!$status_fields) return $icons['default'];
$value = $object->GetDBField($status_fields[0]); // sets base status icon
if ($value == STATUS_ACTIVE) {
if( $object->GetDBField('IsPop') ) $value = 'POP';
if( $object->GetDBField('IsHot') ) $value = 'HOT';
if( $object->GetDBField('IsNew') ) $value = 'NEW';
if( $object->GetDBField('EditorsPick') ) $value = 'PICK';
}
return isset($icons[$value]) ? $icons[$value] : $icons['default'];
}
function ItemLink($params)
{
// 'p_id'=>'0', ??
$params = array_merge($params, array('pass'=>'m,'.$this->Prefix));
$item_id = getArrayValue($params,$this->Prefix.'_id');
if (!$item_id) {
$item_id = $this->Application->GetVar($this->Prefix.'_id');
}
$params[$this->Prefix.'_id'] = $item_id;
$item =& $this->Application->recallObject($this->getPrefixSpecial());
$params['m_cat_id'] = $item->GetDBField('CategoryId');
$main_processor =& $this->Application->recallObject('m_TagProcessor');
return $main_processor->T($params);
}
/**
* Returns path where exported category items should be saved
*
* @param Array $params
*/
function ExportPath($params)
{
$ret = EXPORT_PATH.'/';
if( getArrayValue($params, 'as_url') )
{
$ret = str_replace( FULL_PATH.'/', $this->Application->BaseURL(), $ret);
}
$export_options = unserialize($this->Application->RecallVar($this->getPrefixSpecial().'_options'));
$ret .= $export_options['ExportFilename'].'.'.($export_options['ExportFormat'] == 1 ? 'csv' : 'xml');
return $ret;
}
function CategoryPath($params)
{
if (!isset($params['cat_id'])) {
$params['cat_id'] = $this->Application->RecallVar($params['session_var'], 0);
}
return $this->Application->ProcessParsedTag('c', 'CategoryPath', $params);
}
function BuildListSpecial($params)
{
if ($this->Special != '') return $this->Special;
if ( isset($params['parent_cat_id']) ) {
$parent_cat_id = $params['parent_cat_id'];
}
else {
$parent_cat_id = $this->Application->GetVar('c_id');
if (!$parent_cat_id) {
$parent_cat_id = $this->Application->GetVar('m_cat_id');
}
}
$recursive = isset($params['recursive']);
$types = $this->SelectParam($params, 'types');
$except = $this->SelectParam($params, 'except');
if ($types.$except.$recursive == '') {
return parent::BuildListSpecial($params);
}
$special = crc32($parent_cat_id.$types.$except.$recursive);
return $special;
}
function ExportStatus($params)
{
$export_object =& $this->Application->recallObject('CatItemExportHelper');
$event = new kEvent($this->getPrefixSpecial().':OnDummy');
$action_method = 'perform'.ucfirst($this->Special);
$field_values = $export_object->$action_method($event);
// finish code is done from JS now
if ($field_values['start_from'] == $field_values['total_records'])
{
if ($this->Special == 'import') {
$this->Application->StoreVar('PermCache_UpdateRequired', 1);
$this->Application->Redirect('categories/cache_updater', Array('pass' => 'm', 'continue' => 1, 'no_amp' => 1));
}
elseif ($this->Special == 'export') {
$template = $this->Application->getUnitOption($this->Prefix, 'ModuleFolder').'/'.$this->Special.'_finish';
$this->Application->Redirect($template, Array('pass' => 'all'));
}
}
$export_options = $export_object->loadOptions($event);
return $export_options['start_from'] * 100 / $export_options['total_records'];
}
function CatalogItemCount($params)
{
$object =& $this->GetList($params);
if (!$object->Counted) {
$object->CountRecs();
}
return $object->NoFilterCount != $object->RecordsCount ? $object->RecordsCount.' / '.$object->NoFilterCount : $object->RecordsCount;
}
function ListReviews($params)
{
$prefix = $this->Prefix.'-rev';
$review_tag_processor =& $this->Application->recallObject($prefix.'.item_TagProcessor');
return $review_tag_processor->PrintList($params);
}
function ReviewCount($params)
{
$review_tag_processor =& $this->Application->recallObject('rev.item_TagProcessor');
return $review_tag_processor->TotalRecords($params);
}
function InitCatalogTab($params)
{
- $tab_special = $this->Application->GetVar('tab_special');
+ $tab_params['mode'] = $this->Application->GetVar('tm'); // single/multi selection possible
+ $tab_params['special'] = $this->Application->GetVar('ts'); // use special for this tab
+ $tab_params['dependant'] = $this->Application->GetVar('td'); // is grid dependant on categories grid
+
+ // set default params (same as in catalog)
+ if ($tab_params['mode'] === false) $tab_params['mode'] = 'multi';
+ if ($tab_params['special'] === false) $tab_params['special'] = '';
+ if ($tab_params['dependant'] === false) $tab_params['dependant'] = 'yes';
+
+ // pass params to block with tab content
$params['name'] = $params['render_as'];
- $params['prefix'] = trim($this->Prefix.'.'.($tab_special !== false ? $tab_special : $this->Special), '.');
+ $params['prefix'] = trim($this->Prefix.'.'.($tab_params['special'] ? $tab_params['special'] : $this->Special), '.');
+ $params['cat_prefix'] = trim('c.'.($tab_params['special'] ? $tab_params['special'] : $this->Special), '.');
+ $params['tab_mode'] = $tab_params['mode'];
+ $params['tab_dependant'] = $tab_params['dependant'];
return $this->Application->ParseBlock($params, 1);
}
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.11.2/core/units/general/cat_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.11.2.5
\ No newline at end of property
+1.11.2.6
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.155.2/core/kernel/application.php
===================================================================
--- branches/unlabeled/unlabeled-1.155.2/core/kernel/application.php (revision 5734)
+++ branches/unlabeled/unlabeled-1.155.2/core/kernel/application.php (revision 5735)
@@ -1,2139 +1,2171 @@
<?php
/**
* Basic class for Kernel3-based Application
*
* This class is a Facade for any other class which needs to deal with Kernel3 framework.<br>
* The class incapsulates the main run-cycle of the script, provide access to all other objects in the framework.<br>
* <br>
* The class is a singleton, which means that there could be only one instance of KernelApplication in the script.<br>
* This could be guranteed by NOT calling the class constuctor directly, but rather calling KernelApplication::Instance() method,
* which returns an instance of the application. The method gurantees that it will return exactly the same instance for any call.<br>
* See singleton pattern by GOF.
* @package kernel4
*/
class kApplication {
/**
* Is true, when Init method was called already, prevents double initialization
*
* @var bool
*/
var $InitDone = false;
/**
* Holds internal TemplateParser object
* @access private
* @var TemplateParser
*/
var $Parser;
/**
* Holds parser output buffer
* @access private
* @var string
*/
var $HTML;
/**
* Prevents request from beeing proceeded twice in case if application init is called mere then one time
*
* @var bool
* @todo This is not good anyway (by Alex)
*/
var $RequestProcessed = false;
/**
* The main Factory used to create
* almost any class of kernel and
* modules
*
* @access private
* @var kFactory
*/
var $Factory;
/**
* All ConfigurationValues table content (hash) here
*
* @var Array
* @access private
*/
var $ConfigHash = Array();
/**
* Ids of config variables used in current run (for caching)
*
* @var Array
* @access private
*/
var $ConfigCacheIds = array();
/**
* Reference to debugger
*
* @var Debugger
*/
var $Debugger = null;
/**
* Holds all phrases used
* in code and template
*
* @var PhrasesCache
*/
var $Phrases;
/**
* Modules table content, key - module name
*
* @var Array
*/
var $ModuleInfo = Array();
/**
* Holds DBConnection
*
* @var kDBConnection
*/
var $Conn = null;
/**
* Maintains list of user-defined error handlers
*
* @var Array
*/
var $errorHandlers = Array();
// performance needs:
/**
* Holds a refererence to httpquery
*
* @var kHttpQuery
*/
var $HttpQuery = null;
/**
* Holds a reference to UnitConfigReader
*
* @var kUnitConfigReader
*/
var $UnitConfigReader = null;
/**
* Holds a reference to Session
*
* @var Session
*/
var $Session = null;
/**
* Holds a ref to kEventManager
*
* @var kEventManager
*/
var $EventManager = null;
/**
* Ref to itself, needed because everybody used to write $this->Application, even inside kApplication
*
* @var kApplication
*/
var $Application = null;
/**
* Ref for TemplatesChache
*
* @var TemplatesCache
*/
var $TemplatesCache = null;
var $CompilationCache = array(); //used when compiling templates
var $CachedProcessors = array(); //used when running compiled templates
/**
* Returns kApplication instance anywhere in the script.
*
* This method should be used to get single kApplication object instance anywhere in the
* Kernel-based application. The method is guranteed to return the SAME instance of kApplication.
* Anywhere in the script you could write:
* <code>
* $application =& kApplication::Instance();
* </code>
* or in an object:
* <code>
* $this->Application =& kApplication::Instance();
* </code>
* to get the instance of kApplication. Note that we call the Instance method as STATIC - directly from the class.
* To use descendand of standard kApplication class in your project you would need to define APPLICATION_CLASS constant
* BEFORE calling kApplication::Instance() for the first time. If APPLICATION_CLASS is not defined the method would
* create and return default KernelApplication instance.
* @static
* @access public
* @return kApplication
*/
function &Instance()
{
static $instance = false;
if(!$instance)
{
safeDefine('APPLICATION_CLASS', 'kApplication');
$class = APPLICATION_CLASS;
$instance = new $class();
$instance->Application =& $instance;
}
return $instance;
}
/**
* Initializes the Application
*
* @access public
* @see kHTTPQuery
* @see Session
* @see TemplatesCache
* @return bool Was Init actually made now or before
*/
function Init()
{
if($this->InitDone) return false;
ob_start(); // collect any output from method (other then tags) into buffer
if(defined('DEBUG_MODE') && $this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Init:');
}
if (!$this->isDebugMode() && !constOn('DBG_ZEND_PRESENT')) {
error_reporting(0);
ini_set('display_errors', 0);
}
if (!constOn('DBG_ZEND_PRESENT')) {
$error_handler = set_error_handler( Array(&$this,'handleError') );
if ($error_handler) $this->errorHandlers[] = $error_handler;
}
$this->Conn = new kDBConnection(SQL_TYPE, Array(&$this, 'handleSQLError') );
$this->Conn->Connect(SQL_SERVER, SQL_USER, SQL_PASS, SQL_DB);
$this->Conn->debugMode = $this->isDebugMode();
$this->Factory = new kFactory();
$this->registerDefaultClasses();
$this->Phrases = new PhrasesCache();
$this->EventManager =& $this->Factory->makeClass('EventManager');
$this->Factory->Storage['EventManager'] =& $this->EventManager;
$this->RegisterDefaultBuildEvents();
$this->SetDefaultConstants();
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
$this->UnitConfigReader->scanModules(MODULES_PATH);
$this->registerModuleConstants();
$rewrite_on = $this->ConfigValue('UseModRewrite');
// admin=1 - when front is browsed using admin session
$admin_on = getArrayValue($_REQUEST, 'admin') || $this->IsAdmin();
define('MOD_REWRITE', $rewrite_on && !$admin_on ? 1 : 0);
if ($this->UseOutputCompression()) {
header('Content-Encoding: gzip');
safeDefine('DBG_COMPRESS_OUTPUT', 1);
$level = $this->ConfigValue('OutputCompressionLevel');
if ($level < 0 || $level > 9) $level = 7;
safeDefine('DBG_COMPRESSION_LEVEL', $level);
}
$this->HttpQuery =& $this->recallObject('HTTPQuery');
$this->Session =& $this->recallObject('Session');
$this->HttpQuery->AfterInit();
$this->UnitConfigReader->AfterConfigRead();
$this->LoadCache();
$this->InitConfig();
// Module items are recalled during url parsing & PhrasesCache is needed already there,
// because it's used in their build events. That's why phrases cache initialization is
// called from kHTTPQuery in case when mod_rewrite is used
if (!$this->RewriteURLs()) {
$this->Phrases = new PhrasesCache();
}
$this->Phrases->Init('phrases');
if(!$this->RecallVar('UserGroups')) {
$session =& $this->recallObject('Session');
$user_groups = trim($session->GetField('GroupList'), ',');
if (!$user_groups) $user_groups = $this->ConfigValue('User_GuestGroup');
$this->StoreVar('UserGroups', $user_groups);
}
if ($this->GetVar('m_cat_id') === false) $this->SetVar('m_cat_id', 0);
if( !$this->RecallVar('curr_iso') ) $this->StoreVar('curr_iso', $this->GetPrimaryCurrency() );
$this->SetVar('visits_id', $this->RecallVar('visit_id') );
$language =& $this->recallObject( 'lang.current', null, Array('live_table' => true) );
$this->HandleEvent( new kEvent('visits:OnRegisterVisit') );
$this->ValidateLogin();
if($this->isDebugMode()) {
$this->Debugger->profileFinish('kernel4_startup');
}
$this->InitDone = true;
return true;
}
/**
* Returns module information. Searches module by requested field
*
* @param string $field
* @param mixed $value
* @param string field value to returns, if not specified, then return all fields
* @param string field to return
* @return Array
*/
function findModule($field, $value, $return_field = null)
{
$found = false;
foreach ($this->ModuleInfo as $module_name => $module_info) {
if (strtolower($module_info[$field]) == strtolower($value)) {
$found = true;
break;
}
}
if ($found) {
return isset($return_field) ? $module_info[$return_field] : $module_info;
}
return false;
}
function refreshModuleInfo()
{
$modules_helper =& $this->recallObject('ModulesHelper');
$sql = 'SELECT *
FROM '.TABLE_PREFIX.'Modules
WHERE '.$modules_helper->getWhereClause().'
ORDER BY LoadOrder';
$this->ModuleInfo = $this->Conn->Query($sql, 'Name');
$this->registerModuleConstants();
}
/**
* Checks if passed language id if valid and sets it to primary otherwise
*
*/
function VerifyLanguageId()
{
$language_id = $this->GetVar('m_lang');
if (!$language_id) {
$language_id = 'default';
}
$this->SetVar('lang.current_id', $language_id );
$this->SetVar('m_lang', $language_id );
$lang_mode = $this->GetVar('lang_mode');
$this->SetVar('lang_mode', '');
$lang =& $this->recallObject('lang.current');
if ( !$lang->IsLoaded() || (!$this->Application->IsAdmin() && !$lang->GetDBField('Enabled')) ) {
if (!defined('IS_INSTALL')) $this->ApplicationDie('Unknown or disabled language');
}
$this->SetVar('lang_mode',$lang_mode);
}
/**
* Checks if passed theme id if valid and sets it to primary otherwise
*
*/
function VerifyThemeId()
{
if ($this->Application->IsAdmin()) {
safeDefine('THEMES_PATH', '/kernel/admin_templates');
return;
}
$theme_id = $this->GetVar('m_theme');
if (!$theme_id) {
$theme_id = $this->GetDefaultThemeId();
if (!$theme_id) {
$this->ApplicationDie('No Primary Theme Selected');
}
}
$this->SetVar('m_theme', $theme_id);
$this->SetVar('theme.current_id', $theme_id ); // KOSTJA: this is to fool theme' getPassedId
$theme =& $this->recallObject('theme.current');
if (!$theme->IsLoaded() || !$theme->GetDBField('Enabled')) {
if (!defined('IS_INSTALL')) $this->ApplicationDie('Unknown or disabled theme');
}
safeDefine('THEMES_PATH', '/themes/'.$theme->GetDBField('Name'));
}
function GetDefaultLanguageId()
{
static $language_id = 0;
if ($language_id > 0) return $language_id;
$table = $this->getUnitOption('lang','TableName');
$id_field = $this->getUnitOption('lang','IDField');
$sql = 'SELECT '.$id_field.'
FROM '.$table.'
WHERE (PrimaryLang = 1) AND (Enabled = 1)';
$language_id = $this->Conn->GetOne($sql);
return $language_id;
}
function GetDefaultThemeId()
{
static $theme_id = 0;
if($theme_id > 0) return $theme_id;
if (constOn('DBG_FORCE_THEME')) {
$theme_id = DBG_FORCE_THEME;
}
else {
$table = $this->getUnitOption('theme','TableName');
$id_field = $this->getUnitOption('theme','IDField');
$sql = 'SELECT '.$id_field.'
FROM '.$table.'
WHERE (PrimaryTheme = 1) AND (Enabled = 1)';
$theme_id = $this->Conn->GetOne($sql);
}
return $theme_id;
}
function GetPrimaryCurrency()
{
if ($this->isModuleEnabled('In-Commerce')) {
$table = $this->getUnitOption('curr', 'TableName');
return $this->Conn->GetOne('SELECT ISO FROM '.$table.' WHERE IsPrimary = 1');
}
else {
return 'USD';
}
}
/**
* Registers default classes such as ItemController, GridController and LoginController
*
* Called automatically while initializing Application
* @access private
* @return void
*/
function RegisterDefaultClasses()
{
$this->registerClass('kTempTablesHandler', KERNEL_PATH.'/utility/temp_handler.php');
$this->registerClass('kEventManager', KERNEL_PATH.'/event_manager.php', 'EventManager');
$this->registerClass('kUnitConfigReader', KERNEL_PATH.'/utility/unit_config_reader.php');
$this->registerClass('kArray', KERNEL_PATH.'/utility/params.php');
$this->registerClass('Params', KERNEL_PATH.'/utility/params.php');
$this->registerClass('kHelper', KERNEL_PATH.'/kbase.php');
$this->registerClass('kCache', KERNEL_PATH.'/utility/cache.php', 'Cache', Array('Params'));
$this->registerClass('kHTTPQuery', KERNEL_PATH.'/utility/http_query.php', 'HTTPQuery', Array('Params') );
$this->registerClass('Session', KERNEL_PATH.'/session/session.php');
$this->registerClass('SessionStorage', KERNEL_PATH.'/session/session.php');
$this->registerClass('Params', KERNEL_PATH.'/utility/params.php', 'kActions');
/*$this->registerClass('kFormatter', KERNEL_PATH.'/utility/formatters.php');
$this->registerClass('kOptionsFormatter', KERNEL_PATH.'/utility/formatters.php');
$this->registerClass('kUploadFormatter', KERNEL_PATH.'/utility/formatters.php');
$this->registerClass('kPictureFormatter', KERNEL_PATH.'/utility/formatters.php');
$this->registerClass('kDateFormatter', KERNEL_PATH.'/utility/formatters.php');
$this->registerClass('kLEFTFormatter', KERNEL_PATH.'/utility/formatters.php');
$this->registerClass('kMultiLanguage', KERNEL_PATH.'/utility/formatters.php');
$this->registerClass('kPasswordFormatter', KERNEL_PATH.'/utility/formatters.php');
$this->registerClass('kCCDateFormatter', KERNEL_PATH.'/utility/formatters.php');
$this->registerClass('kUnitFormatter', KERNEL_PATH.'/utility/formatters.php');
$this->registerClass('kFilesizeFormatter', KERNEL_PATH.'/utility/formatters.php');
$this->registerClass('kSerializedFormatter', KERNEL_PATH.'/utility/formatters.php');*/
$this->registerClass('kMultipleFilter', KERNEL_PATH.'/utility/filters.php');
$this->registerClass('kDBList', KERNEL_PATH.'/db/dblist.php');
$this->registerClass('kDBItem', KERNEL_PATH.'/db/dbitem.php');
$this->registerClass('kDBEventHandler', KERNEL_PATH.'/db/db_event_handler.php');
$this->registerClass('kTagProcessor', KERNEL_PATH.'/processors/tag_processor.php');
$this->registerClass('kMainTagProcessor', KERNEL_PATH.'/processors/main_processor.php','m_TagProcessor', 'kTagProcessor');
$this->registerClass('kDBTagProcessor', KERNEL_PATH.'/db/db_tag_processor.php', null, 'kTagProcessor');
$this->registerClass('TemplatesCache', KERNEL_PATH.'/parser/template.php');
$this->registerClass('Template', KERNEL_PATH.'/parser/template.php');
$this->registerClass('TemplateParser', KERNEL_PATH.'/parser/template_parser.php',null, 'kDBTagProcessor');
$this->registerClass('kEmailMessage', KERNEL_PATH.'/utility/email.php');
$this->registerClass('kSmtpClient', KERNEL_PATH.'/utility/smtp_client.php');
if (file_exists(MODULES_PATH.'/in-commerce/units/currencies/currency_rates.php')) {
$this->registerClass('kCurrencyRates', MODULES_PATH.'/in-commerce/units/currencies/currency_rates.php');
}
$this->registerClass('FCKeditor', FULL_PATH.'/admin/editor/cmseditor/fckeditor.php'); // need this?
}
function RegisterDefaultBuildEvents()
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->registerBuildEvent('kTempTablesHandler', 'OnTempHandlerBuild');
}
/**
* Returns item's filename that corresponds id passed. If possible, then get it from cache
*
* @param string $prefix
* @param int $id
* @return string
*/
function getFilename($prefix, $id, $category_id=null)
{
$filename = $this->getCache('filenames', $prefix.'_'.$id);
if ($filename === false) {
$table = $this->getUnitOption($prefix, 'TableName');
$id_field = $this->getUnitOption($prefix, 'IDField');
if ($prefix == 'c') {
if(!$id) {
$this->setCache('filenames', $prefix.'_'.$id, '');
return '';
}
// this allows to save 2 sql queries for each category
$sql = 'SELECT NamedParentPath, CachedCategoryTemplate, CachedItemTemplate
FROM '.$table.'
WHERE '.$id_field.' = '.$this->Conn->qstr($id);
$category_data = $this->Conn->GetRow($sql);
$filename = $category_data['NamedParentPath'];
$this->setCache('category_templates', $id, $category_data['CachedCategoryTemplate']);
$this->setCache('item_templates', $id, $category_data['CachedItemTemplate']);
}
else {
$resource_id = $this->Conn->GetOne('SELECT ResourceId FROM '.$table.' WHERE '.$id_field.' = '.$this->Conn->qstr($id));
if (is_null($category_id)) $category_id = $this->GetVar('m_cat_id');
$sql = 'SELECT Filename FROM '.TABLE_PREFIX.'CategoryItems WHERE ItemResourceId = '.$resource_id.' AND CategoryId = '.$category_id;
$filename = $this->Conn->GetOne($sql);
/*$sql = 'SELECT Filename
FROM '.$table.'
WHERE '.$id_field.' = '.$this->Conn->qstr($id);
$filename = $this->Conn->GetOne($sql);*/
}
$this->setCache('filenames', $prefix.'_'.$id, $filename);
}
return $filename;
}
/**
* Adds new value to cache $cache_name and identified by key $key
*
* @param string $cache_name cache name
* @param int $key key name to add to cache
* @param mixed $value value of chached record
*/
function setCache($cache_name, $key, $value)
{
$cache =& $this->recallObject('Cache');
$cache->setCache($cache_name, $key, $value);
}
/**
* Returns cached $key value from cache named $cache_name
*
* @param string $cache_name cache name
* @param int $key key name from cache
* @return mixed
*/
function getCache($cache_name, $key)
{
$cache =& $this->recallObject('Cache');
return $cache->getCache($cache_name, $key);
}
/**
* Defines default constants if it's not defined before - in config.php
*
* @access private
*/
function SetDefaultConstants()
{
safeDefine('SERVER_NAME', $_SERVER['HTTP_HOST']);
}
/**
* Registers each module specific constants if any found
*
*/
function registerModuleConstants()
{
if (!$this->ModuleInfo) return false;
foreach($this->ModuleInfo as $module_name => $module_info)
{
$module_path = '/'.$module_info['Path'];
$contants_file = FULL_PATH.$module_path.'constants.php';
if( file_exists($contants_file) ) k4_include_once($contants_file);
}
return true;
}
function ProcessRequest()
{
$event_manager =& $this->recallObject('EventManager');
if($this->isDebugMode() && constOn('DBG_SHOW_HTTPQUERY')) {
$this->Debugger->appendHTML('HTTPQuery:');
$this->Debugger->dumpVars($this->HttpQuery->_Params);
}
$event_manager->ProcessRequest();
$event_manager->RunRegularEvents(reBEFORE);
$this->RequestProcessed = true;
}
/**
* Actually runs the parser against current template and stores parsing result
*
* This method gets t variable passed to the script, loads the template given in t variable and
* parses it. The result is store in {@link $this->HTML} property.
* @access public
* @return void
*/
function Run()
{
if($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Run:');
}
if ($this->IsAdmin()) {
// for permission checking in events & templates
$this->LinkVar('module'); // for common configuration templates
$this->LinkVar('section'); // for common configuration templates
if ($this->GetVar('m_opener') == 'p') {
$this->LinkVar('main_prefix'); // window prefix, that opened selector
$this->LinkVar('dst_field'); // field to set value choosed in selector
$this->LinkVar('return_template'); // template to go, when something was coosen from popup (from finalizePopup)
$this->LinkVar('return_m'); // main env part to restore after popup will be closed (from finalizePopup)
}
if ($this->GetVar('ajax') == 'yes') {
// hide debug output from ajax requests automatically
define('DBG_SKIP_REPORTING', 1);
}
}
if (!$this->RequestProcessed) $this->ProcessRequest();
$this->InitParser();
$t = $this->GetVar('t');
if ($this->isModuleEnabled('In-CMS')) {
$cms_handler =& $this->recallObject('cms_EventHandler');
if (!$this->TemplatesCache->TemplateExists($t) && !$this->IsAdmin()) {
$t = $cms_handler->GetDesignTemplate();
}
/*else {
$cms_handler->SetCatByTemplate();
}*/
}
if($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Parsing:');
}
$this->HTML = $this->Parser->ParseTemplate( $t );
if ($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application after Parsing:');
}
}
function InitParser()
{
if( !is_object($this->Parser) ) {
$this->Parser =& $this->recallObject('TemplateParser');
$this->TemplatesCache =& $this->recallObject('TemplatesCache');
}
}
/**
* Send the parser results to browser
*
* Actually send everything stored in {@link $this->HTML}, to the browser by echoing it.
* @access public
* @return void
*/
function Done()
{
if ($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Done:');
}
if ($this->GetVar('admin')) {
$reg = '/('.preg_quote(BASE_PATH, '/').'.*\.html)(#.*){0,1}(")/sU';
$this->HTML = preg_replace($reg, "$1?admin=1$2$3", $this->HTML);
}
//eval("?".">".$this->HTML);
$this->HTML = ob_get_clean().$this->HTML;
if ($this->isDebugMode()) {
$this->HTML .= $this->Debugger->printReport(true);
}
echo $this->UseOutputCompression() ? gzencode($this->HTML, DBG_COMPRESSION_LEVEL) : $this->HTML;
$this->UpdateCache();
flush();
if ($this->isDebugMode() && constOn('DBG_CACHE')) {
$cache =& $this->recallObject('Cache');
$cache->printStatistics();
}
$event_manager =& $this->recallObject('EventManager');
$event_manager->RunRegularEvents(reAFTER);
$session =& $this->recallObject('Session');
$session->SaveData();
//$this->SaveBlocksCache();
}
/**
* Checks if output compression options is available
*
* @return string
*/
function UseOutputCompression()
{
if (constOn('IS_INSTALL')) return false;
return $this->ConfigValue('UseOutputCompression') && function_exists('gzencode') && strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
}
function SaveBlocksCache()
{
/*if (constOn('EXPERIMENTAL_PRE_PARSE')) {
$data = serialize($this->PreParsedCache);
$this->Conn->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("blocks_cache", '.$this->Conn->qstr($data).', '.adodb_mktime().')');
}*/
}
// Facade
/**
* Returns current session id (SID)
* @access public
* @return longint
*/
function GetSID()
{
$session =& $this->recallObject('Session');
return $session->GetID();
}
function DestroySession()
{
$session =& $this->recallObject('Session');
$session->Destroy();
}
/**
* Returns variable passed to the script as GET/POST/COOKIE
*
* @access public
* @param string $name Name of variable to retrieve
* @param int $default default value returned in case if varible not present
* @return mixed
*/
function GetVar($name, $default = false)
{
// $http_query =& $this->recallObject('HTTPQuery');
return isset($this->HttpQuery->_Params[$name]) ? $this->HttpQuery->_Params[$name] : $default;
}
/**
* Returns ALL variables passed to the script as GET/POST/COOKIE
*
* @access public
* @return array
*/
function GetVars()
{
return $this->HttpQuery->GetParams();
}
/**
* Set the variable 'as it was passed to the script through GET/POST/COOKIE'
*
* This could be useful to set the variable when you know that
* other objects would relay on variable passed from GET/POST/COOKIE
* or you could use SetVar() / GetVar() pairs to pass the values between different objects.<br>
*
* This method is formerly known as $this->Session->SetProperty.
* @param string $var Variable name to set
* @param mixed $val Variable value
* @access public
* @return void
*/
function SetVar($var,$val)
{
// $http_query =& $this->recallObject('HTTPQuery');
return $this->HttpQuery->Set($var,$val);
}
/**
* Deletes kHTTPQuery variable
*
* @param string $var
* @todo think about method name
*/
function DeleteVar($var)
{
return $this->HttpQuery->Remove($var);
}
/**
* Deletes Session variable
*
* @param string $var
*/
function RemoveVar($var)
{
return $this->Session->RemoveVar($var);
}
/**
* Restores Session variable to it's db version
*
* @param string $var
*/
function RestoreVar($var)
{
return $this->Session->RestoreVar($var);
}
/**
* Returns session variable value
*
* Return value of $var variable stored in Session. An optional default value could be passed as second parameter.
*
* @see SimpleSession
* @access public
* @param string $var Variable name
* @param mixed $default Default value to return if no $var variable found in session
* @return mixed
*/
function RecallVar($var,$default=false)
{
return $this->Session->RecallVar($var,$default);
}
/**
* Stores variable $val in session under name $var
*
* Use this method to store variable in session. Later this variable could be recalled.
* @see RecallVar
* @access public
* @param string $var Variable name
* @param mixed $val Variable value
*/
function StoreVar($var, $val)
{
$session =& $this->recallObject('Session');
$this->Session->StoreVar($var, $val);
}
function StoreVarDefault($var, $val)
{
$session =& $this->recallObject('Session');
$this->Session->StoreVarDefault($var, $val);
}
/**
* Links HTTP Query variable with session variable
*
* If variable $var is passed in HTTP Query it is stored in session for later use. If it's not passed it's recalled from session.
* This method could be used for making sure that GetVar will return query or session value for given
* variable, when query variable should overwrite session (and be stored there for later use).<br>
* This could be used for passing item's ID into popup with multiple tab -
* in popup script you just need to call LinkVar('id', 'current_id') before first use of GetVar('id').
* After that you can be sure that GetVar('id') will return passed id or id passed earlier and stored in session
* @access public
* @param string $var HTTP Query (GPC) variable name
* @param mixed $ses_var Session variable name
* @param mixed $default Default variable value
*/
function LinkVar($var, $ses_var = null, $default = '')
{
if (!isset($ses_var)) $ses_var = $var;
if ($this->GetVar($var) !== false) {
$this->StoreVar($ses_var, $this->GetVar($var));
}
else {
$this->SetVar($var, $this->RecallVar($ses_var, $default));
}
}
/**
* Returns variable from HTTP Query, or from session if not passed in HTTP Query
*
* The same as LinkVar, but also returns the variable value taken from HTTP Query if passed, or from session if not passed.
* Returns the default value if variable does not exist in session and was not passed in HTTP Query
*
* @see LinkVar
* @access public
* @param string $var HTTP Query (GPC) variable name
* @param mixed $ses_var Session variable name
* @param mixed $default Default variable value
* @return mixed
*/
function GetLinkedVar($var, $ses_var = null, $default = '')
{
$this->LinkVar($var, $ses_var, $default);
return $this->GetVar($var);
}
function AddBlock($name, $tpl)
{
$this->cache[$name] = $tpl;
}
/* Seems to be not used anywhere... /Kostja
function SetTemplateBody($title,$body)
{
$templates_cache =& $this->recallObject('TemplatesCache');
$templates_cache->SetTemplateBody($title,$body);
}*/
function ProcessTag($tag_data)
{
$a_tag = new Tag($tag_data,$this->Parser);
return $a_tag->DoProcessTag();
}
function ProcessParsedTag($prefix, $tag, $params)
{
$a_tag = new Tag('',$this->Parser);
$a_tag->Tag = $tag;
$a_tag->Processor = $prefix;
$a_tag->NamedParams = $params;
return $a_tag->DoProcessTag();
}
/**
* Return ADODB Connection object
*
* Returns ADODB Connection object already connected to the project database, configurable in config.php
* @access public
* @return kDBConnection
*/
function &GetADODBConnection()
{
return $this->Conn;
}
function ParseBlock($params,$pass_params=0,$as_template=false)
{
if (substr($params['name'], 0, 5) == 'html:') return substr($params['name'], 6);
return $this->Parser->ParseBlock($params, $pass_params, $as_template);
}
/**
* Returns index file, that could be passed as parameter to method, as parameter to tag and as constant or not passed at all
*
* @param string $prefix
* @param string $index_file
* @param Array $params
* @return string
*/
function getIndexFile($prefix, $index_file, &$params)
{
if (isset($params['index_file'])) {
$index_file = $params['index_file'];
unset($params['index_file']);
return $index_file;
}
if (isset($index_file)) {
return $index_file;
}
if (defined('INDEX_FILE')) {
return INDEX_FILE;
}
$cut_prefix = trim(BASE_PATH, '/').'/'.trim($prefix, '/');
return trim(preg_replace('/'.preg_quote($cut_prefix, '/').'(.*)/', '\\1', $_SERVER['PHP_SELF']), '/');
}
/**
* Return href for template
*
* @access public
* @param string $t Template path
* @var string $prefix index.php prefix - could be blank, 'admin'
*/
function HREF($t, $prefix='', $params=null, $index_file=null)
{
if(!$t) $t = $this->GetVar('t'); // moved from kMainTagProcessor->T()
if ($this->GetVar('skip_last_template')) {
$params['opener'] = 'p';
$this->SetVar('m_opener', 'p');
}
if ($t == 'incs/close_popup') {
// because this template closes the popup and we don't need popup mark here anymore
$params['m_opener'] = 's';
}
if( substr($t, -4) == '.tpl' ) $t = substr($t, 0, strlen($t) - 4 );
if ( $this->IsAdmin() && $prefix == '') $prefix = '/admin';
if ( $this->IsAdmin() && $prefix == '_FRONT_END_') $prefix = '';
$index_file = $this->getIndexFile($prefix, $index_file, $params);
$ssl = isset($params['__SSL__']) ? $params['__SSL__'] : null;
if ($ssl !== null) {
$session =& $this->recallObject('Session');
$cookie_url = $session->CookieDomain.$session->CookiePath;
if ($ssl) {
$target_url = $this->ConfigValue('SSL_URL');
}
else {
$target_url = 'http://'.DOMAIN.$this->ConfigValue('Site_Path');
}
if (!preg_match('#'.preg_quote($cookie_url).'#', $target_url)) {
$session->SetMode(smGET_ONLY);
}
}
if (getArrayValue($params, 'opener') == 'u') {
$opener_stack=$this->RecallVar('opener_stack');
if($opener_stack) {
$opener_stack=unserialize($opener_stack);
if (count($opener_stack) > 0) {
list($index_file, $env) = explode('|', $opener_stack[count($opener_stack)-1]);
$ret = $this->BaseURL($prefix, $ssl).$index_file.'?'.ENV_VAR_NAME.'='.$env;
if( getArrayValue($params,'escape') ) $ret = addslashes($ret);
return $ret;
}
else {
//define('DBG_REDIRECT', 1);
$t = $this->GetVar('t');
}
}
else {
//define('DBG_REDIRECT', 1);
$t = $this->GetVar('t');
}
}
$pass = isset($params['pass']) ? $params['pass'] : '';
$pass_events = isset($params['pass_events']) ? $params['pass_events'] : false; // pass events with url
$map_link = '';
if( isset($params['anchor']) )
{
$map_link = '#'.$params['anchor'];
unset($params['anchor']);
}
if ( isset($params['no_amp']) )
{
$params['__URLENCODE__'] = $params['no_amp'];
unset($params['no_amp']);
}
$no_rewrite = false;
if( isset($params['__NO_REWRITE__']) )
{
$no_rewrite = true;
unset($params['__NO_REWRITE__']);
}
+ // append pass through variables to each link to be build
+ $params = array_merge_recursive2($this->getPassThroughVariables(), $params);
+
if ($this->RewriteURLs($ssl) && !$no_rewrite)
{
$session =& $this->recallObject('Session');
if( $session->NeedQueryString() ) $params['sid'] = $this->GetSID();
$url = $this->BuildEnv_NEW($t, $params, $pass, $pass_events);
$ret = $this->BaseURL($prefix, $ssl).$url.$map_link;
}
else
{
$env = $this->BuildEnv($t, $params, $pass, $pass_events);
$ret = $this->BaseURL($prefix, $ssl).$index_file.'?'.$env.$map_link;
}
return $ret;
}
+ /**
+ * Returns variables with values that should be passed throught with this link + variable list
+ *
+ * @return unknown
+ */
+ function getPassThroughVariables()
+ {
+ static $cached_pass_through = null;
+
+ // because pass through is not changed during script run, then we can cache it
+ if (is_null($cached_pass_through)) {
+
+ $cached_pass_through = Array();
+ $pass_through = $this->Application->GetVar('pass_through');
+
+ if ($pass_through) {
+ // names of variables to pass to each link
+ $cached_pass_through['pass_through'] = $pass_through;
+ $pass_through = explode(',', $pass_through);
+ foreach ($pass_through as $pass_through_var) {
+ $cached_pass_through[$pass_through_var] = $this->Application->GetVar($pass_through_var);
+ }
+ }
+
+ }
+
+ return $cached_pass_through;
+ }
+
/**
* Returns sorted array of passed prefixes (to build url from)
*
* @param string $pass
* @return Array
*/
function getPassInfo($pass = 'all')
{
$pass = trim(str_replace('all', trim($this->GetVar('passed'), ','), $pass), ',');
if (!$pass) {
return Array();
}
$pass_info = array_unique( explode(',', $pass) ); // array( prefix[.special], prefix[.special] ...
sort($pass_info, SORT_STRING); // to be prefix1,prefix1.special1,prefix1.special2,prefix3.specialX
// ensure that "m" prefix is at the beginning
$main_index = array_search('m', $pass_info);
if ($main_index !== false) {
unset($pass_info[$main_index]);
array_unshift($pass_info, 'm');
}
return $pass_info;
}
function BuildEnv_NEW($t, $params, $pass = 'all', $pass_events = false)
{
// $session =& $this->recallObject('Session');
$force_admin = getArrayValue($params,'admin') || $this->GetVar('admin');
// if($force_admin) $sid = $this->GetSID();
$ret = '';
$env = '';
$encode = false;
if (isset($params['__URLENCODE__']))
{
$encode = $params['__URLENCODE__'];
unset($params['__URLENCODE__']);
}
if (isset($params['__SSL__'])) {
unset($params['__SSL__']);
}
$m_only = true;
$pass_info = $this->getPassInfo($pass);
if ($pass_info) {
if ($pass_info[0] == 'm') array_shift($pass_info);
$params['t'] = $t;
foreach($pass_info as $pass_index => $pass_element)
{
list($prefix) = explode('.', $pass_element);
$require_rewrite = $this->findModule('Var', $prefix);
if ($require_rewrite) {
// if next prefix is same as current, but with special => exclude current prefix from url
$next_prefix = getArrayValue($pass_info, $pass_index + 1);
if ($next_prefix) {
$next_prefix = substr($next_prefix, 0, strlen($prefix) + 1);
if ($prefix.'.' == $next_prefix) continue;
}
$a = $this->BuildModuleEnv_NEW($pass_element, $params, $pass_events);
if ($a) {
$ret .= '/'.$a;
$m_only = false;
}
}
else
{
$env .= ':'.$this->BuildModuleEnv($pass_element, $params, $pass_events);
}
}
$ret = $this->BuildModuleEnv_NEW('m', $params, $pass_events).$ret;
$cat_processed = isset($params['category_processed']) && $params['category_processed'];
if ($cat_processed) {
unset($params['category_processed']);
}
if (!$m_only || !$cat_processed) {
$ret = trim($ret, '/').'.html';
}
else {
$ret .= '/';
}
// $ret = trim($ret, '/').'/';
if($env) $params[ENV_VAR_NAME] = ltrim($env, ':');
}
unset($params['pass'], $params['opener'], $params['m_event']);
if ($force_admin) $params['admin'] = 1;
if( getArrayValue($params,'escape') )
{
$ret = addslashes($ret);
unset($params['escape']);
}
$ret = str_replace('%2F', '/', urlencode($ret));
$params_str = '';
$join_string = $encode ? '&' : '&amp;';
foreach ($params as $param => $value)
{
$params_str .= $join_string.$param.'='.$value;
}
$ret .= preg_replace('/^'.$join_string.'(.*)/', '?\\1', $params_str);
if ($encode) {
$ret = str_replace('\\', '%5C', $ret);
}
return $ret;
}
function BuildModuleEnv_NEW($prefix_special, &$params, $pass_events = false)
{
$event_params = Array('pass_events' => $pass_events, 'url_params' => $params);
$event = new kEvent($prefix_special.':BuildEnv', $event_params);
$this->HandleEvent($event);
$params = $event->getEventParam('url_params'); // save back unprocessed parameters
$ret = '';
if ($event->getEventParam('env_string')) {
$ret = trim( $event->getEventParam('env_string'), '/');
}
return $ret;
}
/**
* Builds env part that corresponds prefix passed
*
* @param string $prefix_special item's prefix & [special]
* @param Array $params url params
* @param bool $pass_events
*/
function BuildModuleEnv($prefix_special, &$params, $pass_events = false)
{
list($prefix) = explode('.', $prefix_special);
$query_vars = $this->getUnitOption($prefix, 'QueryString');
//if pass events is off and event is not implicity passed
if( !$pass_events && !isset($params[$prefix_special.'_event']) ) {
$params[$prefix_special.'_event'] = ''; // remove event from url if requested
//otherwise it will use value from get_var
}
if(!$query_vars) return '';
$tmp_string = Array(0 => $prefix_special);
foreach($query_vars as $index => $var_name)
{
//if value passed in params use it, otherwise use current from application
$var_name = $prefix_special.'_'.$var_name;
$tmp_string[$index] = isset( $params[$var_name] ) ? $params[$var_name] : $this->GetVar($var_name);
if ( isset($params[$var_name]) ) unset( $params[$var_name] );
}
$escaped = array();
foreach ($tmp_string as $tmp_val) {
$escaped[] = str_replace(Array('-',':'), Array('\-','\:'), $tmp_val);
}
$ret = implode('-', $escaped);
if ($this->getUnitOption($prefix, 'PortalStyleEnv') == true)
{
$ret = preg_replace('/^([a-zA-Z]+)-([0-9]+)-(.*)/','\\1\\2-\\3', $ret);
}
return $ret;
}
function BuildEnv($t, $params, $pass='all', $pass_events = false, $env_var = true)
{
$session =& $this->recallObject('Session');
$ssl = isset($params['__SSL__']) ? $params['__SSL__'] : 0;
$sid = $session->NeedQueryString() && !$this->RewriteURLs($ssl) ? $this->GetSID() : '';
if (getArrayValue($params,'admin') == 1) $sid = $this->GetSID();
$ret = '';
if ($env_var) {
$ret = ENV_VAR_NAME.'=';
}
$ret .= $sid.(constOn('INPORTAL_ENV') ? '-' : ':');
$encode = false;
if (isset($params['__URLENCODE__'])) {
$encode = $params['__URLENCODE__'];
unset($params['__URLENCODE__']);
}
if (isset($params['__SSL__'])) {
unset($params['__SSL__']);
}
$env_string = '';
$category_id = isset($params['m_cat_id']) ? $params['m_cat_id'] : $this->GetVar('m_cat_id');
$item_id = 0;
$pass_info = $this->getPassInfo($pass);
if ($pass_info) {
if ($pass_info[0] == 'm') array_shift($pass_info);
foreach ($pass_info as $pass_element) {
list($prefix) = explode('.', $pass_element);
$require_rewrite = $this->findModule('Var', $prefix);
if ($require_rewrite) {
$item_id = isset($params[$pass_element.'_id']) ? $params[$pass_element.'_id'] : $this->GetVar($pass_element.'_id');
}
$env_string .= ':'.$this->BuildModuleEnv($pass_element, $params, $pass_events);
}
}
if (strtolower($t) == '__default__') {
// to put category & item templates into cache
$filename = $this->getFilename('c', $category_id);
if ($item_id) {
$t = $this->getCache('item_templates', $category_id);
}
elseif ($category_id) {
$t = $this->getCache('category_templates', $category_id);
}
else {
$t = 'index';
}
}
$ret .= $t.':'.$this->BuildModuleEnv('m', $params, $pass_events).$env_string;
unset($params['pass']);
unset($params['opener']);
unset($params['m_event']);
if ($this->GetVar('admin') && !isset($params['admin'])) {
$params['admin'] = 1;
}
if( getArrayValue($params,'escape') )
{
$ret = addslashes($ret);
unset($params['escape']);
}
$join_string = $encode ? '&' : '&amp;';
$params_str = '';
foreach ($params as $param => $value)
{
$params_str .= $join_string.$param.'='.$value;
}
$ret .= $params_str;
if ($encode) {
$ret = str_replace('\\', '%5C', $ret);
}
return $ret;
}
function BaseURL($prefix='', $ssl=null)
{
if ($ssl === null) {
return PROTOCOL.SERVER_NAME.(defined('PORT')?':'.PORT : '').rtrim(BASE_PATH, '/').$prefix.'/';
}
else {
if ($ssl) {
return rtrim( $this->ConfigValue('SSL_URL'), '/').$prefix.'/';
}
else {
return 'http://'.DOMAIN.(defined('PORT')?':'.PORT : '').rtrim( $this->ConfigValue('Site_Path'), '/').$prefix.'/';
}
}
}
function Redirect($t='', $params=null, $prefix='', $index_file=null)
{
if ($t == '' || $t === true) $t = $this->GetVar('t');
// pass prefixes and special from previous url
$js_redirect = getArrayValue($params, 'js_redirect');
if( isset($params['js_redirect']) ) unset($params['js_redirect']);
if (!isset($params['pass'])) $params['pass'] = 'all';
if ($this->GetVar('ajax') == 'yes' && $t == $this->GetVar('t')) {
// redirects to the same template as current
$params['ajax'] = 'yes';
}
$params['__URLENCODE__'] = 1;
$location = $this->HREF($t, $prefix, $params, $index_file);
$a_location = $location;
$location = "Location: $location";
//echo " location : $location <br>";
if ($this->isDebugMode() && constOn('DBG_REDIRECT')) {
$this->Debugger->appendTrace();
echo "<b>Debug output above!!!</b> Proceed to redirect: <a href=\"$a_location\">$a_location</a><br>";
}
else {
if ($js_redirect) {
$this->SetVar('t', 'redirect');
$this->SetVar('redirect_to_js', addslashes($a_location) );
$this->SetVar('redirect_to', $a_location);
return true;
}
else {
if ($this->GetVar('ajax') == 'yes' && $t != $this->GetVar('t')) {
// redirection to other then current template during ajax request
echo '#redirect#'.$a_location;
}
elseif (headers_sent() != '') {
// some output occured -> redirect using javascript
echo '<script type="text/javascript">window.location.href = \''.$a_location.'\';</script>';
}
else {
// no output before -> redirect using HTTP header
// header('HTTP/1.1 302 Found');
header("$location");
}
}
}
$buffer_content = ob_get_clean();
echo $this->UseOutputCompression() ? gzencode($buffer_content, DBG_COMPRESSION_LEVEL) : $buffer_content;
$session =& $this->recallObject('Session');
$session->SaveData();
$this->SaveBlocksCache();
exit;
}
function Phrase($label)
{
return $this->Phrases->GetPhrase($label);
}
/**
* Replace language tags in exclamation marks found in text
*
* @param string $text
* @param bool $force_escape force escaping, not escaping of resulting string
* @return string
* @access public
*/
function ReplaceLanguageTags($text, $force_escape=null)
{
// !!!!!!!!
// if( !is_object($this->Phrases) ) $this->Debugger->appendTrace();
return $this->Phrases->ReplaceLanguageTags($text,$force_escape);
}
/**
* Checks if user is logged in, and creates
* user object if so. User object can be recalled
* later using "u" prefix. Also you may
* get user id by getting "u_id" variable.
*
* @access private
*/
function ValidateLogin()
{
$session =& $this->recallObject('Session');
$user_id = $session->GetField('PortalUserId');
if (!$user_id && $user_id != -1) $user_id = -2;
$this->SetVar('u_id', $user_id);
$this->StoreVar('user_id', $user_id);
if ($this->GetVar('expired') == 1) {
$user =& $this->recallObject('u');
$user->SetError('ValidateLogin', 'session_expired', 'la_text_sess_expired');
}
if (($user_id != -2) && constOn('DBG_REQUREST_LOG') ) {
$http_query =& $this->recallObject('HTTPQuery');
$http_query->writeRequestLog(DBG_REQUREST_LOG);
}
}
function LoadCache() {
$cache_key = $this->GetVar('t').$this->GetVar('m_theme').$this->GetVar('m_lang').$this->IsAdmin();
$query = sprintf("SELECT PhraseList, ConfigVariables FROM %s WHERE Template = %s",
TABLE_PREFIX.'PhraseCache',
$this->Conn->Qstr(md5($cache_key)));
$res = $this->Conn->GetRow($query);
if ($res) {
$this->Caches['PhraseList'] = $res['PhraseList'] ? explode(',', $res['PhraseList']) : array();
$config_ids = $res['ConfigVariables'] ? explode(',', $res['ConfigVariables']) : array();
$config_ids = array_diff($config_ids, $this->Caches['ConfigVariables']);
}
else {
$config_ids = array();
}
$this->Caches['ConfigVariables'] = $config_ids;
$this->ConfigCacheIds = $config_ids;
}
function UpdateCache()
{
$update = false;
//something changed
$update = $update || $this->Phrases->NeedsCacheUpdate();
$update = $update || (count($this->ConfigCacheIds) && $this->ConfigCacheIds != $this->Caches['ConfigVariables']);
if ($update) {
$cache_key = $this->GetVar('t').$this->GetVar('m_theme').$this->GetVar('m_lang').$this->IsAdmin();
$query = sprintf("REPLACE %s (PhraseList, CacheDate, Template, ConfigVariables)
VALUES (%s, %s, %s, %s)",
TABLE_PREFIX.'PhraseCache',
$this->Conn->Qstr(join(',', $this->Phrases->Ids)),
adodb_mktime(),
$this->Conn->Qstr(md5($cache_key)),
$this->Conn->qstr(implode(',', array_unique($this->ConfigCacheIds))));
$this->Conn->Query($query);
}
}
function InitConfig()
{
if (isset($this->Caches['ConfigVariables']) && count($this->Caches['ConfigVariables']) > 0) {
$this->ConfigHash = array_merge($this->ConfigHash, $this->Conn->GetCol(
'SELECT VariableValue, VariableName FROM '.TABLE_PREFIX.'ConfigurationValues
WHERE VariableId IN ('.implode(',', $this->Caches['ConfigVariables']).')', 'VariableName'));
}
}
/**
* Returns configuration option value by name
*
* @param string $name
* @return string
*/
function ConfigValue($name)
{
$res = isset($this->ConfigHash[$name]) ? $this->ConfigHash[$name] : false;
if ($res !== false) return $res;
$res = $this->Conn->GetRow('SELECT VariableId, VariableValue FROM '.TABLE_PREFIX.'ConfigurationValues WHERE VariableName = '.$this->Conn->qstr($name));
if ($res) {
$this->ConfigHash[$name] = $res['VariableValue'];
$this->ConfigCacheIds[] = $res['VariableId'];
return $res['VariableValue'];
}
return false;
}
function UpdateConfigCache()
{
if ($this->ConfigCacheIds) {
}
}
/**
* Allows to process any type of event
*
* @param kEvent $event
* @access public
* @author Alex
*/
function HandleEvent(&$event, $params=null, $specificParams=null)
{
if ( isset($params) ) {
$event = new kEvent( $params, $specificParams );
}
if (!isset($this->EventManager)) {
$this->EventManager =& $this->recallObject('EventManager');
}
$this->EventManager->HandleEvent($event);
}
/**
* Registers new class in the factory
*
* @param string $real_class Real name of class as in class declaration
* @param string $file Filename in what $real_class is declared
* @param string $pseudo_class Name under this class object will be accessed using getObject method
* @param Array $dependecies List of classes required for this class functioning
* @access public
* @author Alex
*/
function registerClass($real_class, $file, $pseudo_class = null, $dependecies = Array() )
{
$this->Factory->registerClass($real_class, $file, $pseudo_class, $dependecies);
}
/**
* Add $class_name to required classes list for $depended_class class.
* All required class files are included before $depended_class file is included
*
* @param string $depended_class
* @param string $class_name
* @author Alex
*/
function registerDependency($depended_class, $class_name)
{
$this->Factory->registerDependency($depended_class, $class_name);
}
/**
* Registers Hook from subprefix event to master prefix event
*
* @param string $hookto_prefix
* @param string $hookto_special
* @param string $hookto_event
* @param string $mode
* @param string $do_prefix
* @param string $do_special
* @param string $do_event
* @param string $conditional
* @access public
* @todo take care of a lot parameters passed
* @author Kostja
*/
function registerHook($hookto_prefix, $hookto_special, $hookto_event, $mode, $do_prefix, $do_special, $do_event, $conditional)
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->registerHook($hookto_prefix, $hookto_special, $hookto_event, $mode, $do_prefix, $do_special, $do_event, $conditional);
}
/**
* Allows one TagProcessor tag act as other TagProcessor tag
*
* @param Array $tag_info
* @author Kostja
*/
function registerAggregateTag($tag_info)
{
$aggregator =& $this->recallObject('TagsAggregator', 'kArray');
$aggregator->SetArrayValue($tag_info['AggregateTo'], $tag_info['AggregatedTagName'], Array($tag_info['LocalPrefix'], $tag_info['LocalTagName'], getArrayValue($tag_info, 'LocalSpecial')));
}
/**
* Returns object using params specified,
* creates it if is required
*
* @param string $name
* @param string $pseudo_class
* @param Array $event_params
* @return Object
* @author Alex
*/
function &recallObject($name,$pseudo_class=null,$event_params=Array())
{
$result =& $this->Factory->getObject($name, $pseudo_class, $event_params);
return $result;
}
/**
* Returns object using Variable number of params,
* all params starting with 4th are passed to object consturctor
*
* @param string $name
* @param string $pseudo_class
* @param Array $event_params
* @return Object
* @author Alex
*/
function &recallObjectP($name,$pseudo_class=null,$event_params=Array())
{
$func_args = func_get_args();
$result =& ref_call_user_func_array( Array(&$this->Factory, 'getObjectP'), $func_args );
return $result;
}
/**
* Returns tag processor for prefix specified
*
* @param string $prefix
* @return kDBTagProcessor
*/
function &recallTagProcessor($prefix)
{
$result =& $this->recallObject($prefix.'_TagProcessor');
return $result;
}
/**
* Checks if object with prefix passes was already created in factory
*
* @param string $name object presudo_class, prefix
* @return bool
* @author Kostja
*/
function hasObject($name)
{
return isset($this->Factory->Storage[$name]);
}
/**
* Removes object from storage by given name
*
* @param string $name Object's name in the Storage
* @author Kostja
*/
function removeObject($name)
{
$this->Factory->DestroyObject($name);
}
/**
* Get's real class name for pseudo class,
* includes class file and creates class
* instance
*
* @param string $pseudo_class
* @return Object
* @access public
* @author Alex
*/
function &makeClass($pseudo_class)
{
$func_args = func_get_args();
$result =& ref_call_user_func_array( Array(&$this->Factory, 'makeClass'), $func_args);
return $result;
}
/**
* Checks if application is in debug mode
*
* @param bool $check_debugger check if kApplication debugger is initialized too, not only for defined DEBUG_MODE constant
* @return bool
* @author Alex
* @access public
*/
function isDebugMode($check_debugger = true)
{
$debug_mode = defined('DEBUG_MODE') && DEBUG_MODE;
if($check_debugger)
{
$debug_mode = $debug_mode && is_object($this->Debugger);
}
return $debug_mode;
}
/**
* Checks if it is admin
*
* @return bool
* @author Alex
*/
function IsAdmin()
{
return constOn('ADMIN');
}
/**
* Apply url rewriting used by mod_rewrite or not
*
* @param bool $ssl Force ssl link to be build
* @return bool
*/
function RewriteURLs($ssl = false)
{
// case #1,#4:
// we want to create https link from http mode
// we want to create https link from https mode
// conditions: ($ssl || PROTOCOL == 'https://') && $this->ConfigValue('UseModRewriteWithSSL')
// case #2,#3:
// we want to create http link from https mode
// we want to create http link from http mode
// conditions: !$ssl && (PROTOCOL == 'https://' || PROTOCOL == 'http://')
$allow_rewriting =
(!$ssl && (PROTOCOL == 'https://' || PROTOCOL == 'http://')) // always allow mod_rewrite for http
|| // or allow rewriting for redirect TO httpS or when already in httpS
(($ssl || PROTOCOL == 'https://') && $this->ConfigValue('UseModRewriteWithSSL')); // but only if it's allowed in config!
return constOn('MOD_REWRITE') && $allow_rewriting;
}
/**
* Reads unit (specified by $prefix)
* option specified by $option
*
* @param string $prefix
* @param string $option
* @param mixed $default
* @return string
* @access public
* @author Alex
*/
function getUnitOption($prefix, $option, $default = false)
{
/*if (!isset($this->UnitConfigReader)) {
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
}*/
return $this->UnitConfigReader->getUnitOption($prefix, $option, $default);
}
/**
* Set's new unit option value
*
* @param string $prefix
* @param string $name
* @param string $value
* @author Alex
* @access public
*/
function setUnitOption($prefix, $option, $value)
{
// $unit_config_reader =& $this->recallObject('kUnitConfigReader');
return $this->UnitConfigReader->setUnitOption($prefix,$option,$value);
}
/**
* Read all unit with $prefix options
*
* @param string $prefix
* @return Array
* @access public
* @author Alex
*/
function getUnitOptions($prefix)
{
// $unit_config_reader =& $this->recallObject('kUnitConfigReader');
return $this->UnitConfigReader->getUnitOptions($prefix);
}
/**
* Returns true if config exists and is allowed for reading
*
* @param string $prefix
* @return bool
*/
function prefixRegistred($prefix)
{
/*if (!isset($this->UnitConfigReader)) {
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
}*/
return $this->UnitConfigReader->prefixRegistred($prefix);
}
/**
* Splits any mixing of prefix and
* special into correct ones
*
* @param string $prefix_special
* @return Array
* @access public
* @author Alex
*/
function processPrefix($prefix_special)
{
return $this->Factory->processPrefix($prefix_special);
}
/**
* Set's new event for $prefix_special
* passed
*
* @param string $prefix_special
* @param string $event_name
* @access public
*/
function setEvent($prefix_special,$event_name)
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->setEvent($prefix_special,$event_name);
}
/**
* SQL Error Handler
*
* @param int $code
* @param string $msg
* @param string $sql
* @return bool
* @access private
* @author Alex
*/
function handleSQLError($code, $msg, $sql)
{
if ( isset($this->Debugger) )
{
$errorLevel = constOn('DBG_SQL_FAILURE') && !defined('IS_INSTALL') ? E_USER_ERROR : E_USER_WARNING;
$this->Debugger->dumpVars($_REQUEST);
$this->Debugger->appendTrace();
$error_msg = '<span class="debug_error">'.$msg.' ('.$code.')</span><br><a href="javascript:$Debugger.SetClipboard(\''.htmlspecialchars($sql).'\');"><b>SQL</b></a>: '.$this->Debugger->formatSQL($sql);
$long_id = $this->Debugger->mapLongError($error_msg);
trigger_error( substr($msg.' ('.$code.') ['.$sql.']',0,1000).' #'.$long_id, $errorLevel);
return true;
}
else
{
//$errorLevel = constOn('IS_INSTALL') ? E_USER_WARNING : E_USER_ERROR;
$errorLevel = E_USER_WARNING;
trigger_error('<b>SQL Error</b> in sql: '.$sql.', code <b>'.$code.'</b> ('.$msg.')', $errorLevel);
/*echo '<b>xProcessing SQL</b>: '.$sql.'<br>';
echo '<b>Error ('.$code.'):</b> '.$msg.'<br>';*/
return $errorLevel == E_USER_ERROR ? false : true;
}
}
/**
* Default error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param Array $errcontext
*/
function handleError($errno, $errstr, $errfile = '', $errline = '', $errcontext = '')
{
if( constOn('SILENT_LOG') )
{
$fp = fopen(FULL_PATH.'/silent_log.txt','a');
$time = adodb_date('d/m/Y H:i:s');
fwrite($fp, '['.$time.'] #'.$errno.': '.strip_tags($errstr).' in ['.$errfile.'] on line '.$errline."\n");
fclose($fp);
}
if( !$this->errorHandlers ) return true;
$i = 0; // while (not foreach) because it is array of references in some cases
$eh_count = count($this->errorHandlers);
while($i < $eh_count)
{
if( is_array($this->errorHandlers[$i]) )
{
$object =& $this->errorHandlers[$i][0];
$method = $this->errorHandlers[$i][1];
$object->$method($errno, $errstr, $errfile, $errline, $errcontext);
}
else
{
$function = $this->errorHandlers[$i];
$function($errno, $errstr, $errfile, $errline, $errcontext);
}
$i++;
}
}
/**
* Returns & blocks next ResourceId available in system
*
* @return int
* @access public
* @author Alex
*/
function NextResourceId()
{
$table_name = TABLE_PREFIX.'IdGenerator';
$this->Conn->Query('LOCK TABLES '.$table_name.' WRITE');
$this->Conn->Query('UPDATE '.$table_name.' SET lastid = lastid + 1');
$id = $this->Conn->GetOne('SELECT lastid FROM '.$table_name);
if($id === false)
{
$this->Conn->Query('INSERT INTO '.$table_name.' (lastid) VALUES (2)');
$id = 2;
}
$this->Conn->Query('UNLOCK TABLES');
return $id - 1;
}
/**
* Returns main prefix for subtable prefix passes
*
* @param string $current_prefix
* @return string
* @access public
* @author Kostja
*/
function GetTopmostPrefix($current_prefix)
{
while ( $parent_prefix = $this->getUnitOption($current_prefix, 'ParentPrefix') )
{
$current_prefix = $parent_prefix;
}
return $current_prefix;
}
function &EmailEventAdmin($email_event_name, $to_user_id = -1, $send_params = false)
{
return $this->EmailEvent($email_event_name, 1, $to_user_id, $send_params);
}
function &EmailEventUser($email_event_name, $to_user_id = -1, $send_params = false)
{
return $this->EmailEvent($email_event_name, 0, $to_user_id, $send_params);
}
function &EmailEvent($email_event_name, $email_event_type, $to_user_id = -1, $send_params = false)
{
$event = new kEvent('emailevents:OnEmailEvent');
$event->setEventParam('EmailEventName', $email_event_name);
$event->setEventParam('EmailEventToUserId', $to_user_id);
$event->setEventParam('EmailEventType', $email_event_type);
if ($send_params){
$event->setEventParam('DirectSendParams', $send_params);
}
$this->HandleEvent($event);
return $event;
}
function LoggedIn()
{
$user_id = $this->Application->RecallVar('user_id');
// $user =& $this->recallObject('u');
// $user_id = $user->GetID();
$ret = $user_id > 0;
if ($this->IsAdmin() && ($user_id == -1)) {
$ret = true;
}
return $ret;
}
/**
* Check current user permissions based on it's group permissions in specified category
*
* @param string $name permission name
* @param int $cat_id category id, current used if not specified
* @param int $type permission type {1 - system, 0 - per category}
* @return int
*/
function CheckPermission($name, $type = 1, $cat_id = null)
{
$perm_helper =& $this->recallObject('PermissionsHelper');
return $perm_helper->CheckPermission($name, $type, $cat_id);
}
/**
* Set's any field of current visit
*
* @param string $field
* @param mixed $value
*/
function setVisitField($field, $value)
{
$visit =& $this->recallObject('visits');
$visit->SetDBField($field, $value);
$visit->Update();
}
/**
* Allows to check if in-portal is installed
*
* @return bool
*/
function isInstalled()
{
return $this->InitDone && (count($this->ModuleInfo) > 0);
}
/**
* Allows to determine if module is installed & enabled
*
* @param string $module_name
* @return bool
*/
function isModuleEnabled($module_name)
{
return $this->findModule('Name', $module_name);
}
function reportError($class, $method)
{
$this->Debugger->appendTrace();
trigger_error('depricated method <b>'.$class.'->'.$method.'(...)</b>', E_USER_ERROR);
}
/**
* Get temp table name
*
* @param string $table
* @return string
*/
function GetTempName($table)
{
return TABLE_PREFIX.'ses_'.$this->GetSID().'_edit_'.$table;
}
function GetTempTablePrefix()
{
return TABLE_PREFIX.'ses_'.$this->GetSID().'_edit_';
}
function IsTempTable($table)
{
return strpos($table, TABLE_PREFIX.'ses_'.$this->GetSID().'_edit_') !== false;
}
/**
* Return live table name based on temp table name
*
* @param string $temp_table
* @return string
*/
function GetLiveName($temp_table)
{
if( preg_match('/'.TABLE_PREFIX.'ses_'.$this->GetSID().'_edit_(.*)/',$temp_table,$rets) )
{
return $rets[1];
}
else
{
return $temp_table;
}
}
function CheckProcessors($processors)
{
foreach ($processors as $a_processor)
{
if (!isset($this->CachedProcessors[$a_processor])) {
$this->CachedProcessors[$a_processor] =& $this->recallObject($a_processor.'_TagProcessor');
}
}
}
function TimeZoneAdjustment($time_zone=null)
{
$target_zone = isset($time_zone) ? $time_zone : $this->ConfigValue('Config_Site_Time');
return 3600 * ($target_zone - $this->ConfigValue('Config_Server_Time'));
}
function ApplicationDie($message = '')
{
$message = ob_get_clean().$message;
if ($this->isDebugMode()) {
$message .= $this->Debugger->printReport(true);
}
echo $this->UseOutputCompression() ? gzencode($message, DBG_COMPRESSION_LEVEL) : $message;
exit;
}
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.155.2/core/kernel/application.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.155.2.12
\ No newline at end of property
+1.155.2.13
\ No newline at end of property

Event Timeline