Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sun, Feb 2, 12:00 PM

in-portal

Index: branches/RC/kernel/include/modules.php
===================================================================
--- branches/RC/kernel/include/modules.php (revision 9388)
+++ branches/RC/kernel/include/modules.php (revision 9389)
@@ -1,1021 +1,1021 @@
<?php
/* List of installed modules and module-specific variables
Copyright 2002, Intechnic Corporation, All rights reserved
*/
$ado =& GetADODBConnection();
$application =& kApplication::Instance();
define('SESSION_COOKIE_NAME', $application->Session->CookieName);
/*$session_cookie_name = $ado->GetOne('SELECT VariableValue FROM '.$g_TablePrefix.'ConfigurationValues WHERE VariableName = "SessionCookieName"');
define('SESSION_COOKIE_NAME', $session_cookie_name ? $session_cookie_name : 'sid');
*/
set_cookie('cookies_on', '1', adodb_mktime() + 31104000);
// if branches that uses if($mod_prefix) or like that will never be executed
// due global variable $mod_prefix is never defined
$ExtraVars = array();
function ParseEnv()
{
global $env, $var_list, $mod_prefix,$objSession, $SessionQueryString;
/* parse individual sections */
$env = GetVar('env');
if (!$env)
{
$var_list['t'] = 'index';
if (is_array($mod_prefix))
{
foreach($mod_prefix as $module_prefix => $module_name)
{
$parser_name = $module_prefix.'_ParseEnv';
if( function_exists($parser_name) ) $parser_name();
}
}
}
else
{
$env_sections = explode(':', $env);
$main = array_shift($env_sections);
if($main)
{
list($sid, $template) = explode('-', $main, 2);
if(!$SessionQueryString)
{
if (!$sid || $sid == '_')
{
if ($sid != '_') $sid = $_COOKIE[SESSION_COOKIE_NAME];
}
else
{
$SessionQueryString = true;
}
}
$var_list['sid'] = $sid;
$var_list['t'] = $template;
if( getArrayValue($_GET, 'dest') ) $var_list['dest'] = $_GET['dest'];
}
foreach ($env_sections as $env_section)
{
$env_section = preg_replace("/^([a-zA-Z]+)([0-9]+)-(.*)/", "$1-$2-$3", $env_section);
$pieces = explode('-', $env_section);
$parser_name = $pieces[0].'_ParseEnv';
if( function_exists($parser_name) )
{
$env_section = preg_replace('/^([a-zA-Z]+)-([0-9]+)-(.*)/','\\1\\2-\\3', $env_section);
$parser_name($env_section);
}
}
}
if(!$SessionQueryString) $var_list['sid'] = $_COOKIE[SESSION_COOKIE_NAME];
}
function LoadEnv()
{
global $env, $var_list, $mod_prefix,$objSession;
$env = $_GET["env"];
// echo "Loading Variables..<br>\n";
if ($env != "")
{
$envsections = explode(":", $env);
foreach($mod_prefix as $key => $value)
{
if(strlen($key))
{
$parsed=FALSE;
for($i=1; $i<sizeof($envsections); $i++)
{
$pieces = explode("-", $envsections[$i]);
if(substr($pieces[0],0,strlen($key))==$key)
{
$parsed=TRUE;
break;
}
}
if(!$parsed)
{
$parser_name = $key . "_LoadEnv";
//echo $parser_name;
if(function_exists($parser_name))
{
$parser_name();
}
}
else
{
$parser_name = $key . "_SaveEnv";
//echo $parser_name;
if(function_exists($parser_name))
{
$parser_name($envsections[$i]);
}
}
}
}
}
}
function BuildEnv($mod_prefix = false)
{
global $var_list,$m_var_list, $var_list_update, $mod_prefix, $objSession, $objConfig,
$ExtraVars, $objThemes, $CurrentTheme, $SessionQueryString, $FrontEnd;
static $theme;
$env = "";
//echo "Query String: $SessionQueryString<br>\n";
if(($objConfig->Get("CookieSessions")==0 || !$FrontEnd || ($objConfig->Get("CookieSessions")==2 && $SessionQueryString==TRUE)))
{
if(!$objSession->UseTempKeys)
{
$sessionkey = $objSession->GetSessionKey();
}
else
$sessionkey = $objSession->Get("CurrentTempKey");
$env = $sessionkey;
}
$env .= "-";
if (isset($var_list_update["t"]))
{
if($var_list_update["t"]=="_referer_")
{
$var_list_update["t"] =$objSession->GetVariable("Template_Referer");
}
$t = $var_list_update["t"];
if (substr($t, 0, strlen('kernel4:')) == 'kernel4:')
{
$t = substr($t, strlen('kernel4:'));
$env .= $t;
}
else {
if(!is_numeric($t))
{
if(!is_object($theme))
$theme = $objThemes->GetItem($m_var_list["theme"]);
$id = $theme->GetTemplateId($t);
$var_list_update["t"] = $id;
}
$env .= $var_list_update["t"];
}
}
else
{
$t = isset($var_list['t']) ? $var_list['t'] : '';
if(!is_numeric($t))
{
if(!is_object($theme))
$theme = $objThemes->GetItem($m_var_list["theme"]);
$id = $theme->GetTemplateId($t);
$t = $id;
}
$env .= $t;
}
if(is_array($mod_prefix))
{
foreach($mod_prefix as $key => $value)
{
$builder_name = $key . "_BuildEnv";
if(function_exists($builder_name))
{
if($key == 'm')
{
$GLOBALS[$key.'_var_list_update']['test'] = 'test';
}
$env .= $builder_name();
}
}
}
$extra = "";
$keys = array_keys($ExtraVars);
if(is_array($keys))
{
for($i=0;$i<count($keys);$i++)
{
$key = $keys[$i];
$e = "&".$key."=".$ExtraVars[$key];
$extra .= $e;
$e = "";
}
}
$env .= $extra;
return $env;
}
function BuildEnv_NEW($mod_prefix = false)
{
global $var_list, $var_list_update, $mod_prefix, $objSession;
$t = getArrayValue($var_list_update, 't') ? $var_list_update['t'] : $var_list['t'];
if($t == '_referer_') $t = $objSession->GetVariable('Template_Referer');
if ( substr($t, 0, strlen('kernel4:') ) == 'kernel4:' ) $t = substr($t, strlen('kernel4:') );
$url_params = Array('t' => $t);
// sicne 1.3.0 the category is not passed by default when mod_rewrite is on
// enable pass category for module templates (they usually need it) and suggest_cat.
// platform templates usually do not need category
if (
preg_match('/^inlink|^inbulletin|^innews/', $t) ||
in_array(preg_replace('/\.tpl$/', '', $t), array('suggest_cat'))
) {
$url_params['pass_category'] = 1;
}
$app =& kApplication::Instance();
$app->SetVar('prefixes_passed', Array() );
if( is_array($mod_prefix) )
{
foreach($mod_prefix as $key => $value)
{
$builder_name = $key.'_BuildEnv_NEW';
if( function_exists($builder_name) )
{
if($key == 'm')
{
$GLOBALS[$key.'_var_list_update']['test'] = 'test';
}
$url_params = array_merge_recursive2($url_params, $builder_name() );
}
}
}
$url_params['pass'] = implode( ',', $app->GetVar('prefixes_passed') );
return $url_params;
}
function CategoryActionFunc($basename,$CatList)
{
global $mod_prefix;
foreach($mod_prefix as $key => $value)
{
$function_name = $key."_".$basename;
if(function_exists($function_name))
{
$function_name($CatList);
}
}
}
function RegisterEnv($Var,$Value)
{
global $ExtraVars;
$ExtraVars[$Var] = $Value;
}
function UnregisterEnv($Var)
{
global $ExtraVars;
unset($ExtraVars[$Var]);
}
function ModuleTagPrefix($name)
{
global $modules_loaded;
$ret = "";
foreach($modules_loaded as $prefix=>$mod_name)
{
if($name==$mod_name)
{
$ret = $prefix;
break;
}
}
return $ret;
}
function ModuleEnabled($name)
{
global $template_path;
$a = array_keys($template_path);
if(in_array($name,$a))
return TRUE;
return FALSE;
}
function GetModuleArray($array_name="mod_prefix")
{
switch($array_name)
{
case "mod_prefix":
global $mod_prefix;
return $mod_prefix;
break;
case "admin":
global $mod_prefix, $modules_loaded;
$mod = array();
if(is_array($mod_prefix) && is_array($modules_loaded))
{
foreach ($mod_prefix as $key=>$value)
{
if($key != 'bbcat' && _ModuleLicensed($modules_loaded[$key]) || $key=="m")
{
$mod[$key] = $value;
}
}
}
return $mod;
break;
case "loaded":
global $modules_loaded;
return $modules_loaded;
break;
case "template":
global $template_path;
return $template_path;
case "rootcat":
global $mod_root_cats;
return $mod_root_cats;
break;
}
}
function admin_login()
{
global $objSession,$login_error, $objConfig,$g_Allow,$g_Deny;
// echo "<pre>"; print_r($objSession); echo "</pre>";
if( GetVar('help_usage') == 'install' ) return true;
$env_arr = explode('-', $_GET['env']);
$get_session_key = $env_arr[0];
$admin_login = isset($_POST['adminlogin']) && $_POST['adminlogin'];
if(!$objSession->ValidSession()) { // || ($objSession->GetSessionKey() != $get_session_key && !$admin_login)
if( isset($_GET['expired']) && ($_GET['expired'] == 1) )
$login_error = admin_language("la_text_sess_expired");
return FALSE;
//echo "Expired<br>";
}
if ($objSession->HasSystemPermission("ADMIN") == 1)
return TRUE;
if(count($_POST)==0 || $_POST["adminlogin"]!=1)
return FALSE;
$login=$_POST["login"];
$password = $_POST["password"];
if (strlen($login) && strlen($password))
{
if(!_IpAccess($_SERVER['REMOTE_ADDR'],$g_Allow,$g_Deny))
{
$login_error = admin_language("la_text_address_denied");
return FALSE;
}
$valid = $objSession->Login($login, md5($password));
$hasperm = ($objSession->HasSystemPermission("ADMIN") == 1);
if (($login=="root" || $hasperm) && $valid)
{
if(_ValidateModules())
{
return TRUE;
}
else
$login_error = "Missing or invalid In-Portal License";
}
else
{
if(!$hasperm && $valid)
{
$login_error = admin_language("la_text_nopermissions");
}
else
{
$login_error = admin_language("la_Text_Access_Denied");
}
return FALSE;
}
}
else
{
if(!strlen($login))
{
$login_error = admin_language("la_Text_Missing_Username");
}
else
if(!strlen($password))
$login_error = admin_language("la_Text_Missing_Password");
return FALSE;
}
}
#---------------------------------------------------------------------------
function _EnableCookieSID()
{
global $var_list, $objConfig;
if((!$_COOKIE[SESSION_COOKIE_NAME] && $objConfig->Get("CookieSessions")>0 && strlen($var_list["sid"])<2 && !headers_sent())
|| strlen($_COOKIE[SESSION_COOKIE_NAME]) > 0)
{
return TRUE;
}
else
return FALSE;
}
function _IsSpider($UserAgent)
{
global $robots, $pathtoroot;
$lines = file($pathtoroot.'kernel/include/robots_list.txt');
if(!is_array($robots))
{
$robots = array();
for($i=0;$i<count($lines);$i++)
{
$l = $lines[$i];
$p = explode("\t",$l,3);
$robots[] = $p[2];
}
}
return in_array($UserAgent,$robots);
}
function _StripDomainHost($d)
{
$dotcount = substr_count($d,".");
if($dotcount==3)
{
$IsIp = TRUE;
for($x=0;$x<strlen($d);$x++)
{
if(!is_numeric(substr($d,$x,1)) && substr($d,$x,1)!=".")
{
$IsIp = FALSE;
break;
}
}
}
if($dotcount>1 && !$IsIp)
{
$p = explode(".",$d);
$ret = $p[count($p)-2].".".$p[count($p)-1];
}
else
$ret = $d;
return $ret;
}
function _MatchIp($ip1,$ip2)
{
$matched = TRUE;
$ip = explode(".",$ip1);
$MatchIp = explode(".",$ip2);
for($i=0;$i<count($ip);$i++)
{
if($i==count($MatchIp))
break;
if(trim($ip[$i]) != trim($MatchIp[$i]) || trim($ip[$i])=="*")
{
$matched=FALSE;
break;
}
}
return $matched;
}
function _IpAccess($IpAddress,$AllowList,$DenyList)
{
$allowed = explode(",",$AllowList);
$denied = explode(",",$DenyList);
$MatchAllowed = FALSE;
for($x=0;$x<count($allowed);$x++)
{
$ip = explode(".",$allowed[$x]);
$MatchAllowed = _MatchIp($IpAddress,$allowed[$x]);
if($MatchAllowed)
break;
}
$MatchDenied = FALSE;
for($x=0;$x<count($denied);$x++)
{
$ip = explode(".",$denied[$x]);
$MatchDenied = _MatchIp($IpAddress,$denied[$x]);
if($MatchDenied)
break;
}
$Result = (($MatchAllowed && !$MatchDenied) || (!$MatchAllowed && !$MatchDenied) ||
($MatchAllowed && $MatchDenied));
return $Result;
}
function _ValidateModules()
{
global $i_Keys, $objConfig, $g_License;
$lic = base64_decode($g_License);
_ParseLicense($lic);
$modules = array();
//echo "License: ".$lic."<br>";
$domain = _GetDomain();
//echo "Domain: ".$domain."<br>";
if(!_IsLocalSite($domain))
{
$domain = _StripDomainHost($domain);
//echo "New domain: $domain<br>";
// echo "<pre>"; print_r($i_Keys); echo "</pre>";
for($x=0;$x<count($i_Keys);$x++)
{
$key = $i_Keys[$x];
if(strlen(stristr($key["domain"],$domain)))
{
$modules = explode(",",$key["mod"]);
//echo "Modules: $modules";
}
}
if(count($modules)>0)
{
return TRUE;
}
}
else
return TRUE;
return FALSE;
}
function _ModuleLicensed($name)
{
global $i_Keys, $objConfig, $pathtoroot;
$vars = parse_portal_ini($pathtoroot.'config.php');
// globalize vars from config (theese vars are already present, why to do this again?)
foreach ($vars as $config_key => $config_value) {
$GLOBALS['g_'.$config_key] = $config_value;
}
$lic = base64_decode($GLOBALS['g_License']);
_ParseLicense($lic);
$modules = array();
if(!_IsLocalSite(_GetDomain()))
{
for($x=0;$x<count($i_Keys);$x++)
{
$key = $i_Keys[$x];
if(strlen(stristr(_GetDomain(),$key["domain"])))
{
//echo "ok<br>";
$modules = explode(",",$key["mod"]);
}
}
//print_pre($modules);
if(in_array($name,$modules)) {
//echo "ok<br>";
return TRUE;
}
}
else {
return TRUE;
}
return FALSE;
}
function _GetDomain()
{
global $objConfig, $g_Domain;
if($objConfig->Get("DomainDetect"))
{
$d = $_SERVER['HTTP_HOST'];
}
else
$d = $g_Domain;
return $d;
}
function _keyED($txt,$encrypt_key)
{
$encrypt_key = md5($encrypt_key);
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
if ($ctr==strlen($encrypt_key)) $ctr=0;
$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
$ctr++;
}
return $tmp;
}
function _decrypt($txt,$key)
{
$txt = _keyED($txt,$key);
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
$md5 = substr($txt,$i,1);
$i++;
$tmp.= (substr($txt,$i,1) ^ $md5);
}
return $tmp;
}
function LoadFromRemote()
{
return "";
}
function DLid()
{
global $lid;
echo $lid."\n";
die();
}
function _LoadLicense($LoadRemote=FALSE)
{
global $pathtoroot, $objConfig;
$f = $pathtoroot."intechnic.php";
if (_falseIsLocalSite($f)) $ret = true;
if(file_exists($f))
{
$contents = file($f);
$data = base64_decode($contents[1]);
}
else
if($LoadRemote)
return $LoadFromRemote;
return $data;
}
function _VerifyKey($domain,$k)
{
$key = md5($domain);
$lkey = substr($key,0,strlen($key)/2);
$rkey = substr($key,strlen($key)/2);
$r = $rkey.$lkey;
if($k==$r)
return TRUE;
return FALSE;
}
function _ParseLicense($txt)
{
global $i_User, $i_Pswd, $i_Keys;
if (!_falseIsLocalSite($txt)) $nah = false;
$data = _decrypt($txt,"beagle");
$i_Keys = array();
$lines = explode("\n",$data);
for($x=0;$x<count($lines);$x++)
{
$l = $lines[$x];
$p = explode("=",$l,2);
switch($p[0])
{
case "Username":
$i_User = $p[1];
break;
case "UserPass":
$i_Pswd = $p[1];
break;
default:
if(substr($p[0],0,3)=="key")
{
$parts = explode("|",$p[1]);
if(_VerifyKey($parts[0],$parts[1]))
{
unset($K);
$k["domain"]=$parts[0];
$k["key"]=$parts[1];
$k["desc"]=$parts[2];
$k["mod"]=$parts[3];
$i_Keys[] = $k;
}
}
break;
}
}
}
function _GetObscureValue($i)
{
if ($i == 'x') return 0254; $z = '';
if ($i == 'z') return 0x7F.'.';
if ($i == 'c') return '--code--';
if ($i >= 5 && $i < 7) return _GetObscureValue($z)*_GetObscureValue('e');
if ($i > 30) return Array(0x6c,0x6f,0x63,0x61,0x6c,0x68,0x6f,0x73,0x74);
if ($i > 20) return 99;
if ($i > 10) return '.'.(_GetObscureValue(6.5)+1);
if ($i == 'a') return 0xa;
}
function _Chr($val)
{
$x = _GetObscureValue(25);
$f = chr($x).chr($x+5).chr($x+15);
return $f($val);
}
function _IsLocalSite($domain)
{
$ee = _GetObscureValue(35); $yy = '';
foreach ($ee as $e) $yy .= _Chr($e);
$localb = FALSE;
if(substr($domain,0,3)==_GetObscureValue('x'))
{
$b = substr($domain,0,6);
$p = explode(".",$domain);
$subnet = $p[1];
if($p[1]>15 && $p[1]<32)
$localb=TRUE;
}
$zz = _GetObscureValue('z')._GetObscureValue(5).'.'.(int)_GetObscureValue(7)._GetObscureValue(12);
$ff = _GetObscureValue('z')+65;
$hh = $ff-0x18;
if($domain==$yy || $domain==$zz || substr($domain,0,7)==$ff._Chr(46).$hh ||
substr($domain,0,3)==_GetObscureValue('a')._Chr(46) || $localb || strpos($domain,".")==0)
{
return TRUE;
}
return FALSE;
}
function _falseIsLocalSite($domain)
{
$localb = FALSE;
if(substr($domain,0,3)=="172")
{
$b = substr($domain,0,6);
$p = explode(".",$domain);
$subnet = $p[1];
if($p[1]>15 && $p[1]<32)
$localb=TRUE;
}
if($domain=="localhost" || $domain=="127.0.0.1" || substr($domain,0,7)=="192.168" ||
substr($domain,0,3)=="10." || $localb || strpos($domain,".")==0)
{
return TRUE;
}
return FALSE;
}
//echo "Before Stuff<br>";
LogEntry("Loading Modules\n");
/* get the module list from the database */
$adodbConnection = &GetADODBConnection();
$sql = "SELECT Name, Path, Var,TemplatePath, RootCat from ".GetTablePrefix()."Modules where Loaded=1 ORDER BY LoadOrder";
$rs = $adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$key = $rs->fields["Var"];
$mod_prefix[$key] = $rs->fields["Path"];
$modules_loaded[$key] = $rs->fields["Name"];
$name = $rs->fields["Name"];
$template_path[$name] = $rs->fields["TemplatePath"];
$mod_root_cats[$name] = $rs->fields["RootCat"];
// echo $key . "=". $modules_loaded[$key]."<br>\n";
$rs->MoveNext();
}
LogEntry("Loading Module Parser scripts\n");
/* for each module enabled, load up parser.php */
//foreach($mod_prefix as $key => $value)
$LogLevel++;
if(is_array($mod_prefix))
{
foreach($mod_prefix as $key => $value)
{
$mod = $pathtoroot . $value . "parser.php";
// LogEntry("Loading parser $mod \n");
if (file_exists($mod)) { // k4 modules may have no parser.php
require_once($mod);
}
}
}
$LogLevel--;
LogEntry("Finished Loading Module Parser scripts\n");
/*now each module gets a look at the environment string */
// SID detecting engine: begin
$SessionQueryString = false; // by default assume, that SID is located in cookie
if( !isset($FrontEnd) ) $FrontEnd = false; // if frontend not explicitly defined, than
$SessionQueryString = $application->Session->NeedQueryString();
/*if($FrontEnd != 1) {
$SessionQueryString = true;
}*/
if (is_array($mod_prefix)) {
ParseEnv();
}
if (defined('THIS_FILE') && (THIS_FILE == 'admin/index') ) {
// this is admin login screen & we don't have sid in url here,
// but session is already created by K4, then gether sid from it
$application =& kApplication::Instance();
$var_list['sid'] = $application->GetSID();
}
/* create the session object */
$ip = $_SERVER["REMOTE_ADDR"];
if ( !isset($var_list['sid']) ) $var_list['sid'] = '';
if ( !isset($_GET['env']) ) $_GET['env'] = '';
if(strlen($var_list["sid"])==0 && strlen($_GET["env"])>0 && $objConfig->Get("CookieSessions")==smCOOKIES_ONLY)
{
if(_IsSpider($_SERVER["HTTP_USER_AGENT"]))
{
$UseSession = FALSE;
}
else
{
/* switch user to GET session var */
if (!$_COOKIE[SESSION_COOKIE_NAME]) {
$SessionQueryString = TRUE;
}
//else {
//$cg = '--code--';
//}
$UseSession = TRUE;
}
}
else {
$UseSession = TRUE;
}
if($var_list["sid"]=="_")
$var_list["sid"]="";
/*setup action variable*/
$Action = isset($_REQUEST['Action']) ? $_REQUEST['Action'] : '';
if($Action == 'm_logout')
{
$u = new clsUserSession($var_list['sid']); // ,($SessionQueryString && $FrontEnd==1)
$application =& kApplication::Instance();
$application->HandleEvent( new kEvent('u:OnInpLogout') );
$u->Logout();
unset($u);
$var_list_update['t'] = 'index';
$var_list['t'] = '';
$var_list['sid'] = '';
set_cookie('login', '', adodb_mktime() - 3600);
set_cookie(SESSION_COOKIE_NAME, '', adodb_mktime() - 3600);
}
$CookieTest = isset($_COOKIE['cookies_on']) ? $_COOKIE['cookies_on'] : '';
if($var_list['sid'] && !$CookieTest) // when going from http -> https and via versa assume, that cookies are allowed
{
$CookieTest = true;
$_COOKIE['cookies_on'] = 1;
}
$HTTP_REFERER = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
/*if ( ($CookieTest == 1) ) { // || !strstr($HTTP_REFERER, $_SERVER['HTTP_HOST'].$objConfig->Get("Site_Path"))
$SessionQueryString = FALSE;
}
if ($FrontEnd != 1) {
$SessionQueryString = TRUE;
}*/
// SID detecting engine: end
$objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));
if($UseSession)
{
if(!$objSession->ValidSession())
{
/* Get rid of Invalid Session and make a brand new one*/
// echo "Dumping Session ".$var_list["sid"]."<br>";
unset($var_list["sid"]);
$objSession->GetNewSession();
$var_list["sid"] = $objSession->GetSessionKey();
$var_list_update["sid"]=$objSession->GetSessionKey();
if(is_numeric($m_var_list["theme"]))
$objSession->SetThemeName($m_var_list["theme"]);
if($objConfig->Get("CookieSessions")>0 && !$SessionQueryString && !headers_sent())
{
// set_cookie(SESSION_COOKIE_NAME, $var_list['sid'], 0);
}
//echo "New Session: ".$objSession->GetSessionKey()."<br>\n";
if(isset($_COOKIE["login"]) && $Action != "m_logout" && $FrontEnd==1)
{
$parts = explode("|",$_COOKIE["login"]);
$username = $parts[0];
$pass = $parts[1];
$objSession->Login($username,$pass);
}
}
else
{
if($objSession->Get("Language")!=$m_var_list["lang"])
{
$objSession->Set("Language", (int)$m_var_list["lang"]);
}
$objSession->LoadSessionData();
$objSession->UpdateAccessTime();
$objSession->Update();
LoadEnv();
}
}
if( isset($var_list['t']) && is_numeric($var_list['t']))
{
if( !isset($CurrentTheme) ) $CurrentTheme = null;
if(!is_object($CurrentTheme))
$CurrentTheme = $objThemes->GetItem($m_var_list["theme"]);
$var_list["t"] = $CurrentTheme->GetTemplateById($var_list["t"]);
$objSession->Set("Theme", (int)$CurrentTheme->Get("Name"));
}
/*create the global current user object */
$UserID=$objSession->Get("PortalUserId");
$objCurrentUser = new clsPortalUser($UserID);
/* include each module's action.php script */
LogEntry("Loading Module action scripts\n");
## Global Referer Template
$_local_t = isset($var_list['t']) ? $var_list['t'] : '';
if(is_array($mod_prefix))
{
foreach($mod_prefix as $key => $folder_name)
{
$var_to_global = $key.'_var_list';
global $$var_to_global;
$application =& kApplication::Instance(); // just to sure, that object is here in all actions
if($FrontEnd == 0 || !is_numeric($FrontEnd) || $FrontEnd == 2) {
- $rootURL = 'http://'.ThisDomain().$objConfig->Get('Site_Path');
+ /*$rootURL = 'http://'.ThisDomain().$objConfig->Get('Site_Path');
$admin = $objConfig->Get("AdminDirectory");
if( !strlen($admin) ) $admin = "admin";
$adminURL = $rootURL.$admin;
- $imagesURL = $adminURL."/images";
+ $imagesURL = $adminURL."/images";*/
if( $key != 'bbcat' && _ModuleLicensed($modules_loaded[$key]) )
{
$mod = $pathtoroot.$folder_name."module_init.php";
if( file_exists($mod) ) require_once($mod);
$mod = $pathtoroot.$folder_name."action.php";
if( file_exists($mod) ) require_once($mod);
$mod = $pathtoroot.$folder_name."searchaction.php";
if( file_exists($mod) ) require_once($mod);
}
}
if($FrontEnd==1 || $FrontEnd==2)
{
$mod = $pathtoroot.$folder_name."module_init.php";
if(file_exists($mod))
require_once($mod);
$mod = $pathtoroot.$folder_name."frontaction.php";
if(file_exists($mod))
require_once($mod);
}
}
}
if( !isset($SearchPerformed) ) $SearchPerformed = false;
if($SearchPerformed == true) $objSearch->BuildIndexes();
LogEntry("Finished Loading Module action scripts\n");
?>
\ No newline at end of file
Property changes on: branches/RC/kernel/include/modules.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.55
\ No newline at end of property
+1.55.2.1
\ No newline at end of property
Index: branches/RC/kernel/startup.php
===================================================================
--- branches/RC/kernel/startup.php (revision 9388)
+++ branches/RC/kernel/startup.php (revision 9389)
@@ -1,208 +1,208 @@
<?php
if( !defined('FULL_PATH') ) define('FULL_PATH', realpath(dirname(__FILE__).'/..') );
require_once FULL_PATH.'/kernel/include/globals.php';
if( !isset($FrontEnd) ) $FrontEnd = 0;
if( !class_exists('kApplication') )
{
// KENEL4 INIT: BEGIN
if ($FrontEnd != 1 && !defined('ADMIN') ) {
define('ADMIN', 1);
}
include_once(FULL_PATH.'/core/kernel/startup.php');
$application =& kApplication::Instance();
$application->Init();
$application->ProcessRequest();
// KERNEL4 INIT: END
}
// compatibility constants
$g_TablePrefix = TABLE_PREFIX;
$pathtoroot = preg_replace('/(.*)\/$/', '\\1', FULL_PATH).'/';
- $admin = 'admin';
+ $admin = defined('ADMIN_DIRECTORY') ? trim(ADMIN_DIRECTORY, '/') : 'admin';
$rootURL = PROTOCOL.SERVER_NAME.(defined('PORT')?':'.PORT : '').rtrim(BASE_PATH, '/').'/';
$localURL = $rootURL.'kernel/';
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL.'/images';
$browseURL = $adminURL.'/browse';
$cssURL = $adminURL.'/include';
$pathchar = '/';
if(!get_magic_quotes_gpc())
{
function addSlashesA($a)
{
foreach($a as $k => $v)
{
$a[$k] = is_array($v) ? addSlashesA($v) : addslashes($v);
}
return $a;
}
foreach(Array(
'HTTP_GET_VARS','HTTP_POST_VARS','HTTP_COOKIE_VARS','HTTP_SESSION_VARS','HTTP_SERVER_VARS',
'_POST','_GET','_COOKIE','_SESSION','_SERVER','_REQUEST') as $_)
if(isset($GLOBALS[$_]))
$GLOBALS[$_]=addSlashesA($GLOBALS[$_]);
}
/*
startup.php: this is the primary startup sequence for in-portal services
*/
if( file_exists(FULL_PATH.'/debug.php') && !defined('DEBUG_MODE') ) include_once(FULL_PATH.'/debug.php');
if( !defined('DEBUG_MODE') ) error_reporting(0);
ini_set('memory_limit', constOn('IS_INSTALL') ? -1 : '32M');
ini_set('include_path', '.');
$kernel_version = "1.0.0";
$FormError = array();
$FormValues = array();
/* include PHP version compatibility functions */
require_once(FULL_PATH.'/kernel/include/compat.php');
/* set global variables and module lists */
if( constOn('DEBUG_MODE') ) include_once(FULL_PATH.'/kernel/include/debugger.php');
// put all non-checked checkboxes in $_POST & $_REQUEST with 0 values
if( GetVar('form_fields') )
{
$form_fields = GetVar('form_fields');
foreach($form_fields as $checkbox_name)
{
if( GetVar($checkbox_name) === false ) SetVar($checkbox_name,0);
}
}
LogEntry("Initalizing System..\n");
/* for 64 bit timestamps */
if( !function_exists('adodb_mktime') ) require_once(FULL_PATH.'/kernel/include/adodb/adodb-time.inc.php');
require_once(FULL_PATH.'/kernel/include/dates.php');
/* create the global error object */
require_once(FULL_PATH.'/kernel/include/error.php');
$Errors = new clsErrorManager();
require_once(FULL_PATH.'/kernel/include/itemdb.php');
require_once(FULL_PATH.'/kernel/include/db.class.php'); // moved from kernel/include/config.php
require_once(FULL_PATH.'/kernel/include/adodb/adodb.inc.php'); // moved from kernel/include/config.php
require_once(FULL_PATH.'/kernel/include/config.php');
/* create the global configuration object */
LogEntry("Creating Config Object..\n");
$objConfig = new clsConfig();
$objConfig->Load(); /* Populate our configuration data */
LogEntry("Done Loading Configuration\n");
if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 )
LogEntry("ADO Extension: ".ADODB_EXTENSION."\n");
require_once(FULL_PATH.'/kernel/include/parseditem.php');
require_once(FULL_PATH.'/kernel/include/itemreview.php'); // moved from kernel/include/item.php
require_once(FULL_PATH.'/kernel/include/itemrating.php'); // moved from kernel/include/item.php
require_once(FULL_PATH.'/kernel/include/item.php');
require_once(FULL_PATH.'/kernel/include/syscache.php');
require_once(FULL_PATH.'/kernel/include/modlist.php');
require_once(FULL_PATH.'/kernel/include/searchconfig.php');
require_once(FULL_PATH.'/kernel/include/banrules.php');
$objModules = new clsModList();
$objSystemCache = new clsSysCacheList();
$objSystemCache->PurgeExpired();
$objBanList = new clsBanRuleList();
require_once(FULL_PATH.'/kernel/include/image.php');
require_once(FULL_PATH.'/kernel/include/itemtypes.php');
$objItemTypes = new clsItemTypeList();
require_once(FULL_PATH.'/kernel/include/theme.php');
$objThemes = new clsThemeList();
require_once(FULL_PATH.'/kernel/include/language.php');
$objLanguages = new clsLanguageList();
$objImageList = new clsImageList();
/* Load session and user class definitions */
//require_once("include/customfield.php");
//require_once("include/custommetadata.php");
require_once(FULL_PATH.'/kernel/include/usersession.php');
require_once(FULL_PATH.'/kernel/include/favorites.php');
require_once(FULL_PATH.'/kernel/include/portaluser.php');
require_once(FULL_PATH.'/kernel/include/portalgroup.php');
/* create the user management class */
$objFavorites = new clsFavoriteList();
$objUsers = new clsUserManager();
$objGroups = new clsGroupList();
require_once(FULL_PATH.'/kernel/include/cachecount.php');
require_once(FULL_PATH.'/kernel/include/customfield.php');
require_once(FULL_PATH.'/kernel/include/custommetadata.php');
require_once(FULL_PATH.'/kernel/include/permissions.php');
require_once(FULL_PATH.'/kernel/include/relationship.php');
require_once(FULL_PATH.'/kernel/include/category.php');
require_once(FULL_PATH.'/kernel/include/statitem.php');
/* category base class, used by all the modules at some point */
$objPermissions = new clsPermList();
$objPermCache = new clsPermCacheList();
$objCatList = new clsCatList();
$objCustomFieldList = new clsCustomFieldList();
$objCustomDataList = new clsCustomDataList();
$objCountCache = new clsCacheCountList();
require_once(FULL_PATH.'/kernel/include/smtp.php');
require_once(FULL_PATH.'/kernel/include/emailmessage.php');
require_once(FULL_PATH.'/kernel/include/events.php');
LogEntry("Creating Mail Queue..\n");
$objMessageList = new clsEmailMessageList();
$objEmailQueue = new clsEmailQueue();
LogEntry("Done creating Mail Queue Objects\n");
require_once(FULL_PATH.'/kernel/include/searchitems.php');
require_once(FULL_PATH.'/kernel/include/advsearch.php');
require_once(FULL_PATH.'/kernel/include/parse.php');
require_once(FULL_PATH.'/kernel/include/socket.php');
/* responsible for including module code as required
This script also creates an instance of the user session onject and
handles all session management. The global session object is created
and populated, then the global user object is created and populated
each module's parser functions and action code is included here
*/
LogEntry("Startup complete\n");
include_once("include/modules.php");
if( IsDebugMode() && function_exists('DebugByFile') ) DebugByFile();
/* startup is complete, so now check the mail queue to see if there's anything that needs to be sent*/
$objEmailQueue->SendMailQeue();
$ado=&GetADODBConnection();
$rs = $ado->Execute("SELECT * FROM ".GetTablePrefix()."Modules WHERE LoadOrder = 0");
$kernel_version = $rs->fields['Version'];
$adminDir = $objConfig->Get("AdminDirectory");
if ($adminDir == '') {
$adminDir = 'admin';
}
/*if (strstr(__FILE__, $adminDir) && !GetVar('logout') && !strstr(__FILE__, "install") && !strstr(__FILE__, "index")) {
require_login(null, 'expired='.(int)GetVar('expired') );
}*/
?>
\ No newline at end of file
Property changes on: branches/RC/kernel/startup.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.45
\ No newline at end of property
+1.45.2.1
\ No newline at end of property
Index: branches/RC/admin/install_over_kx.php
===================================================================
--- branches/RC/admin/install_over_kx.php (revision 9388)
+++ branches/RC/admin/install_over_kx.php (revision 9389)
@@ -1,58 +1,59 @@
<?php
+// die('aa');
// new startup: begin
define('REL_PATH', 'admin');
$relation_level = count( explode('/', REL_PATH) );
define('FULL_PATH', realpath(dirname(__FILE__) . str_repeat('/..', $relation_level) ) );
-
+
if (!defined('IS_INSTALL')) define('IS_INSTALL', 1);
require_once FULL_PATH.'/kernel/startup.php';
// new startup: end
$application =& kApplication::Instance();
$application->Init();
- require_once FULL_PATH.'/admin/install/install_lib.php';
+ require_once FULL_PATH.ADMIN_DIRECTORY.'/install/install_lib.php';
echo '<strong>In-Portal Installation</strong><br />';
-
+
echo '1. Importing Database<br />';
- RunSchemaFile($application->Conn, FULL_PATH.'/admin/install/inportal_schema.sql', 'dbconnection');
- RunSQLFile($application->Conn, FULL_PATH.'/admin/install/inportal_data.sql', 'dbconnection');
-
+ RunSchemaFile($application->Conn, FULL_PATH.ADMIN_DIRECTORY.'/install/inportal_schema.sql', 'dbconnection');
+ RunSQLFile($application->Conn, FULL_PATH.ADMIN_DIRECTORY.'/install/inportal_data.sql', 'dbconnection');
+
echo '2. Writing config.php<br />';
if (!(isset($ini_file) && $ini_file)) {
$ini_file = FULL_PATH.'/config.php';
$ini_vars = inst_parse_portal_ini($ini_file, true);
}
-
+
$sql = 'SELECT Version FROM '.TABLE_PREFIX.'Modules WHERE Name = '.$application->Conn->qstr('In-Portal');
$mod_version = $application->Conn->GetOne($sql);
set_ini_value('Module Versions', 'In-Portal', $mod_version);
save_values();
echo '3. Removing Config Cache<br />';
$sql = 'DELETE FROM '.TABLE_PREFIX.'Cache WHERE (VarName = "config_files") OR (VarName LIKE "%_parsed")';
$application->Conn->Query($sql);
-
+
echo '4. Importing Language Pack<br />';
$lang_xml =& $application->recallObjectP('LangXML', null, Array(), false); // false - don't use temp tables
/* @var $lang_xml LangXML_Parser */
-
- $lang_xml->Parse(FULL_PATH.'/admin/install/langpacks/english.lang', '|0|1|2|', '');
-
+
+ $lang_xml->Parse(FULL_PATH.ADMIN_DIRECTORY.'/install/langpacks/english.lang', '|0|1|2|', '');
+
echo '5. Verifying License Status<br />';
$modules_helper =& $application->recallObject('ModulesHelper');
/* @var $modules_helper kModulesHelper */
-
+
$modules = $modules_helper->checkLogin();
if (in_array('In-Portal', $modules)) {
// in-portal is licensed
echo '<script type="text/javascript">window.location.href = "index.php";</script>';
}
else {
echo '<a href="install.php?install_type=5&state=license&next_step=2">Please Update Your License</a><br />';
}
-
+
echo '<strong>Done</strong><br />';
?>
\ No newline at end of file
Property changes on: branches/RC/admin/install_over_kx.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.2.2.1
\ No newline at end of property
Index: branches/RC/admin/index4_direct.php
===================================================================
--- branches/RC/admin/index4_direct.php (revision 9388)
+++ branches/RC/admin/index4_direct.php (revision 9389)
@@ -1,43 +1,43 @@
<?php
##############################################################
##In-portal ##
##############################################################
## In-portal ##
## Intechnic Corporation ##
## All Rights Reserved, 1998-2002 ##
-## ##
-## No portion of this code may be copied, reproduced or ##
+## ##
+## No portion of this code may be copied, reproduced or ##
## otherwise redistributed without proper written ##
## consent of Intechnic Corporation. Violation will ##
## result in revocation of the license and support ##
## privileges along maximum prosecution allowed by law. ##
##############################################################
// new startup: begin
define('REL_PATH', 'admin');
$relation_level = count( explode('/', REL_PATH) );
define('FULL_PATH', realpath(dirname(__FILE__) . str_repeat('/..', $relation_level) ) );
require_once FULL_PATH.'/kernel/startup.php';
// new startup: end
-
+
$prefix = $application->GetVar('prefix');
$application->SetVar($prefix.'_mode', 't');
-
+
$id_field = $application->getUnitOption($prefix, 'IDField');
$temp_handler =& $application->recallObject($prefix.'_TempHandler', 'kTempTablesHandler');
$table_name = $temp_handler->GetTempName( $application->getUnitOption($prefix, 'TableName'), 'prefix:'.$prefix );
-
+
$db =& $application->GetADODBConnection();
$item_id = $db->GetOne('SELECT '.$id_field.' FROM '.$table_name, (int)$application->GetVar('en'));
- $application->SetVar($prefix.'_id', $item_id);
-
+ $application->SetVar($prefix.'_id', $item_id);
+
$object =& $application->recallObject($prefix, null, Array('skip_autoload' => true));
$object->Load($item_id);
-
+
$template = $application->GetVar('t');
- include_once FULL_PATH.'/admin/'.$template.'.php';
-
+ include_once FULL_PATH.ADMIN_DIRECTORY.'/'.$template.'.php';
+
$application->Run();
-
+
int_footer();
?>
\ No newline at end of file
Property changes on: branches/RC/admin/index4_direct.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3
\ No newline at end of property
+1.3.2.1
\ No newline at end of property
Index: branches/RC/admin/editor/editor_new.php
===================================================================
--- branches/RC/admin/editor/editor_new.php (revision 9388)
+++ branches/RC/admin/editor/editor_new.php (revision 9389)
@@ -1,180 +1,180 @@
<?php
##############################################################
##In-portal ##
##############################################################
## In-portal ##
## Intechnic Corporation ##
## All Rights Reserved, 1998-2002 ##
-## ##
-## No portion of this code may be copied, reproduced or ##
+## ##
+## No portion of this code may be copied, reproduced or ##
## otherwise redistributed without proper written ##
## consent of Intechnic Corporation. Violation will ##
## result in revocation of the license and support ##
## privileges along maximum prosecution allowed by law. ##
##############################################################
-define('IS_POPUP', 1);
+define('IS_POPUP', 1);
// new startup: begin
define('REL_PATH', 'admin/editor');
$relation_level = count( explode('/', REL_PATH) );
define('FULL_PATH', realpath(dirname(__FILE__) . str_repeat('/..', $relation_level) ) );
require_once FULL_PATH.'/kernel/startup.php';
// new startup: end
-require_once ($pathtoroot.$admin."/include/elements.php");
-require_once ($pathtoroot."kernel/admin/include/navmenu.php");
+require_once ($pathtoroot.$admin."/include/elements.php");
+require_once ($pathtoroot."kernel/admin/include/navmenu.php");
require_once($pathtoroot.$admin."/toolbar.php");
require_once($pathtoroot.$admin."/editor/cmseditor/fckeditor.php");
$style_sheet_global = $adminURL."/include/style.css";
?>
<html>
<head>
<title>Online Editor</title>
<?php print "<link rel=\"stylesheet\" type=\"text/css\" href=\"$style_sheet_global\">\n"; ?>
<?php require_once($pathtoroot.$admin."/include/mainscript.php"); ?>
<script>
function HasParam(param)
{
// checks of parameter is passed to function (cross-browser)
return typeof(param) == 'undefined' ? false : true;
}
</script>
</head>
<body marginwidth="0" leftmargin="0" topmargin="0" marginheight="0" style="overflow:auto" onload="update_content()">
<table width="100%" height="100%" cellspacing="0" cellpadding="0" border="0" align="center"><tr><td align="left" valign="top">
<?php
$section=$_GET["section"];
$objListToolBar = new clsToolBar();
$objListToolBar->Set("section",$section);
$objListToolBar->Set("load_menu_func","");
$objListToolBar->Set("CheckClass","");
-
+
$listImages = array();
//$img, $alt, $link, $onMouseOver, $onMouseOut, $onClick
$objListToolBar->Add("select", "la_ToolTip_Select","#","swap('select','toolbar/tool_select_f2.gif');",
"swap('select', 'toolbar/tool_select.gif');",
"document.frm.submit();","tool_select.gif");
$objListToolBar->Add("cancel", "la_ToolTip_Stop","#","swap('cancel','toolbar/tool_stop_f2.gif');",
"swap('cancel', 'toolbar/tool_stop.gif');","window.close();","tool_stop.gif");
$title = "Online HTML Editor";
$objSections->SetCurrentSection($section);
print $objSections->section_header($envar,NULL,$title);
$TargetForm = $_GET["TargetForm"];
$TargetField = $_GET["TargetField"];
echo $objListToolBar->Build();
?>
<form name="frm" action="javascript:update_opener();">
-<?php
+<?php
$oFCKeditor = new FCKeditor('Content');
-
+
$oFCKeditor->BasePath = 'cmseditor/' ;
$oFCKeditor->Width = '100%' ;
$oFCKeditor->Height = '500' ;
$oFCKeditor->ToolbarSet = 'Advanced' ;
$oFCKeditor->Value = '' ;
$oFCKeditor->Config = Array(
//'UserFilesPath' => $pathtoroot.'kernel/user_files',
'ProjectPath' => $objConfig->Get("Site_Path"),
- 'CustomConfigurationsPath' => $rootURL.'admin/editor/inp_fckconfig.js',
+ 'CustomConfigurationsPath' => $rootURL.$admin.'/editor/inp_fckconfig.js',
'EditorAreaCSS' => GetThemeCSS(),
//'StylesXmlPath' => '../../inp_styles.xml',
//'Debug' => 1,
);
-
+
function GetThemeCSS()
{
$query = 'SELECT LastCompiled, '.GetTablePrefix().'Stylesheets.Name as StyleName FROM '.GetTablePrefix().'Theme
LEFT JOIN '.GetTablePrefix().'Stylesheets
ON '.GetTablePrefix().'Theme.StylesheetId = '.GetTablePrefix().'Stylesheets.StylesheetId
WHERE ThemeId = 4';
$conn =& GetADODBConnection();
-
+
$res = $conn->GetRow($query);
-
+
$last_compiled = $res['LastCompiled'];
-
+
$style_name = strtolower( $res['StyleName'] );
-
+
global $pathtoroot,$rootURL;
-
+
$css_path = $pathtoroot.'kernel/stylesheets';
-
+
$css_url = $rootURL.'kernel/stylesheets';
-
+
if( file_exists($css_path.'/'.$style_name.'-'.$last_compiled.'.css') )
{
$ret = $css_url.'/'.$style_name.'-'.$last_compiled.'.css';
}
return $ret;
}
-
- echo $oFCKeditor->CreateHtml() ;
-?>
- </FORM>
+
+ echo $oFCKeditor->CreateHtml() ;
+?>
+ </FORM>
</td></tr></table>
-
+
</form>
</body>
<script>
<?php
print <<<END
function update_content()
{
if (window.opener)
{
if (!window.opener.closed)
{
bf = window.opener.document.$TargetForm;
// if (typeof (bf.$TargetField.value) != 'undefined') {
// current = bf.$TargetField.value;
// }
// else {
current = window.opener.document.getElementById('$TargetField').value;
// }
//f = document.getElementById('editform');
d = document.getElementById('Content');
d.value = current;
- }
- else
+ }
+ else
window.close()
}
- else
+ else
window.close()
}
-
+
function update_opener()
- {
- d = document.getElementById('Content');
+ {
+ d = document.getElementById('Content');
if (d.form)
if (d.form.onsubmit)
d.form.onsubmit()
if (!window.opener) return;
if (!window.opener.closed)
-
+
// if (typeof (bf.$TargetField.value) != 'undefined') {
// current = bf.$TargetField;
// }
// else {
current = window.opener.document.getElementById('$TargetField');
// }
-
+
current.value = d.value;
- //alert('Setting bf.$TargetField.value to'+d.value);
+ //alert('Setting bf.$TargetField.value to'+d.value);
window.close();
}
-
+
END;
?>
// setTimeout('update_content();',100);
</script>
</html>
Property changes on: branches/RC/admin/editor/editor_new.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10
\ No newline at end of property
+1.10.22.1
\ No newline at end of property
Index: branches/RC/admin/tag_listing.php
===================================================================
--- branches/RC/admin/tag_listing.php (revision 9388)
+++ branches/RC/admin/tag_listing.php (revision 9389)
@@ -1,124 +1,124 @@
<?php
// new startup: begin
define('REL_PATH', 'admin');
$relation_level = count( explode('/', REL_PATH) );
define('FULL_PATH', realpath(dirname(__FILE__) . str_repeat('/..', $relation_level) ) );
require_once FULL_PATH.'/kernel/startup.php';
// new startup: end
checkViewPermission('in-portal:tag_library');
include_once($pathtoroot."kernel/include/tag-class.php");
$pathtolocal = $pathtoroot."kernel/";
-require_once ($pathtoroot."admin/include/elements.php");
+require_once ($pathtoroot.$admin."/include/elements.php");
require_once ($pathtoroot."kernel/admin/include/navmenu.php");
require_once ($pathtolocal."admin/include/navmenu.php");
-require_once($pathtoroot."admin/toolbar.php");
+require_once($pathtoroot.$admin."/toolbar.php");
//Set Section
$section = "in-portal:tag_library";
//Set Environment Variable
$envar = "env=" . BuildEnv();
$sec = $objSections->GetSection($section);
$objCatToolBar = new clsToolBar();
-$objCatToolBar->Add("img_save",
+$objCatToolBar->Add("img_save",
"la_Save",
"#",
"swap('img_save','toolbar/tool_select_f2.gif');",
"swap('img_save', 'toolbar/tool_select.gif');",
"javascript:history.back();",
"tool_select.gif");
-$objCatToolBar->Add("img_cancel",
+$objCatToolBar->Add("img_cancel",
"la_Cancel",
"#",
- "swap('img_cancel','toolbar/tool_cancel_f2.gif');",
+ "swap('img_cancel','toolbar/tool_cancel_f2.gif');",
"swap('img_cancel', 'toolbar/tool_cancel.gif');",
"javascript:history.back();",
"tool_cancel.gif");
$extra_styles = '<STYLE type="text/css">
<!--
.tag-listing {
border-collapse: collapse;
padding: 0px;
margin: 0px;
border: 0px;
background-color: #f6f6f6;
}
.tag-listing-row {font: 11px verdana}
.b-element {font: bold 13px}
.i-element {font: oblique 12px; background: #ebebeb;}
.header {
background: #999;
color: #fff;
}
-->
</STYLE>';
$title = admin_language("la_tag_library");
int_header($objCatToolBar,NULL,$title,NULL,$extra_styles);
$objTagList = new clsTagList();
$objTagList->Clear();
$objTagList->Query_Item("SELECT * FROM ".$objTagList->SourceTable);
?>
<table class="tag-listing" border="0" width="100%">
<?php
if($objTagList->NumItems()>0)
{
foreach($objTagList->Items as $i)
{
$i->LoadAttribs(); //echo " ".$i->attribs->NumItems()." Attributes<br>\n";
if( $i->Get("name") )
- {
- ?>
+ {
+ ?>
<tr class="header">
<td class="b-element" colspan="2">
<?php echo ($i->Get("scope") != "global") ? $i->Get("scope").'.'.$i->Get("name") : $i->Get("name"); ?>
</td>
</tr>
- <tr class="tag-listing-row">
+ <tr class="tag-listing-row">
<td colspan="2" class="i-element"><?php echo $i->Get("description"); ?></td>
</tr>
<tr class="tag-listing-row">
<td class="b-element" width="90%">Attributes:</td>
<td class="b-element" width="10%">Source example:</td>
</tr>
-
+
<tr>
<td>
<?php if( $i->attribs->NumItems() > 0 ) { // has attributes ?>
<!-- attributes listing: begin -->
<table border="0" width="100%" class="tag-listing">
<?php
foreach($i->attribs->Items as $a)
- {
+ {
?>
<tr class="tag-listing-row">
<td valign="top"><?php echo $a->Get("Name").'['.$a->Get("AttrType").']'; ?></td>
<td><?php echo $a->Get("Description"); ?></td>
</tr>
<?php
}
- ?>
+ ?>
</table>
<!-- attributes listing: end -->
<?php } else{ ?>&nbsp; <?php } ?>
</td>
<td>
<!-- example -->
- <?php
+ <?php
$example = $i->Get('example');
echo $example ? $example : '&nbsp;';
?>
</td>
</tr>
<?php
}
}
}
-?>
-</table>
+?>
+</table>
<?php int_footer(); ?>
\ No newline at end of file
Property changes on: branches/RC/admin/tag_listing.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.6
\ No newline at end of property
+1.6.2.1
\ No newline at end of property
Index: branches/RC/admin/listview/listview.php
===================================================================
--- branches/RC/admin/listview/listview.php (revision 9388)
+++ branches/RC/admin/listview/listview.php (revision 9389)
@@ -1,479 +1,479 @@
<?php
-require_once FULL_PATH.'/admin/listview/columnheader.php';
-require_once FULL_PATH.'/admin/listview/viewmenu.php';
+require_once FULL_PATH.ADMIN_DIRECTORY.'/listview/columnheader.php';
+require_once FULL_PATH.ADMIN_DIRECTORY.'/listview/viewmenu.php';
-class clsListView
+class clsListView
{
var $Formatters = Array(); // formatters to apply while printing list
var $ColumnHeaders;
var $ToolBar;
var $ListItems;
- var $PageLinkTemplate;
+ var $PageLinkTemplate;
var $PerPageVar;
var $CurrentPageVar;
var $CurrentPage;
var $TotalItemCount;
var $SortField;
var $SortOrder;
var $IdField;
var $PrintToolBar=TRUE;
var $ShowColumnHeaders=TRUE;
var $checkboxes=TRUE;
var $SelectorType;
var $CheckboxName;
var $CheckArray;
var $RowIcons;
var $SearchBar=FALSE;
var $SearchKeywords;
var $SearchAction;
var $SearchDropdownId="";
var $PageLinks;
var $extra_env;
var $PriorityField;
var $PageURL;
var $ViewMenu;
var $JSCheckboxName;
-
+
function clsListView($ToolBar=NULL,$ListItems=NULL)
{
$this->SetToolBar($ToolBar);
$this->SetListItems($ListItems);
- $this->ColumnHeaders = new clsColumnHeaderList();
+ $this->ColumnHeaders = new clsColumnHeaderList();
$this->CurrentPage=1;
$this->CheckboxName = "itemlist[]";
$this->SelectorType="checkbox";
$this->RowIcons = array();
$this->PageLinks = "";
$this->SearchAction = "";
$this->extra_env="";
$this->PriorityField="Priority";
$this->TotalItemCount = 0;
-
+
if (!is_null($ToolBar))
$this->JSCheckboxName = $ToolBar->Get("CheckClass");
- $this->SetFormatters(); // for setting custom formatters
+ $this->SetFormatters(); // for setting custom formatters
}
function SetToolbar($ToolBar)
{
$this->ToolBar=$ToolBar;
if(is_object($this->ToolBar))
$this->CheckArray=$this->ToolBar->Get("CheckClass");
}
-
+
function GetPage()
{
// get current page
$this->RefreshPageVar();
return $this->CurrentPage;
}
-
+
function GetLimitSQL()
{
return GetLimitSQL($this->GetPage(), $this->GetPerPage() );
}
-
+
function SetListItems(&$ListItems)
{
- $this->ListItems =& $ListItems;
+ $this->ListItems =& $ListItems;
}
function SetIDfield($field)
{
$this->IdField = $field;
}
function SetSort($SortField,$SortOrderVariable)
{
$this->ColumnHeaders->SetSort($SortField,$SortOrder);
}
function SetRowIcon($index,$url)
{
$this->RowIcons[$index] = $url;
}
function ConfigureViewMenu($SortFieldVar,$SortOrderVar,$DefaultSort,$FilterVar,$FilterValue,$FilterMax)
{
global $objConfig;
-
+
//$FilterVal = $this->CurrentFilter;
//$fMax = $this->Filtermax;
//$sOrder = $this->CurrentSortOrder;
//$sOrderVar = $this->OrderVar;
//$sField = $this->CurrentSortField;
- //$sDefault = $this->DefaultSortField;
-
+ //$sDefault = $this->DefaultSortField;
+
$this->ViewMenu = new clsViewMenu();
$this->ViewMenu->PerPageVar = $this->PerPageVar;
$this->ViewMenu->PerPageValue = (int)$objConfig->Get($this->PerPageVar);
if($this->ViewMenu->PerPageValue==0)
$this->ViewMenu->PerPageValue = 20;
$this->ViewMenu->CurrentSortField = $objConfig->Get($SortFieldVar);
$this->ViewMenu->CurrentSortOrder = $objConfig->get($SortOrderVar);
$this->ViewMenu->SortVar = $SortFieldVar;
$this->ViewMenu->OrderVar = $SortOrderVar;
- $this->ViewMenu->CurrentFilter= $FilterValue;
+ $this->ViewMenu->CurrentFilter= $FilterValue;
$this->ViewMenu->FilterVar = $FilterVar;
$this->ViewMenu->FilterMax = $FilterMax;
foreach($this->ColumnHeaders->Columns as $col)
{
- $this->ViewMenu->AddSortField($col->field,$col->label,$DefaultSort==$col->field);
+ $this->ViewMenu->AddSortField($col->field,$col->label,$DefaultSort==$col->field);
}
}
-
+
function AddViewMenuFilter($Label,$Bit)
{
if(is_object($this->ViewMenu))
- $this->ViewMenu->AddFilterField($Label,$Bit);
+ $this->ViewMenu->AddFilterField($Label,$Bit);
}
-
+
function GetViewMenu($imagesURL)
- {
- if(is_object($this->ViewMenu))
+ {
+ if(is_object($this->ViewMenu))
{
$this->ViewMenu->CheckboxName = $this->JSCheckboxName;
- return $this->ViewMenu->GetViewMenuJS($imagesURL);
+ return $this->ViewMenu->GetViewMenuJS($imagesURL);
}
else
return "";
}
-
+
function SetFormatters()
{
- // for setting custom formatters
+ // for setting custom formatters
// abstract
}
-
+
function SetFormatter($field, $type, $params)
{
// by Alex
// all params after 2nd are formmater type specific
$this->Formatters[$field]['type'] = $type;
switch($type)
{
case FT_OPTION:
$this->Formatters[$field]['options'] = $params;
- break;
+ break;
}
}
-
+
function PrintItem($index)
{
if( !isset($this->ListItems->Items[$index]) ) return '';
$li = $this->ListItems->Items[$index];
-
+
$o = "";
- $first=1;
+ $first=1;
if(is_object($li))
- {
+ {
// ==== new by Alex: begin ====
$li->Formatters =& $this->Formatters;
// ==== new by Alex: end ====
-
+
$id_field = $this->IdField;
$row_id = $li->Get($id_field);
if(is_numeric($li->Get($this->PriorityField)))
{
$Priority = (int)$li->Get($this->PriorityField);
}
else
$Priority=0;
$o = "<TR ".int_table_color_ret()." ID=\"$row_id\">\n";
foreach($this->ColumnHeaders->Columns as $col)
{
- $width="";
+ $width="";
$ColId = $row_id."_col_".$col->field;
if($first==1)
- {
+ {
if(strlen($col->width))
{
$width = $col->width;
}
$o .= "<TD $width valign=\"top\" class=\"text\">";
if($this->checkboxes)
- {
+ {
$onclick = "onclick=\"if (this.checked) {".$this->CheckArray.".addCheck('$row_id');} else {".$this->CheckArray.".removeCheck('$row_id');}\"";
$onclicksrc = "onclicksrc=\"if (this.checked) {".$this->CheckArray.".addCheck('$row_id');} else {".$this->CheckArray.".removeCheck('$row_id');}\"";
$o .= "<input rowId='".$row_id."' checkArrayName='".$this->CheckArray."' isSelector=\"true\" type=\"".$this->SelectorType."\" name=\"".$this->CheckboxName."\" value=\"$row_id\" $onclick $onclicksrc>";
}
if(isset($this->RowIcons[$index]))
- {
+ {
$url = $this->RowIcons[$index];
if(strlen($url))
$o .= "<img src=\"".$url."\"> ";
}
$first=0;
}
else
- {
+ {
if(strlen($col->width))
{
$o .= "<TD ".$col->width.">";
}
else
$o .= "<TD>";
}
if($Priority!=0)
- {
+ {
$o .= "<span class=\"priority\"><sup>$Priority</sup></span>";
$Priority=0;
}
$o .= "<SPAN ID=\"$ColId\">".($li->GetFormatted($col->field))."</SPAN></TD>\n";
}
$o .= "</TR>\n";
}
return $o;
}
function PrintItems()
{
$o = '';
$numitems = $this->ListItems->NumItems();
for($index=0;$index<=$numitems;$index++)
{
$o .= $this->PrintItem($index);
}
return $o;
}
function TotalPageNumbers()
{
if($this->PerPage>0)
{
$ret = $this->ListItems->NumItems() / $this->PerPage;
$ret = (int)$ret;
}
else
$ret = 1;
return $ret;
}
-
+
function GetPerPage()
{
global $objConfig;
$PerPage = $objConfig->Get($this->PerPageVar);
if($PerPage < 1)
{
if( IsDebugMode() ) echo 'PerPage Variable [<b>'.$this->PerPageVar.'</b>] not defined in Config<br>';
$PerPage = 20;
//$objConfig->Set($this->PerPageVar,20);
//$objConfig->Save();
}
return $PerPage;
}
-
+
function GetAdminPageLinkList($url)
{
global $objConfig;
-
+
$PerPage = $this->GetPerPage();
-
+
if($this->TotalItemCount>0)
{
$NumPages = ceil($this->TotalItemCount / $PerPage);
}
else
$NumPages = ceil($this->ListItems->NumItems() / $PerPage);
if($NumPages<1)
$NumPages =1;
//echo $this->CurrentPage." of ".$NumPages." Pages";
$o = "";
if($this->CurrentPage>$NumPages)
$this->CurrentPage=$NumPages;
$StartPage = $this->CurrentPage - 5;
if($StartPage<1)
$StartPage=1;
$EndPage = $StartPage+9;
if($EndPage>$NumPages)
- {
+ {
$EndPage = $NumPages;
$StartPage = $EndPage-10;
if($StartPage<1)
$StartPage=1;
}
-
+
$o .= "<b class=\"text\">".admin_language("la_Page")."</b> ";
if($StartPage>1)
{
- $target = $this->CurrentPage-10;
+ $target = $this->CurrentPage-10;
$prev_url = str_replace("{TargetPage}",$target,$url);
$o .= "<A HREF=\"$prev_url\" class=\"NAV_URL\"><<</A>";
}
-
+
for($p=$StartPage;$p<=$EndPage;$p++)
{
if($p!=$this->CurrentPage)
- {
+ {
$href = str_replace("{TargetPage}",$p,$url);
$o .= " <A HREF=\"$href\" class=\"NAV_URL\">$p</A> ";
}
else
{
$o .= " <SPAN class=\"CURRENT_PAGE\">$p</SPAN> ";
}
}
if($EndPage<$NumPages-1)
{
$target = $this->CurrentPage+10;
$next_url = str_replace("{TargetPage}",$target,$url);
$o .= "<A HREF=\"$next_url\" class=\"NAV_URL\"> &gt;&gt;</A>";
}
- return $o;
+ return $o;
}
function SliceItems()
{
global $objConfig;
$PerPage = (int)$objConfig->Get($this->PerPageVar);
if($PerPage<1)
$PerPage=20;
$NumPages = ceil($this->ListItems->NumItems() / $PerPage);
if($NumPages>1)
- {
+ {
$Start = ($this->CurrentPage-1)*$PerPage;
$this->ListItems->Items = array_slice($this->ListItems->Items,$Start,$PerPage);
}
}
-
+
function RefreshPageVar()
{
global $objSession;
if( (int)GetVar('lpn') > 0)
- {
+ {
$this->CurrentPage = $_GET["lpn"];
$objSession->SetVariable($this->CurrentPageVar,$this->CurrentPage);
}
else
$this->CurrentPage = $objSession->GetVariable($this->CurrentPageVar);
-
+
$this->ListItems->Page = $this->CurrentPage;
}
-
+
function PrintPageLinks($add_search = '')
{
global $imagesURL, $objSession, $lvErrorString;
-
+
if(strlen($this->PageLinks)>0)
{
return $this->PageLinks;
}
$this->RefreshPageVar();
-
+
if($this->CurrentPage<1)
$this->CurrentPage = 1;
if(!strlen($this->PageURL))
- {
+ {
$this->PageURL = $_SERVER["PHP_SELF"]."?env=".BuildEnv();
if(strlen($this->extra_env))
{
$this->PageURL .= "&".$this->extra_env;
}
elseif (GetVar('en') !== false) {
$this->PageURL .= '&en='.(int)GetVar('en');
}
-
+
$this->PageURL .= "&lpn={TargetPage}";
}
$cols = $this->ColumnHeaders->Count();
$o = "<TABLE cellSpacing=0 cellPadding=2 width=\"100%\" class=\"pagenav\"><tbody><TR >\n";
-
+
if(strlen($lvErrorString))
{
$o .= "<TD STYLE=\"border-bottom: 1px solid #000000;\" colspan=2><span class=\"validation_error\">$lvErrorString</SPAN></TD></TR><TR>";
-
+
}
if($this->SearchBar==FALSE)
- {
+ {
$o .= '<TD colspan="2">';
$o .= $this->GetAdminPageLinkList($this->PageURL);
$o .= "</TD>\n";
}
else
{
$val = inp_htmlize(str_replace(","," ", $this->SearchKeywords),1);
$o .= "<TD>";
- $o .= $this->GetAdminPageLinkList($this->PageURL)."</TD>";
+ $o .= $this->GetAdminPageLinkList($this->PageURL)."</TD>";
$o .= "<TD align=\"right\" valign=\"top\">$add_search".admin_language("la_prompt_Search");
$o .= " <INPUT TYPE=\"TEXT\" ID=\"ListSearchWord\" NAME=\"ListSearchWord\" VALUE=\"$val\">";
$o .= " <IMG align=\"middle\" height=24 width=24 name=\"imgSearch\" ID=\"imgSearch\" src=\"$imagesURL/itemicons/icon16_search.gif\" ";
- $o .= " onMouseOut=\"swap('imgSearch', '$imagesURL/itemicons/icon16_search.gif');\" ";
+ $o .= " onMouseOut=\"swap('imgSearch', '$imagesURL/itemicons/icon16_search.gif');\" ";
$o .= " onMouseOver=\"swap('imgSearch','$imagesURL/itemicons/icon16_search_f2.gif');\" ";
- $o .= " onClick=\"Submit_ListSearch('".$this->SearchAction."');\">";
+ $o .= " onClick=\"Submit_ListSearch('".$this->SearchAction."');\">";
$o .= " <IMG align=\"middle\" height=24 width=24 name=\"imgResetSearch\" ID=\"imgResetSearch\" src=\"$imagesURL/itemicons/icon16_search_reset.gif\" ";
- $o .= " onMouseOut=\"swap('imgResetSearch', '$imagesURL/itemicons/icon16_search_reset.gif');\" ";
+ $o .= " onMouseOut=\"swap('imgResetSearch', '$imagesURL/itemicons/icon16_search_reset.gif');\" ";
$o .= " onMouseOver=\"swap('imgResetSearch','$imagesURL/itemicons/icon16_search_reset_f2.gif');\" ";
- $o .= " onClick=\"Submit_ListSearch('".$this->SearchAction."_reset');\">";
+ $o .= " onClick=\"Submit_ListSearch('".$this->SearchAction."_reset');\">";
if(strlen($this->SearchDropdownId)>0)
{
$o .= " <IMG height=16 width=16 name=\"imgSearchDropDown\" src=\"$imagesURL/itemicons/icon16_search_dropdown.gif\" ";
- $o .= " onMouseOut=\"swap('imgResetDropDown', '$imagesURL/itemicons/icon16_search_dropdown.gif');\" ";
+ $o .= " onMouseOut=\"swap('imgResetDropDown', '$imagesURL/itemicons/icon16_search_dropdown.gif');\" ";
$o .= " onMouseOver=\"swap('imgResetDropDown','$imagesURL/itemicons/icon16_search_dropdown.gif');\" ";
- $o .= " onClick=\"ListSearch_PopUp('".$this->SearchDropdownId."');\">";
+ $o .= " onClick=\"ListSearch_PopUp('".$this->SearchDropdownId."');\">";
}
$o .= "</TD>";
}
$o .= "</TR></TABLE>";
return $o;
}
function PrintJavaScriptInit()
{
$o = '';
if($this->checkboxes)
- {
+ {
$o = "<script language=\"javascript\">\n";
$o .="<!--\n";
foreach($this->ListItems->Items as $li)
{
$o .= $this->CheckArray.".CheckList[".$this->CheckArray.".CheckList.length] = '".$li->Get($this->IdField)."';\n";
}
$o .= $this->CheckArray.".setImages();\n";
$o .="//-->\n";
$o .="</script>";
}
return $o;
}
function PrintList($footer = '',$add_search = '')
{
global $objSession;
if((int)$this->CurrentPage<1)
$this->CurrentPage=1;
$o = "\n";
-
+
if(is_object($this->ToolBar))
{
if($this->PrintToolBar)
$o .= $this->ToolBar->Build();
}
$o .= $this->PrintPageLinks($add_search);
$o .= "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\" class=\"tableborder\">\n";
if($this->ShowColumnHeaders)
{
$o .= $this->ColumnHeaders->PrintColumns();
}
if($this->ListItems->NumItems()>0)
- {
+ {
$o .= $this->PrintItems();
-
+
}
-
+
$o .= "$footer</TABLE>";
if($this->ListItems->NumItems()>0)
$o .= $this->PrintJavaScriptInit();
return $o;
}
}
Property changes on: branches/RC/admin/listview/listview.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.11
\ No newline at end of property
+1.11.2.1
\ No newline at end of property
Index: branches/RC/core/kernel/utility/debugger/debugger.js
===================================================================
--- branches/RC/core/kernel/utility/debugger/debugger.js (revision 9388)
+++ branches/RC/core/kernel/utility/debugger/debugger.js (revision 9389)
@@ -1,417 +1,430 @@
function DebugReq() {}
DebugReq.timeout = 5000; //5 seconds
DebugReq.makeRequest = function(p_url, p_busyReq, p_progId, p_successCallBack, p_errorCallBack, p_pass, p_object) {
//p_url: the web service url
//p_busyReq: is a request for this object currently in progress?
//p_progId: element id where progress HTML should be shown
//p_successCallBack: callback function for successful response
//p_errorCallBack: callback function for erroneous response
//p_pass: string of params to pass to callback functions
//p_object: object of params to pass to callback functions
if (p_busyReq) {
return;
}
var req = DebugReq.getRequest();
if (req != null) {
p_busyReq = true;
DebugReq.showProgress(p_progId);
req.onreadystatechange = function() {
if (req.readyState == 4) {
p_busyReq = false;
window.clearTimeout(toId);
if (req.status == 200) {
p_successCallBack(req,p_pass,p_object);
} else {
p_errorCallBack(req,p_pass,p_object);
}
}
}
req.open('GET', p_url, true);
req.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');
req.send(null);
var toId = window.setTimeout( function() {if (p_busyReq) req.abort();}, DebugReq.timeout );
}
}
DebugReq.getRequest = function() {
var xmlHttp;
try { xmlHttp = new ActiveXObject('MSXML2.XMLHTTP'); return xmlHttp; } catch (e) {}
try { xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); return xmlHttp; } catch (e) {}
try { xmlHttp = new XMLHttpRequest(); return xmlHttp; } catch(e) {}
return null;
}
DebugReq.showProgress = function(p_id) {
$Debugger.AppendRow(DebugReq.getProgressHtml());
}
DebugReq.getProgressHtml = function() {
return 'Loading ...';
}
DebugReq.getErrorHtml = function(p_req) {
//TODO: implement accepted way to handle request error
return "<p>" + "(" + p_req.status + ") " + p_req.statusText + "</p>"
}
// Debugger
function Debugger($row_separator, $errors_count, $fatal_error, $sql_count) {
this.RowSeparator = $row_separator;
this.IsFatalError = $fatal_error;
this.ErrorsCount = parseInt($errors_count);
this.SQLCount = parseInt($sql_count);
this.IsQueried = false;
this.IsVisible = false;
this.DebuggerDIV = document.getElementById('debug_layer');
this.DebuggerTable = document.getElementById('debug_table');
this.RowCount = 0;
this.busyRequest = false;
this.DragObject = null;
this.LastDragObject = null;
this.MouseOffset = [0,0];
this.ResizeHappening = false;
this.ResizeTimer = null;
this.InitialPos = null;
// window.$Debugger = this; // this should be uncommented in case if debugger variable is not $Debugger
this.AddEvent(window, 'scroll', function (ev) { window.$Debugger.Resize(ev); });
this.AddEvent(window, 'resize', function (ev) { window.$Debugger.Resize(ev); });
// this.AddEvent(window, 'keydown', function (ev) { window.$Debugger.KeyDown(ev); }); // don't work in IE
document.onkeydown = function(ev) { window.$Debugger.KeyDown(ev); }
}
Debugger.prototype.SetOpacity = function(opacity)
{
this.DebuggerToolbar.style.opacity = (opacity / 100);
this.DebuggerToolbar.style.MozOpacity = (opacity / 100);
this.DebuggerToolbar.style.KhtmlOpacity = (opacity / 100);
this.DebuggerToolbar.style.filter = "alpha(opacity=" + opacity + ")";
}
Debugger.prototype.ToolbarClick = function ($button) {
switch ($button.id) {
case 'dbg_ReloadFrame':
self.location.reload();
break;
case 'dbg_ShowDebugger':
this.Toggle();
break;
}
}
Debugger.prototype.AddToolbar = function($var_name) {
var $span = document.createElement('SPAN');
$span.style.position = 'absolute';
$span.style.zIndex= 99;
$span.style.top = '0px';
$span.style.left = '0px';
$span.id = 'debug_toolbar_span';
document.body.style.textAlign = 'left';
var $toolbar_content = '<td class="dbg-button" id="dbg_ReloadFrame" onclick="' + $var_name + '.ToolbarClick(this);">Reload Frame</td>';
if (this.ErrorsCount > 0) {
$toolbar_content += '<td class="dbg-separator"></td><td class="dbg-button debug_error" style="font-weight: bold;" id="dbg_ShowDebugger" onclick="' + $var_name + '.ToolbarClick(this);">Show Debugger (' + this.ErrorsCount + ' errors)</td>';
}
else {
$toolbar_content += '<td class="dbg-button" id="dbg_ShowDebugger" onclick="' + $var_name + '.ToolbarClick(this);">Show Debugger</td>';
}
if (this.SQLCount > 0) {
$toolbar_content += '<td class="dbg-separator"></td><td style="cursor: move">' + this.SQLCount + ' sqls</td>';
}
$span.innerHTML = '<table style="height: 30px" cellpadding="0" cellspacing="3" class="dbg-toolbar"><tr>' + $toolbar_content + '</tr></table>';
this.DebuggerToolbar = $span;
this.SetOpacity(20);
$span.onmouseover = function() {
$Debugger.SetOpacity(100);
}
$span.onmouseout = function() {
$Debugger.SetOpacity(20);
}
var $body = document.getElementsByTagName('BODY')[0];
$body.insertBefore($span, $body.firstChild);
// alert($span.offsetWidth)
this.MakeDragable('debug_toolbar_span', function() {}, function() {}, function() {});
}
Debugger.prototype.AppendRow = function($html) {
this.RowCount++;
var $tr = document.createElement('TR');
this.DebuggerTable.appendChild($tr);
$tr.className = 'debug_row_' + (this.RowCount % 2 ? 'odd' : 'even');
$tr.id = 'debug_row_' + this.RowCount;
var $td = document.createElement('TD');
$td.className = 'debug_cell';
$td.innerHTML = $html;
$tr.appendChild($td);
}
Debugger.prototype.RemoveRow = function($row_index) {
this.DebuggerTable.deleteRow($row_index);
this.RowCount--;
}
Debugger.prototype.Clear = function() {
if (!this.IsQueried) return false;
this.IsQueried = false;
while (this.DebuggerTable.rows.length) {
this.RemoveRow(0);
}
}
Debugger.prototype.KeyDown = function($e) {
var $KeyCode = this.GetKeyCode($e);
if ($KeyCode == 123 || $KeyCode == 27) {// F12 or ESC
this.Toggle($KeyCode);
this.StopEvent($e);
}
}
Debugger.prototype.OpenDOMViewer = function() {
var $value = document.getElementById('dbg_domviewer').value;
DOMViewerObj = ($value.indexOf('"') != -1) ? document.getElementById( $value.substring(1,$value.length-1) ) : eval($value);
window.open(this.DOMViewerURL);
return false;
}
Debugger.prototype.GetKeyCode = function($e) {
$e = ($e) ? $e : event;
var target = ($e.target) ? $e.target : $e.scrElement;
var charCode = ($e.charCode) ? $e.charCode : (($e.which) ? $e.which : $e.keyCode);
return charCode;
}
Debugger.prototype.StopEvent = function($e) {
$e = ($e) ? $e : event;
$e.cancelBubble = true;
if ($e.stopPropagation) $e.stopPropagation();
}
Debugger.prototype.Toggle = function($KeyCode) {
if(!this.DebuggerDIV) return false;
this.IsVisible = this.DebuggerDIV.style.display == 'none' ? false : true;
if (!this.IsVisible && $KeyCode == 27) {
return false;
}
this.Resize(null);
if (!this.IsQueried) {
this.Query();
}
this.DebuggerDIV.style.display = this.IsVisible ? 'none' : 'block';
}
Debugger.prototype.Query = function() {
DebugReq.makeRequest(this.DebugURL, this.busyRequest, '', this.successCallback, this.errorCallback, '', this);
}
Debugger.prototype.successCallback = function(p_req, p_pass, p_object) {
var contents = p_req.responseText;
contents = contents.split(p_object.RowSeparator);
if (contents.length == 1) {
alert('error: '+p_req.responseText);
p_object.IsQueried = true;
return ;
}
for (var $i = 0; $i < contents.length - 1; $i++) {
p_object.AppendRow(contents[$i]);
}
p_object.Refresh();
}
Debugger.prototype.errorCallback = function(p_req, p_pass, p_object) {
alert('AJAX ERROR: '+DebugReq.getErrorHtml(p_req));
p_object.Refresh();
}
Debugger.prototype.Refresh = function() {
// progress mether row
this.RemoveRow(0);
this.IsQueried = true;
this.DebuggerDIV.scrollTop = this.IsFatalError ? 10000000 : 0;
this.DebuggerDIV.scrollLeft = 0;
}
Debugger.prototype.Resize = function($e) {
if (!this.DebuggerDIV) return false;
var $pageTop = document.all ? document.body.offsetTop + document.body.scrollTop : window.scrollY;
this.DebuggerDIV.style.top = $pageTop + 'px';
this.DebuggerDIV.style.height = GetWindowHeight() + 'px';
return true;
}
function GetWindowHeight() {
var currWinHeight;
// if (document.body.clientHeight) {
// currWinHeight = document.body.clientHeight;
if (window.innerHeight) {//FireFox with correction for status bar at bottom of window
currWinHeight = window.innerHeight;
} else if (document.documentElement.clientHeight) {//IE 7 with correction for address bar
currWinHeight = document.documentElement.clientHeight;
} else if (document.body.offsetHeight) {//IE 4+
currWinHeight = document.body.offsetHeight + 10;
}
return currWinHeight - 10; // 10 - horizontal scrollbar height
}
/*function GetWinHeight() {
if (window.innerHeight) return window.innerHeight;
else if (document.documentElement.clientHeight) return document.documentElement.clientHeight;
else if (document.body.offsetHeight) return document.body.offsetHeight;
else return _winHeight;
}*/
Debugger.prototype.SetClipboard = function(copyText) {
if (window.clipboardData) {
// IE send-to-clipboard method.
window.clipboardData.setData('Text', copyText);
}
else if (window.netscape) {
// You have to sign the code to enable this or allow the action in about:config by changing user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
// Store support string in an object.
var str = Components.classes['@mozilla.org/supports-string;1'].createInstance(Components.interfaces.nsISupportsString);
if (!str) {
return false;
}
str.data = copyText;
// Make transferable.
var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if (!trans) {
return false;
}
// Specify what datatypes we want to obtain, which is text in this case.
trans.addDataFlavor('text/unicode');
trans.setTransferData('text/unicode', str, copyText.length * 2);
var clipid = Components.interfaces.nsIClipboard;
var clip = Components.classes['@mozilla.org/widget/clipboard;1'].getService(clipid);
if (!clip) {
return false;
}
clip.setData(trans, null, clipid.kGlobalClipboard);
}
}
Debugger.prototype.ShowProps = function($Obj, $Name) {
var $ret = '';
for ($Prop in $Obj) {
$ret += $Name + '.' + $Prop + ' = ' + $Obj[$Prop] + "\n";
}
return alert($ret);
}
Debugger.prototype.editFile = function($fileName, $lineNo) {
if (!document.all) {
alert('Only works in IE');
return;
}
if (!this.EditorPath) {
alert('Editor path not defined!');
return;
}
var $launch_object = new ActiveXObject('LaunchinIE.Launch');
var $editor_path = this.EditorPath;
$editor_path = $editor_path.replace('%F', $fileName);
$editor_path = $editor_path.replace('%L',$lineNo);
$launch_object.LaunchApplication($editor_path);
}
Debugger.prototype.ToggleTraceArgs = function($arguments_layer_id) {
var $arguments_layer = document.getElementById($arguments_layer_id);
$arguments_layer.style.display = ($arguments_layer.style.display == 'none') ? 'block' : 'none';
}
Debugger.prototype.AddEvent = function (el, evname, func) {
var $status = false;
if (document.all) {
$status = el.attachEvent('on' + evname, func);
} else {
$status = el.addEventListener(evname, func, true);
}
}
Debugger.prototype.mouseCoords = function(ev)
{
if(ev.pageX || ev.pageY){
var res = {x:ev.pageX, y:ev.pageY};
}
else {
var res = {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
return res;
}
Debugger.prototype.MakeDragable = function(object_id, startCallback, moveCallback, endCallback, options)
{
var drag_object = document.getElementById(object_id);
var cur_options = {'VerticalDrag': 1, 'HorizontalDrag': 1};
if (options) {
for(var i in options) {
cur_options[i] = options[i];
}
}
var the_debugger = this;
this.AddEvent(drag_object, 'mousedown', function(ev){
ev = ev || window.event;
- the_debugger.InitialPos = findPos(drag_object);
+ the_debugger.InitialPos = dbg_findPos(drag_object);
var coords = the_debugger.mouseCoords(ev);
- var pos = findPos(drag_object);
+ var pos = dbg_findPos(drag_object);
the_debugger.MouseOffset = [coords.x - pos[0], coords.y - pos[1]];
the_debugger.DragObject = drag_object;
the_debugger.LastDragObject = drag_object;
the_debugger.DragObject.style.position = 'absolute';
the_debugger.Options = cur_options;
startCallback(drag_object);
});
this.AddEvent(document, 'mousemove', function(ev) {
// window.status = 'mouse at: '+coords.x+','+coords.y;
if(the_debugger.DragObject){
ev = ev || window.event;
var coords = the_debugger.mouseCoords(ev);
if (the_debugger.Options.VerticalDrag) {
the_debugger.DragObject.style.top = (coords.y - the_debugger.MouseOffset[1] ) + 'px' // ;
}
if (the_debugger.Options.HorizontalDrag) {
the_debugger.DragObject.style.left = (coords.x - the_debugger.MouseOffset[0] ) + 'px' // ;
}
moveCallback(drag_object, coords)
return false;
}
});
this.AddEvent(document, 'mouseup', function(ev){
var tmp = the_debugger.DragObject;
the_debugger.DragObject = null;
if(tmp){
endCallback(tmp);
}
- var pos = findPos(drag_object);
+ var pos = dbg_findPos(drag_object);
});
+}
+
+function dbg_findPos(obj) {
+ var curleft = curtop = 0;
+ if (obj.offsetParent) {
+ curleft = obj.offsetLeft
+ curtop = obj.offsetTop
+ while (obj = obj.offsetParent) {
+ curleft += obj.offsetLeft
+ curtop += obj.offsetTop
+ }
+ }
+ return [curleft,curtop];
}
\ No newline at end of file
Property changes on: branches/RC/core/kernel/utility/debugger/debugger.js
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.13.2.3
\ No newline at end of property
+1.13.2.4
\ No newline at end of property
Index: branches/RC/core/kernel/startup.php
===================================================================
--- branches/RC/core/kernel/startup.php (revision 9388)
+++ branches/RC/core/kernel/startup.php (revision 9389)
@@ -1,136 +1,148 @@
<?php
define('KERNEL_PATH', FULL_PATH.'/core/kernel');
if (file_exists(FULL_PATH.'/kernel/kernel4/application.php')) {
die('Please remove '.FULL_PATH.'/kernel/kernel4 directiry - it has been moved to '.KERNEL_PATH.'<br/>Don\'t forget to clean Cache table afterwards');
}
if (!function_exists('getmicrotime')) {
function getmicrotime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
}
$globals_start = getmicrotime();
include_once(KERNEL_PATH.'/globals.php'); // non OOP functions used through kernel, e.g. print_pre
$globals_end = getmicrotime();
define('INPORTAL_ENV', 1);
+ $vars = parse_portal_ini(FULL_PATH.'/config.php');
+
+ $admin_directory = isset($vars['AdminDirectory']) ? $vars['AdminDirectory'] : '/admin';
+ define('ADMIN_DIRECTORY', $admin_directory);
+
# New path detection method: begin
- safeDefine('REL_PATH', '/admin');
- $ps = rtrim(preg_replace("/".preg_quote(rtrim(REL_PATH, '/'), '/')."$/", '', str_replace('\\', '/', dirname($_SERVER['PHP_SELF']))), '/');
+ if (defined('REL_PATH')) {
+ // location of index.php relatively to site base folder
+ $relative_path = preg_replace('/^[\/]{0,1}admin(.*)/', $admin_directory.'\\1', REL_PATH);
+ }
+ else {
+ // default index.php relative location is administrative console folder
+ define('REL_PATH', $admin_directory);
+ $relative_path = REL_PATH;
+ }
+
+ $ps = rtrim(preg_replace('/'.preg_quote(rtrim($relative_path, '/'), '/').'$/', '', str_replace('\\', '/', dirname($_SERVER['PHP_SELF']))), '/');
safeDefine('BASE_PATH', $ps); // in case in-portal has defined it before
# New path detection method: end
safeDefine('INPORTAL_TAGS', true);
safeDefine('SERVER_NAME', $_SERVER['HTTP_HOST']);
$https_mark = getArrayValue($_SERVER, 'HTTPS');
safeDefine('PROTOCOL', ($https_mark == 'on') || ($https_mark == '1') ? 'https://' : 'http://');
- $vars = parse_portal_ini(FULL_PATH.'/config.php');
-
safeDefine('APPLICATION_CLASS', isset($vars['ApplicationClass']) ? $vars['ApplicationClass'] : 'kApplication');
safeDefine('APPLICATION_PATH', isset($vars['ApplicationPath']) ? $vars['ApplicationPath'] : '/core/kernel/application.php');
if (isset($vars['WriteablePath'])) {
define('WRITEABLE', FULL_PATH.$vars['WriteablePath']);
define('WRITEBALE_BASE', $vars['WriteablePath']);
}
if ($vars === false || count($vars) == 0) {
global $rootURL;
echo 'In-Portal is probably not installed, or configuration file is missing.<br>';
echo 'Please use the installation script to fix the problem.<br><br>';
$install_script = file_exists(FULL_PATH.'/proj-base/install.php') ? 'core' : 'admin';
echo '<a href="'.PROTOCOL.SERVER_NAME.rtrim(BASE_PATH, '/').'/'.$install_script.'/install.php">Go to installation script</a><br><br>';
flush();
exit;
}
define('SQL_TYPE', $vars['DBType']);
define('SQL_SERVER', $vars['DBHost']);
define('SQL_USER', $vars['DBUser']);
define('SQL_PASS', $vars['DBUserPassword']);
define('SQL_DB', $vars['DBName']);
if (isset($vars['DBCollation']) && isset($vars['DBCharset'])) {
define('SQL_COLLATION', $vars['DBCollation']);
define('SQL_CHARSET', $vars['DBCharset']);
}
define('TABLE_PREFIX', $vars['TablePrefix']);
define('DOMAIN', getArrayValue($vars, 'Domain'));
ini_set('memory_limit', '50M');
define('MODULES_PATH', FULL_PATH);
define('EXPORT_PATH', defined('WRITEABLE') ? WRITEABLE.'/export' : FULL_PATH.'/admin/export');
define('GW_CLASS_PATH', MODULES_PATH.'/in-commerce/units/gateways/gw_classes'); // Payment Gateway Classes Path
define('SYNC_CLASS_PATH', FULL_PATH.'/sync'); // path for 3rd party user syncronization scripts
safeDefine('ENV_VAR_NAME','env');
safeDefine('IMAGES_PATH', '/kernel/images/');
safeDefine('IMAGES_PENDING_PATH', IMAGES_PATH.'pending/');
safeDefine('CUSTOM_UPLOAD_PATH', '/templates/images/custom/');
safeDefine('MAX_UPLOAD_SIZE', min(ini_get('upload_max_filesize'), ini_get('post_max_size'))*1024*1024);
if( ini_get('safe_mode') ) define('SAFE_MODE', 1);
safeDefine('EXPERIMENTAL_PRE_PARSE', 1);
safeDefine('SILENT_LOG', 0);
if( file_exists(FULL_PATH.'/debug.php') )
{
include_once(FULL_PATH.'/debug.php');
if(isset($dbg_options['DEBUG_MODE']) && $dbg_options['DEBUG_MODE']) {
$debugger_start = getmicrotime();
include_once(KERNEL_PATH.'/utility/debugger.php');
$debugger_end = getmicrotime();
if (isset($debugger) && constOn('DBG_PROFILE_INCLUDES')) {
$debugger->profileStart('inc_globals', KERNEL_PATH.'/globals.php', $globals_start);
$debugger->profileFinish('inc_globals', KERNEL_PATH.'/globals.php', $globals_end);
$debugger->profilerAddTotal('includes', 'inc_globals');
$debugger->profileStart('inc_debugger', KERNEL_PATH.'/utility/debugger.php', $debugger_start);
$debugger->profileFinish('inc_debugger', KERNEL_PATH.'/utility/debugger.php', $debugger_end);
$debugger->profilerAddTotal('includes', 'inc_debugger');
}
}
}
$includes = Array(
KERNEL_PATH.'/application.php',
FULL_PATH.APPLICATION_PATH,
KERNEL_PATH.'/db/db_connection.php',
KERNEL_PATH."/kbase.php",
KERNEL_PATH.'/utility/event.php',
KERNEL_PATH."/utility/factory.php",
KERNEL_PATH."/languages/phrases_cache.php",
KERNEL_PATH."/db/dblist.php",
KERNEL_PATH."/db/dbitem.php",
KERNEL_PATH."/event_handler.php",
KERNEL_PATH.'/db/db_event_handler.php',
);
foreach ($includes as $a_file) {
k4_include_once($a_file);
}
if (defined('DEBUG_MODE') && DEBUG_MODE && isset($debugger)) {
$debugger->AttachToApplication();
}
if( !function_exists('adodb_mktime') ) include_once(KERNEL_PATH.'/utility/adodb-time.inc.php');
// include_once(KERNEL_PATH."/utility/temp_handler.php"); // needed because of static calls from kBase
// up to here
// global constants
define ('KG_TO_POUND', 2.20462262);
define ('POUND_TO_KG', 0.45359237);
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/startup.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.55
\ No newline at end of property
+1.55.2.1
\ No newline at end of property
Index: branches/RC/core/kernel/application.php
===================================================================
--- branches/RC/core/kernel/application.php (revision 9388)
+++ branches/RC/core/kernel/application.php (revision 9389)
@@ -1,2557 +1,2555 @@
<?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;
/**
* New Parser (Experimental)
*
* @var NParser
*/
var $NParser;
/**
* 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();
/**
* Template names, that will be used instead of regular templates
*
* @var Array
*/
var $ReplacementTemplates = 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
var $LambdaElements = 1; // for autonumbering unnamed RenderElements [any better place for this prop? KT]
/**
* 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;
if (!constOn('SKIP_OUT_COMPRESSION')) {
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->debugMode = $this->isDebugMode();
$this->Conn->Connect(SQL_SERVER, SQL_USER, SQL_PASS, SQL_DB);
$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);
$this->HttpQuery =& $this->recallObject('HTTPQuery');
$this->Session =& $this->recallObject('Session');
$this->HttpQuery->AfterInit();
$this->LoadCache();
$this->InitConfig();
$this->Phrases->Init('phrases');
$this->UnitConfigReader->AfterConfigRead();
/*// 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();
}*/
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->ValidateLogin();
if($this->isDebugMode()) {
$this->Debugger->profileFinish('kernel4_startup');
}
$this->InitDone = true;
$this->HandleEvent( new kEvent('adm:OnStartup') );
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()
{
if (defined('IS_INSTALL') && IS_INSTALL && !$this->TableFound('Modules')) {
$this->registerModuleConstants();
return false;
}
$modules_helper =& $this->recallObject('ModulesHelper');
$this->ModuleInfo = $this->Conn->Query('SELECT * FROM '.TABLE_PREFIX.'Modules WHERE Loaded = 1 ORDER BY LoadOrder', 'Name');
$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', '/core/admin_templates');
return;
}
$path = $this->GetFrontThemePath();
if ($path === false) {
$this->ApplicationDie('No Primary Theme Selected or Current Theme is Unknown or Disabled');
}
safeDefine('THEMES_PATH', $path);
/*
$theme_id = $this->GetVar('m_theme');
if (!$theme_id) {
$theme_id = $this->GetDefaultThemeId();
if (!$theme_id) {
if (!defined('IS_INSTALL')) $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 GetFrontThemePath($force=0)
{
static $path=null;
if (!$force && isset($path)) return $path;
$theme_id = $this->GetVar('m_theme');
if (!$theme_id) {
$theme_id = $this->GetDefaultThemeId(1); //1 to force front-end mode!
if (!$theme_id) {
return false;
}
}
$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')) {
return false;
}
$path = '/themes/'.$theme->GetDBField('Name');
return $path;
}
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);
if (!$language_id && defined('IS_INSTALL') && IS_INSTALL) {
$language_id = 1;
}
return $language_id;
}
function GetDefaultThemeId($force_front=0)
{
static $theme_id = 0;
if($theme_id > 0) return $theme_id;
if (constOn('DBG_FORCE_THEME')) {
$theme_id = DBG_FORCE_THEME;
}
elseif (!$force_front && $this->IsAdmin()) {
$theme_id = 999;
}
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('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',null, 'kDBTagProcessor');
$this->registerClass('Template', KERNEL_PATH.'/parser/template.php');
$this->registerClass('TemplateParser', KERNEL_PATH.'/parser/template_parser.php',null, 'kDBTagProcessor');
if (defined('NPARSER') && 'NPARSER') {
$this->registerClass('NParser', KERNEL_PATH.'/nparser/nparser.php');
}
$this->registerClass('kEmailSendingHelper', KERNEL_PATH.'/utility/email_send.php', 'EmailSender', Array('kHelper'));
$this->registerClass('kSocket', KERNEL_PATH.'/utility/socket.php', 'Socket');
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?
/* Moved from MyApplication */
$this->registerClass('Inp1Parser',KERNEL_PATH.'/../units/general/inp1_parser.php','Inp1Parser');
$this->registerClass('InpSession',KERNEL_PATH.'/../units/general/inp_ses_storage.php','Session');
$this->registerClass('InpSessionStorage',KERNEL_PATH.'/../units/general/inp_ses_storage.php','SessionStorage');
$this->registerClass('kCatDBItem',KERNEL_PATH.'/../units/general/cat_dbitem.php');
$this->registerClass('kCatDBItemExportHelper',KERNEL_PATH.'/../units/general/cat_dbitem_export.php', 'CatItemExportHelper');
$this->registerClass('kCatDBList',KERNEL_PATH.'/../units/general/cat_dblist.php');
$this->registerClass('kCatDBEventHandler',KERNEL_PATH.'/../units/general/cat_event_handler.php');
$this->registerClass('kCatDBTagProcessor',KERNEL_PATH.'/../units/general/cat_tag_processor.php');
// Do not move to config - this helper is used before configs are read
$this->registerClass('kModulesHelper', KERNEL_PATH.'/../units/general/helpers/modules.php', 'ModulesHelper');
/* End moved */
}
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
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);
/*if (!$filename) {
$sql = 'SELECT Filename FROM '.TABLE_PREFIX.'CategoryItems WHERE ItemResourceId = '.$resource_id.' AND PrimaryCat = 1';
$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() // it's defined in startup.php - can be removed??
{
safeDefine('SERVER_NAME', $_SERVER['HTTP_HOST']);
}
/**
* Registers each module specific constants if any found
*
*/
function registerModuleConstants()
{
if (file_exists(KERNEL_PATH.'/constants.php')) {
k4_include_once(KERNEL_PATH.'/constants.php');
}
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');
/* @var $event_manager kEventManager */
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' && !$this->GetVar('debug_ajax')) {
// 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-Edit')) {
$cms_handler =& $this->recallObject('cms_EventHandler');
if (!$this->TemplatesCache->TemplateExists($t) && !$this->IsAdmin()) {
$t = $cms_handler->GetDesignTemplate();
}
/*else {
$cms_handler->SetCatByTemplate();
}*/
}
if ($this->isModuleEnabled('Proj-CMS')) {
$cms_handler =& $this->recallObject('st_EventHandler');
if (!$this->TemplatesCache->TemplateExists($t) && !$this->IsAdmin()) {
$t = $cms_handler->GetDesignTemplate();
}
}
if($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Parsing:');
}
if (defined('NPARSER') && 'NPARSER') {
$this->HTML = $this->NParser->Run( $t );
}
else {
$this->HTML = $this->Parser->ParseTemplate( $t );
}
if ($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application after Parsing:');
}
}
function InitParser()
{
if (defined('NPARSER') && 'NPARSER') {
if( !is_object($this->NParser) ) {
$this->NParser =& $this->recallObject('NParser');
$this->TemplatesCache =& $this->recallObject('TemplatesCache');
// can be removed in future
// $this->Parser =& $this->recallObject('TemplateParser');
$this->Parser =& $this->NParser;
}
}
else {
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);
if ($this->isDebugMode()) {
$this->EventManager->RunRegularEvents(reAFTER);
$this->Session->SaveData();
$this->HTML = ob_get_clean() . $this->HTML . $this->Debugger->printReport(true);
}
else {
$this->HTML = ob_get_clean().$this->HTML;
}
if ($this->UseOutputCompression()) {
header('Content-Encoding: gzip');
$compression_level = $this->ConfigValue('OutputCompressionLevel');
if ($compression_level < 0 || $compression_level > 9) $compression_level = 7;
echo gzencode($this->HTML, $compression_level);
}
else {
echo $this->HTML;
}
$this->UpdateCache();
flush();
if ($this->isDebugMode() && constOn('DBG_CACHE')) {
$cache =& $this->recallObject('Cache');
$cache->printStatistics();
}
$this->EventManager->RunRegularEvents(reAFTER);
$this->Session->SaveData();
}
/**
* Checks if output compression options is available
*
* @return string
*/
function UseOutputCompression()
{
if (constOn('IS_INSTALL') || constOn('DBG_ZEND_PRESENT') || constOn('SKIP_OUT_COMPRESSION')) return false;
return $this->ConfigValue('UseOutputCompression') && function_exists('gzencode') && strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
}
// 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);
}
function RemovePersistentVar($var)
{
return $this->Session->RemovePersistentVar($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);
}
function RecallPersistentVar($var, $default = false)
{
return $this->Session->RecallPersistentVar($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 StorePersistentVar($var, $val)
{
$this->Session->StorePersistentVar($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)
{
if (defined('NPARSER') && NPARSER) {
$p = $this->Parser->GetProcessor($prefix);
return $p->ProcessParsedTag($tag, $params, $prefix);
}
$a_tag = new Tag('',$this->Parser);
$a_tag->Tag = $tag;
$tmp=$this->Application->processPrefix($prefix);
$a_tag->Processor = $tmp['prefix'];
$a_tag->Special = $tmp['special'];
$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->isModuleEnabled('Proj-CMS')) {
$t = preg_replace('/^Content\//', '', $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 == '') $prefix = ADMIN_DIRECTORY;
if ( $this->IsAdmin() && $prefix == '_FRONT_END_') $prefix = '';
$index_file = $this->getIndexFile($prefix, $index_file, $params);
if (isset($params['_auto_prefix_'])) {
unset($params['_auto_prefix_']); // this is parser-related param, do not need to pass it here
}
$ssl = isset($params['__SSL__']) ? $params['__SSL__'] : null;
if ($ssl !== null) {
$session =& $this->recallObject('Session');
$cookie_url = trim($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 (isset($params['opener']) && $params['opener'] == 'u') {
$wid = $this->Application->GetVar('m_wid');
$stack_name = rtrim('opener_stack_'.$wid, '_');
$opener_stack = $this->RecallVar($stack_name);
if ($opener_stack && $opener_stack != serialize(Array())) {
$opener_stack = unserialize($opener_stack);
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);
if (isset($params['m_opener']) && $params['m_opener'] == 'u') {
array_pop($opener_stack);
if (!$opener_stack) {
$this->RemoveVar($stack_name);
// remove popups last templates, because popup is closing now
$this->RemoveVar('last_template_'.$wid);
$this->RemoveVar('last_template_popup_'.$wid);
// don't save popups last templates again :)
$this->SetVar('skip_last_template', 1);
}
else {
$this->StoreVar($stack_name, serialize($opener_stack));
}
}
return $ret;
}
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__']);
}
$force_rewrite = false;
if( isset($params['__MOD_REWRITE__']) )
{
$force_rewrite = true;
unset($params['__MOD_REWRITE__']);
}
$force_no_sid = false;
if( isset($params['__NO_SID__']) )
{
$force_no_sid = true;
unset($params['__NO_SID__']);
}
// append pass through variables to each link to be build
// $params = array_merge_recursive2($this->getPassThroughVariables($params), $params);
$params = array_merge($this->getPassThroughVariables($params), $params);
if ($force_rewrite || ($this->RewriteURLs($ssl) && !$no_rewrite))
{
$session =& $this->recallObject('Session');
if( $session->NeedQueryString() && !$force_no_sid ) $params['sid'] = $this->GetSID();
$url = $this->BuildEnv_NEW($t, $params, $pass, $pass_events);
$ret = $this->BaseURL($prefix, $ssl).$url.$map_link;
}
else
{
unset($params['pass_category']); // we don't need to pass it when mod_rewrite is off
$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
*
* @param Array $params
* @return Array
*/
function getPassThroughVariables(&$params)
{
static $cached_pass_through = null;
if (isset($params['no_pass_through']) && $params['no_pass_through']) {
unset($params['no_pass_through']);
return Array();
}
// 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')
{
if (!$pass) $pass = 'all';
$pass = trim(
preg_replace(
'/(?<=,|\\A)all(?=,|\\z)/',
trim($this->GetVar('passed'), ','),
trim($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) && $this->getUnitOption($prefix, 'CatalogItem');
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);
}
}
if (!$m_only) $params['pass_category'] = 1;
$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 || !defined('EXP_DIR_URLS')) {
$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) {
$mod_rw_helper =& $this->Application->recallObject('ModRewriteHelper');
$t = $mod_rw_helper->GetItemTemplate($category_id, $pass_element); // $pass_element should be the last processed element
// $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'], $params['opener'], $params['m_event']);
if ($this->GetVar('admin') && !isset($params['admin'])) {
$params['admin'] = 1;
}
if( isset($params['escape']) && $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)
{
$js_redirect = getArrayValue($params, 'js_redirect');
if (preg_match("/external:(.*)/", $t, $rets)) {
$location = $rets[1];
}
else {
if ($t == '' || $t === true) $t = $this->GetVar('t');
// pass prefixes and special from previous url
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);
//echo " location : $location <br>";
}
$a_location = $location;
$location = "Location: $location";
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");
}
}
}
ob_end_flush();
// session expiration is called from session initialization,
// that's why $this->Session may be not defined here
$session =& $this->Application->recallObject('Session');
/* @var $session Session */
$session->SaveData();
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.current" prefix_special. Also you may
* get user id by getting "u.current_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.current_id', $user_id);
if (!$this->IsAdmin()) {
// needed for "profile edit", "registration" forms ON FRONT ONLY
$this->SetVar('u_id', $user_id);
}
$this->StoreVar('user_id', $user_id);
if ($this->GetVar('expired') == 1) {
// this parameter is set only from admin
$user =& $this->recallObject('u.current');
$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);
}
if ($user_id != -2) {
// normal users + root
$this->LoadPersistentVars();
}
}
/**
* Loads current user persistent session data
*
*/
function LoadPersistentVars()
{
$this->Session->LoadPersistentVars();
}
-
-
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();
if (isset($this->Caches['ConfigVariables'])) {
$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;
if (defined('IS_INSTALL') && IS_INSTALL && !$this->TableFound('ConfigurationValues')) {
return false;
}
$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)
{
$this->InitParser(); // because kDBTagProcesor is in TemplateParser dependencies
$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->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 ) {
if ($errno == E_USER_ERROR) {
header('HTTP/1.0 500 Script Fatal Error');
echo ('<div style="background-color: #FEFFBF; margin: auto; padding: 10px; border: 2px solid red; text-align: center">
<strong>Fatal Error: </strong>
'."$errstr in $errfile on line $errline".'
</div>');
exit;
}
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 genealogical main prefix for subtable prefix passes
* OR prefix, that has been found in REQUEST and some how is parent of passed subtable prefix
*
* @param string $current_prefix
* @param string $real_top if set to true will return real topmost prefix, regardless of its id is passed or not
* @return string
* @access public
* @author Kostja / Alex
*/
function GetTopmostPrefix($current_prefix, $real_top=false)
{
// 1. get genealogical tree of $current_prefix
$prefixes = Array ($current_prefix);
while ( $parent_prefix = $this->getUnitOption($current_prefix, 'ParentPrefix') ) {
$current_prefix = $parent_prefix;
array_unshift($prefixes, $current_prefix);
}
if ($real_top) return $current_prefix;
// 2. find what if parent is passed
$passed = explode(',', $this->GetVar('all_passed'));
foreach ($prefixes as $a_prefix) {
if (in_array($a_prefix, $passed)) {
return $a_prefix;
}
}
return $current_prefix;
}
/**
* Triggers email event of type Admin
*
* @param string $email_event_name
* @param int $to_user_id
* @param array $send_params associative array of direct send params, possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEventAdmin($email_event_name, $to_user_id = -1, $send_params = false)
{
$event =& $this->EmailEvent($email_event_name, 1, $to_user_id, $send_params);
return $event;
}
/**
* Triggers email event of type User
*
* @param string $email_event_name
* @param int $to_user_id
* @param array $send_params associative array of direct send params, possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEventUser($email_event_name, $to_user_id = -1, $send_params = false)
{
$event =& $this->EmailEvent($email_event_name, 0, $to_user_id, $send_params);
return $event;
}
/**
* Triggers general email event
*
* @param string $email_event_name
* @param int $email_event_type ( 0 for User, 1 for Admin)
* @param int $to_user_id
* @param array $send_params associative array of direct send params,
* possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEvent($email_event_name, $email_event_type, $to_user_id = -1, $send_params = false)
{
$params = array(
'EmailEventName' => $email_event_name,
'EmailEventToUserId' => $to_user_id,
'EmailEventType' => $email_event_type,
);
if ($send_params) {
$params['DirectSendParams'] = $send_params;
}
$event_str = isset($send_params['use_special']) ? 'emailevents.'.$send_params['use_special'].':OnEmailEvent' : 'emailevents:OnEmailEvent';
$this->HandleEvent($event, $event_str, $params);
return $event;
}
/**
* Allows to check if user in this session is logged in or not
*
* @return bool
*/
function LoggedIn()
{
// no session during expiration process
return is_null($this->Session) ? false : $this->Session->LoggedIn();
}
/**
* 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) !== false;
}
function reportError($class, $method)
{
$this->Debugger->appendTrace();
trigger_error('depricated method <b>'.$class.'->'.$method.'(...)</b>', E_USER_ERROR);
}
/**
* Returns Window ID of passed prefix main prefix (in edit mode)
*
* @param string $prefix
* @return mixed
*/
function GetTopmostWid($prefix)
{
$top_prefix = $this->GetTopmostPrefix($prefix);
$mode = $this->GetVar($top_prefix.'_mode');
return $mode != '' ? substr($mode, 1) : '';
}
/**
* Get temp table name
*
* @param string $table
* @param mixed $wid
* @return string
*/
function GetTempName($table, $wid = '')
{
if (preg_match('/prefix:(.*)/', $wid, $regs)) {
$wid = $this->GetTopmostWid($regs[1]);
}
return TABLE_PREFIX.'ses_'.$this->GetSID().($wid ? '_'.$wid : '').'_edit_'.$table;
}
function GetTempTablePrefix($wid = '')
{
if (preg_match('/prefix:(.*)/', $wid, $regs)) {
$wid = $this->GetTopmostWid($regs[1]);
}
return TABLE_PREFIX.'ses_'.$this->GetSID().($wid ? '_'.$wid : '').'_edit_';
}
function IsTempTable($table)
{
return preg_match('/'.TABLE_PREFIX.'ses_'.$this->GetSID().'(_[\d]+){0,1}_edit_(.*)/',$table);
}
/**
* 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().'(_[\d]+){0,1}_edit_(.*)/',$temp_table, $rets) )
{
// cut wid from table end if any
return $rets[2];
}
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;
}
/* moved from MyApplication */
function getUserGroups($user_id)
{
switch($user_id)
{
case -1:
$user_groups = $this->ConfigValue('User_LoggedInGroup');
break;
case -2:
$user_groups = $this->ConfigValue('User_LoggedInGroup');
$user_groups .= ','.$this->ConfigValue('User_GuestGroup');
break;
default:
$sql = 'SELECT GroupId FROM '.TABLE_PREFIX.'UserGroup WHERE PortalUserId = '.$user_id;
$res = $this->Conn->GetCol($sql);
$user_groups = Array( $this->ConfigValue('User_LoggedInGroup') );
if(is_array($res))
{
$user_groups = array_merge($user_groups, $res);
}
$user_groups = implode(',', $user_groups);
}
return $user_groups;
}
/**
* Allows to detect if page is browsed by spider (293 agents supported)
*
* @return bool
*/
function IsSpider()
{
static $is_spider = null;
if (!isset($is_spider)) {
$user_agent = trim($_SERVER['HTTP_USER_AGENT']);
$robots = file(FULL_PATH.'/core/robots_list.txt');
foreach ($robots as $robot_info) {
$robot_info = explode("\t", $robot_info, 3);
if ($user_agent == trim($robot_info[2])) {
$is_spider = true;
break;
}
}
}
return $is_spider;
}
/**
* Allows to detect table's presense in database
*
* @param string $table_name
* @return bool
*/
function TableFound($table_name)
{
return $this->Conn->TableFound($table_name);
}
/**
* Returns counter value
*
* @param string $name counter name
* @param Array $params counter parameters
* @param string $query_name specify query name directly (don't generate from parmeters)
* @param bool $multiple_results
* @return mixed
*/
function getCounter($name, $params = Array (), $query_name = null, $multiple_results = false)
{
$count_helper =& $this->Application->recallObject('CountHelper');
/* @var $count_helper kCountHelper */
return $count_helper->getCounter($name, $params, $query_name, $multiple_results);
}
/**
* Resets counter, whitch are affected by one of specified tables
*
* @param string $tables comma separated tables list used in counting sqls
*/
function resetCounters($tables)
{
if (constOn('IS_INSTALL')) {
return ;
}
$count_helper =& $this->Application->recallObject('CountHelper');
/* @var $count_helper kCountHelper */
return $count_helper->resetCounters($tables);
}
/**
* Sends XML header + optionally displays xml heading
*
* @param string $xml_version
* @return string
* @author Alex
*/
function XMLHeader($xml_version = false)
{
$lang =& $this->recallObject('lang.current');
header('Content-type: text/xml; charset='.$lang->GetDBField('Charset'));
return $xml_version ? '<?xml version="'.$xml_version.'" encoding="'.$lang->GetDBField('Charset').'"?>' : '';
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/application.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.186.2.2
\ No newline at end of property
+1.186.2.3
\ No newline at end of property

Event Timeline