Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Thu, Feb 6, 4:46 PM

in-portal

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: branches/RC/kernel/include/parseditem.php
===================================================================
--- branches/RC/kernel/include/parseditem.php (revision 9285)
+++ branches/RC/kernel/include/parseditem.php (revision 9286)
@@ -1,3144 +1,3144 @@
<?php
global $ItemTypePrefixes;
$ItemTypePrefixes = array();
$ItemTagFiles = array();
function RegisterPrefix($class,$prefix,$file)
{
global $ItemTypePrefixes, $ItemTagFiles;
$ItemTypePrefixes[$class] = $prefix;
$ItemTagFiles[$prefix] = $file;
}
class clsParsedItem extends clsItemDB
{
var $TagPrefix;
var $Parser;
var $AdminParser;
function clsParsedItem($id=NULL)
{
global $TemplateRoot;
$this->clsItemDB();
$this->Parser = new clsTemplateList($TemplateRoot);
$this->AdminParser = new clsAdminTemplateList();
}
/* function ParseObject($element)
{
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
$tag = $this->TagPrefix."_".$field;
$ret = $this->parsetag($tag);
}
return $ret;
}
*/
function ParseTimeStamp($d,$attribs=array())
{
global $objSession;
if (isset($attribs['_tz'])) {
$timezone = $attribs['_tz'] == 'auto' ? null : $objSession->Get('tz');
$d = GetLocalTime($d, $timezone);
}
$part = isset($attribs['_part']) ? strtolower($attribs['_part']) : '';
if ($part) {
$ret = ExtractDatePart($part,$d);
}
else {
$ret = $d <= 0 ? '' : LangDate($d);
}
return $ret;
}
function ParseObject($element)
{
global $objConfig, $objCatList, $var_list_update, $var_list, $n_var_list_update, $m_var_list_update;
$extra_attribs = ExtraAttributes($element->attributes);
$ret = "";
if ($this->TagPrefix == "email" && strtolower($element->name) == "touser") {
$this->TagPrefix = "touser";
}
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
switch($field)
{
case 'primarycategorylink':
$m_var_list_update['cat'] = (int)$this->GetPrimaryCategory();
$m_var_list_update['p'] = 1;
$ret = str_replace('advanced_view.php','browse.php',$_SERVER['PHP_SELF']).'?env='.BuildEnv();
unset($m_var_list_update['cat']);
unset($m_var_list_update['p']);
return $ret;
break;
case 'primarycategory':
$db =& GetADODBConnection();
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$sql = 'SELECT '.$ml_formatter->LangFieldName('CachedNavbar').' FROM '.$objCatList->SourceTable.' WHERE CategoryId = '.(int)$this->GetPrimaryCategory();
$ret = prompt_language($objConfig->Get("Root_Name"));
if ($this->GetPrimaryCategory()) {
$ret .= ' > '.str_replace('&|&', ' > ', $db->GetOne($sql));
}
break;
case "id":
$ret = $this->Get($this->id_field);
break;
case "resourceid":
if(!$this->NoResourceId)
$ret = $this->Get("ResourceId");
break;
case "category":
$c = $objCatList->GetItem($this->Get("CategoryId"));
if(is_object($c))
{
$ret = $c->parsetag($element->attributes["_cattag"]);
}
break;
case "priority":
if($this->Get("Priority")!=0)
{
$ret = (int)$this->Get("Priority");
}
else
$ret = "";
break;
case "link":
/* if(method_exists($this,"ItemURL"))
{
$ret = $this->ItemURL($element->attributes["_template"],FALSE,"");
}
break; */
case "cat_link":
if(method_exists($this,"ItemURL"))
{
$ret = $this->ItemURL($element->attributes["_template"],TRUE,"");
}
break;
case "fullpath":
$ret = str_replace('&|&', ' &gt; ', $this->Get("CachedNavbar"));
if(!strlen($ret))
{
if(is_numeric($this->Get("CategoryId")))
{
$c = $objCatList->GetItem($this->Get("CategoryId"));
if(is_object($c))
$ret = $c->GetNavBar();
}
else
{
if(method_exists($this,"GetPrimaryCategory"))
{
$cat = $this->GetPrimaryCategory();
$c = $objCatList->GetItem($cat);
if(is_object($c))
$ret = $c->GetNavBar();
}
}
}
// $ret = $this->HighlightText($ret);
break;
case "relevance":
$style = $element->attributes["_displaymode"];
if(!strlen($style))
$style = "numerical";
switch ($style)
{
case "numerical":
$ret = (100 * LangNumber($this->Get("Relevance"),1))."%";
break;
case "bar":
$OffColor = $element->attributes["_offbackgroundcolor"];
$OnColor = $element->attributes["_onbackgroundcolor"];
$percentsOff = (int)(100 - (100 * $this->Get("Relevance"))); if ($percentsOff)
{
$percentsOn = 100 - $percentsOff;
$ret = "<td width=\"$percentsOn%\" bgcolor=\"$OnColor\"><img src=\"img/s.gif\"></td><td width=\"$percentsOff%\" bgcolor=\"$OffColor\"><img src=\"img/s.gif\"></td>";
}
else
$ret = "<td width=\"100%\" bgcolor=\"$OnColor\"><img src=\"img/s.gif\"></td>";
break;
case "graphical":
$OnImage = $element->attributes["_onimage"];
if (!strlen($OnImage))
break;
// Get image extension
$image_data = explode(".", $OnImage);
$image_ext = $image_data[count($image_data)-1];
unset($image_data[count($image_data)-1]);
$rel = (10 * LangNumber($this->Get("Relevance"),1));
$OnImage1 = join(".", $image_data);
if ($rel)
$img_src = $OnImage1."_".$rel.".".$image_ext;
else
$img_src = $OnImage;
$ret = "<img src=\"$img_src\" border=\"0\" alt=\"".(10*$rel)."\">";
break;
}
break;
case "rating":
$style = $element->GetAttributeByName("_displaymode");
if(!strlen($style))
$style = "numerical";
switch($style)
{
case "numerical":
$ret = LangNumber($this->Get("CachedRating"),1);
break;
case "text":
$ret = RatingText($this->Get("CachedRating"));
break;
case "graphical":
$OnImage = $element->attributes["_onimage"];
$OffImage = $element->attributes["_offimage"];
$images = RatingTickImage($this->Get("CachedRating"),$OnImage,$OffImage);
for($i=1;$i<=count($images);$i++)
{
$url = $images[$i];
if(strlen($url))
{
$ret .= "<IMG src=\"$url\" $extra_attribs >";
$ret .= $element->GetAttributeByName('_separator');
}
}
break;
}
break;
case "reviews":
$today = FALSE;
if(method_exists($this,"ReviewCount"))
{
if($element->GetAttributeByName("_today"))
$today = TRUE;
$ret = $this->ReviewCount($today);
$ret = ($element->GetAttributeByName("_dataexists") && empty($ret))? "" : $ret;
}
else
$ret = "";
break;
case "votes":
$ret = (int)$this->Get("CachedVotesQty");
break;
case "favorite":
if(method_exists($this,"IsFavorite"))
{
if($this->IsFavorite())
{
$ret = $element->attributes["_label"];
if(!strlen($ret))
$ret = "lu_favorite";
$ret = language($ret);
}
else
$ret = "";
}
break;
case "new":
if(method_exists($this,"IsNewItem"))
{
if($this->IsNewItem())
{
$ret = $element->GetAttributeByName('_label');
if(!strlen($ret))
$ret = "lu_new";
$ret = language($ret);
}
else
$ret = "";
}
break;
case "pop":
if(method_exists($this,"IsPopItem"))
{
if($this->IsPopItem())
{
$ret = $element->GetAttributeByName('_label');
if(!strlen($ret))
$ret = "lu_pop";
$ret = language($ret);
}
else
$ret = "";
}
break;
case "hot":
if(method_exists($this,"IsHotItem"))
{
if($this->IsHotItem())
{
$ret = $element->GetAttributeByName("_label");
if(!strlen($ret))
$ret = "lu_hot";
$ret = language($ret);
}
else
$ret = "";
}
break;
case "pick":
if($this->Get("EditorsPick")==1)
{
$ret = $element->GetAttributeByName('_label');
if(!strlen($ret))
$ret = "lu_pick";
$ret = language($ret);
}
else
$ret = "";
break;
case "admin_icon":
if(method_exists($this,"StatusIcon"))
{
if($element->GetAttributeByName("fulltag"))
{
$ret = "<IMG $extra_attribs SRC=\"".$this->StatusIcon()."\">";
}
else
$ret = $this->StatusIcon();
}
break;
case "custom":
if(method_exists($this,"GetCustomFieldValue"))
{
$field = $element->attributes["_customfield"];
$listvalue = $element->attributes["_listvalue"];
$default = $element->attributes["_default"];
if (strlen($field))
$ret = $this->GetCustomFieldValue($field, $default, $listvalue);
}
break;
case "image":
$default = $element->attributes["_primary"];
$name = $element->attributes["_name"];
if(strlen($name))
{
$img = $this->GetImageByName($name);
}
else
{
if($default)
$img = $this->GetDefaultImage();
}
if(is_object($img))
{
if(strlen($element->attributes["_imagetemplate"]))
{
$ret = $img->ParseTemplate($element->attributes["_imagetemplate"]);
break;
}
else
{
if($element->attributes["_thumbnail"])
{
$url = $img->parsetag("thumb_url");
}
else
{
if(!$element->attributes["_nothumbnail"])
{
$url = $img->parsetag("image_url");
}
else
{
$url = $img->FullURL(TRUE,"");
}
}
}
}
else
{
$url = $element->attributes["_defaulturl"];
}
if($element->attributes["_imagetag"])
{
if(strlen($url))
{
$ret = "<IMG src=\"$url\" $extra_attribs >";
}
else
$ret = "";
}
else
$ret = $url;
break;
case 'perm':
$cat_id = $this->GetPrimaryCategory();
$element->attributes['_category'] = $cat_id;
$ret = m_perm_text($element->attributes);
break;
default:
$ret = "Undefined:".$element->name;
break;
}
}
else if ($this->TagPrefix == 'email'){
$ret = "Undefined:".$element->name;
}
return $ret;
}
function ParseString($name)
{
$el = new clsHtmlTag();
$el->Clear();
$el->prefix = "inp";
$el->name = $name;
$numargs = func_num_args();
$arg_list = func_get_args();
for ($i = 1; $i < $numargs; $i++)
{
$attr = $arg_list[$i];
$parts = explode("=",$attr,2);
$name = $parts[0];
$val = $parts[1];
$el->attributes[$name] = $val;
}
return $this->ParseObject($el);
}
/* pass attributes as strings
ie: ParseStringEcho('tagname','_field="something" _data="somethingelse"');
*/
function ParseStringEcho($name)
{
$el = new clsHtmlTag();
$el->Clear();
$el->prefix = "inp";
$el->name = $name;
$numargs = func_num_args();
$arg_list = func_get_args();
for ($i = 1; $i < $numargs; $i++)
{
$attr = $arg_list[$i];
$parts = explode("=",$attr,2);
$name = $parts[0];
$val = $parts[1];
$el->attributes[$name] = $val;
}
echo $this->ParseObject($el);
}
function ParseElement($raw, $inner_html ="")
{
$tag = new clsHtmlTag($raw);
$tag->inner_html = $inner_html;
if($tag->parsed)
{
if($tag->name=="include" || $tag->name=="perm_include" || $tag->name=="lang_include")
{
$output = $this->Parser->IncludeTemplate($tag);
}
else
{
$output = $this->ParseObject($tag);
//echo $output."<br>";
if(substr($output,0,9)=="Undefined")
{
$output = $tag->Execute();
// if(substr($output,0,8)="{Unknown")
// $output = $raw;
} return $output;
}
}
else
return "";
}
function AdminParseTemplate($file)
{
$html = "";
$t = $this->AdminParser->GetTemplate($file);
if(is_object($t))
{
array_push($this->AdminParser->stack,$file);
$html = $t->source;
$next_tag = strpos($html,"<inp:");
while($next_tag)
{
$end_tag = strpos($html,"/>",$next_tag);
$tagtext = substr($html,$next_tag,($end_tag - $next_tag)+2);
$pre = substr($html,0,$next_tag);
$post = substr($html,$end_tag+2);
$inner = $this->ParseElement($tagtext);
$html = $pre.$inner.$post;
$next_tag = strpos($html,"<inp:");
}
array_pop($this->AdminParser->stack);
}
return $html;
}
function ParseTemplateText($text)
{
$html = $text;
$search = "<inp:".$this->TagPrefix;
//$next_tag = strpos($html,"<inp:");
$next_tag = strpos($html,$search);
while($next_tag)
{
$closer = strpos(strtolower($html),">",$next_tag);
$end_tag = strpos($html,"/>",$next_tag);
if($end_tag < $closer || $closer == 0)
{
$tagtext = substr($html,$next_tag,($end_tag - $next_tag)+2);
$pre = substr($html,0,$next_tag);
$post = substr($html,$end_tag+2);
$inner = $this->ParseElement($tagtext);
$html = $pre.$inner.$post;
}
else
{
$OldTagStyle = "</inp>";
## Try to find end of TagName
$TagNameEnd = strpos($html, " ", $next_tag);
## Support Old version
// $closer = strpos(strtolower($html),"</inp>",$next_tag);
if ($TagNameEnd)
{
$Tag = strtolower(substr($html, $next_tag, $TagNameEnd-$next_tag));
$TagName = explode(":", $Tag);
if (strlen($TagName[1]))
$CloserTag = "</inp:".$TagName[1].">";
}
else
{
$CloserTag = $OldTagStyle;
}
$closer = strpos(strtolower($html), $CloserTag, $next_tag);
## Try to find old tag closer
if (!$closer && ($CloserTag != $OldTagStyle))
{
$CloserTag = $OldTagStyle;
$closer = strpos(strtolower($html), $CloserTag, $next_tag);
}
$end_tag = strpos($html,">",$next_tag);
$tagtext = substr($html,$next_tag,($end_tag - $next_tag)+1);
$pre = substr($html,0,$next_tag);
$inner = substr($html,$end_tag+1,$closer-($end_tag+1));
$post = substr($html,$end_tag+1+strlen($inner) + strlen($CloserTag));
//echo "PRE:". htmlentities($pre,ENT_NOQUOTES);
//echo "INNER:". htmlentities($inner,ENT_NOQUOTES);
//echo "POST:". htmlentities($post,ENT_NOQUOTES);
$parsed = $this->ParseElement($tagtext);
if(strlen($parsed))
{
$html = $pre.$this->ParseTemplateText($inner).$post;
}
else
$html = $pre.$post;
}
$next_tag = strpos($html,$search);
}
return $html;
}
function ParseTemplate($tname)
{
global $objTemplate, $LogLevel,$ptime,$timestart;
//echo 'Saving ID'.$this->UniqueId().' in Main parseTempalate<br>';
//$GLOBALS[$this->TagPrefix.'_ID'] = $this->UniqueId();
LogEntry("Parsing $tname\n");
$LogLevel++;
$html = "";
$t = $objTemplate->GetTemplate($tname);
//$t = $this->Parser->GetTemplate($tname);
if( is_array($this->Parser->stack) ) $this->Parser->stack = Array();
if(is_object($t))
{
array_push($this->Parser->stack,$tname);
$html = $t->source;
$html = $this->ParseTemplateText($html);
array_pop($this->Parser->stack);
}
$LogLevel--;
LogEntry("Finished Parsing $tname\n");
$ptime = round(getmicrotime() - $timestart,6);
$xf = 867530; //Download ID
if($xf != 0)
{
$x2 = substr($ptime,-6);
$ptime .= $xf ^ $x2; //(1/1000);
}
return $html;
}
/**
* Sends EmailEvent to user
*
* @param string $EventName email event name
* @param mixed $ToUserId recipient's user_id or email address
* @param int $LangId language_id (not in use)
* @param string $RecptName recipient's name (only when ID not passed)
* @return kEvent
*/
function SendUserEventMail($EventName,$ToUserId,$LangId=NULL,$RecptName=NULL)
{
$send_params = is_numeric($ToUserId) ? Array() : Array ('to_email' => $ToUserId, 'to_name' => $RecptName);
return $this->Application->EmailEventUser($EventName, $ToUserId, $send_params);
}
function SendAdminEventMail($EventName,$LangId=NULL)
{
return $this->Application->EmailEventAdmin($EventName);
}
function parse_template($t)
{
}
}
class clsItemCollection
{
var $Items;
var $CurrentItem;
var $adodbConnection;
var $classname;
var $SourceTable;
var $LiveTable;
var $QueryItemCount;
var $AdminSearchFields = array();
var $SortField;
var $debuglevel;
var $id_field = null; // id field for list item
var $BasePermission;
var $Dummy = null;
// enshure that same sql won't be queried twice
var $QueryDone = false;
var $LastQuerySQL = '';
var $Prefix = '';
var $Special = '';
/**
* Application object
*
* @var kApplication
*/
var $Application = null;
/**
* Connection to database
*
* @var kDBConnection
*/
var $Conn = null;
function isLiveTable()
{
global $objSession;
return !preg_match('/'.GetTablePrefix().'ses_'.$objSession->GetSessionKey().'_edit_(.*)/', $this->SourceTable);
}
function SetTable($action, $table_name = null) // new by Alex
{
// $action = {'live', 'restore','edit'}
switch($action)
{
case 'live':
$this->LiveTable = $table_name;
$this->SourceTable = $this->LiveTable;
break;
case 'restore':
$this->SourceTable = $this->LiveTable;
break;
case 'edit':
global $objSession;
$this->SourceTable = $objSession->GetEditTable($this->LiveTable);
break;
}
}
function &GetDummy() // new by Alex
{
if( !isset($this->Dummy) )
- $this->Dummy =& new $this->classname();
+ $this->Dummy = new $this->classname();
$this->Dummy->tablename = $this->SourceTable;
return $this->Dummy;
}
function clsItemCollection()
{
if (class_exists('kApplication')) {
// just in case when aplication is not found
$this->Application =& kApplication::Instance();
$this->Conn =& $this->Application->GetADODBConnection();
}
$this->adodbConnection =& GetADODBConnection();
$this->Clear();
$this->BasePermission = '';
}
function GetIDField() // new by Alex
{
// returns id field for list item
if( !isset($this->id_field) )
{
$dummy =& $this->GetDummy();
$this->id_field = $dummy->IdField();
}
return $this->id_field;
}
function &GetNewItemClass()
{
return new $this->classname();
}
function Clear()
{
unset($this->Items);
$this->Items = array();
$this->CurrentItem=0;
}
function &SetCurrentItem($id)
{
$this->CurrentItem=$id;
return $this->GetItem($id);
}
function &GetCurrentItem()
{
if($this->CurrentItem>0)
{
return $this->GetItem($this->CurrentItem);
}
else
return FALSE;
}
function NumItems()
{
if(is_array($this->Items))
{
// echo "TEST COUNT: ".count($this->Items)."<BR>";
return count($this->Items);
}
else
return 0;
}
function ItemLike($index, $string)
{
// check if any of the item field
// even partially matches $string
$found = false;
$string = strtolower($string);
$item_data = $this->Items[$index]->GetData();
foreach($item_data as $field => $value)
if( in_array($field, $this->AdminSearchFields) )
if( strpos(strtolower($value), $string) !== false)
{
$found = true;
break;
}
return $found;
}
function DeleteItem($index) // by Alex
{
// deletes item with specific index from list
$i = $index; $item_count = $this->NumItems();
while($i < $item_count - 1)
{
$this->Items[$i] = $this->Items[$i + 1];
$i++;
}
unset($this->Items[$i]);
}
function ShowItems()
{
$i = 0; $item_count = $this->NumItems();
while($i < $item_count)
{
echo "Item No <b>$i</b>:<br>";
$this->Items[$i]->PrintVars();
$i++;
}
}
function SwapItems($Index,$Index2)
{
$temp = $this->Items[$Index]->GetData();
$this->Items[$Index]->SetData($this->Items[$Index2]->GetData());
$this->Items[$Index2]->SetData($temp);
}
function CopyResource($OldId,$NewId, $main_prefix)
{
$this->Clear();
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$OldId";
$this->Query_Item($sql);
// echo $sql."<br>\n";
if($this->NumItems()>0)
{
foreach($this->Items as $item)
{
$item->UnsetIdField();
$item->Set("ResourceId",$NewId);
$item->Create();
}
}
}
function ItemsOnClipboard()
{
global $objSession;
$clip = $objSession->GetPersistantVariable("ClipBoard");
$count = 0;
$table = $this->SourceTable;
$prefix = GetTablePrefix();
if(substr($table,0,strlen($prefix))==$prefix)
$table = substr($table,strlen($prefix));
if(strlen($clip))
{
$clipboard = ParseClipboard($clip);
if($clipboard["table"] == $table)
{
$count = count(explode(",",$clipboard["ids"]));
}
else
$count = 0;
}
else
$count = 0;
return $count;
}
function CopyToClipboard($command,$idfield, $idlist)
{
global $objSession,$objCatList;
if(is_array($idlist))
{
$list = implode(",",$idlist);
}
else
$list = $idlist;
$clip = $command."-".$objCatList->CurrentCategoryID().".".$this->SourceTable.".$idfield=".$list;
$objSession->SetVariable("ClipBoard",$clip);
}
function SortItems($asc=TRUE)
{
$done = FALSE;
$field = $this->SortField;
$ItemCount = $this->NumItems();
while(!$done)
{
$done=TRUE;
for($i=1;$i<$this->NumItems();$i++)
{
$doswap = FALSE;
if($asc)
{
$val1 = $this->Items[$i-1]->Get($field);
$val2 = $this->Items[$i]->Get($field);
$doswap = ($val1 > $val2);
}
else
{
$val1 = $this->Items[$i-1]->Get($field);
$val2 = $this->Items[$i]->Get($field);
$doswap = ($val1 < $val2);
}
if($doswap)
{
$this->SwapItems($i-1,$i);
$done = FALSE;
}
}
}
}
function &GetItem($ID,$LoadFromDB=TRUE)
{
$found=FALSE;
if(is_array($this->Items) && count($this->Items) )
{
for($x=0;$x<count($this->Items);$x++)
{
$i =& $this->GetItemRefByIndex($x);
if($i->UniqueID()==$ID)
{
$found=TRUE;
break;
}
}
}
if(!$found)
{
if($LoadFromDB)
{
$n = NULL;
$n = new $this->classname();
$n->tablename = $this->SourceTable;
$n->LoadFromDatabase($ID);
$n->Set( $n->IdField(), $ID ); // in case if no loaded set ID anyway
$index = array_push($this->Items, $n);
$i =& $this->Items[count($this->Items)-1];
}
else
$i = FALSE;
}
return $i;
}
function GetItemByIndex($index)
{
return $this->Items[$index];
}
function &GetItemRefByIndex($index)
{
return $this->Items[$index];
}
function &GetItemByField($Field, $Value, $LoadFromDB = true)
{
if( !is_array($Field) ) $Field = Array($Field);
if( !is_array($Value) ) $Value = Array($Value);
$found = false;
if( is_array($this->Items) )
{
foreach($this->Items as $i)
{
$sub_found = true;
foreach($Field as $key_index => $field_name)
{
$sub_found = $sub_found && ( $i->Get($field_name) == $Value[$key_index] );
}
if($sub_found)
{
$found = true;
break;
}
}
}
if( !$found && $LoadFromDB == true )
{
$sql = 'SELECT * FROM '.$this->SourceTable.' WHERE ';
foreach($Field as $key_index => $field_name)
{
$sql .= '(`'.$field_name.'` = '.$this->adodbConnection->qstr($Value[$key_index]).') AND ';
}
$sql = preg_replace('/(.*) AND $/', '\\1', $sql);
$res = $this->adodbConnection->Execute($sql);
if($res && !$res->EOF)
{
$i = $this->AddItemFromArray($res->fields);
$i->tablename = $this->SourceTable;
$i->Clean();
}
else
{
$i = false;
}
}
return $i;
}
function GetPage($Page, $ItemsPerPage)
{
$result = array_slice($this->Items, ($Page * $ItemsPerPage) - $ItemsPerPage, $ItemsPerPage);
return $result;
}
function GetNumPages($ItemsPerPage)
{
if( isset($_GET['reset']) && $_GET['reset'] == 1) $this->Page = 1;
return GetPageCount($ItemsPerPage,$this->QueryItemCount);
}
function &AddItemFromArray($data, $clean=FALSE)
{
$class = new $this->classname;
$class->SetFromArray($data);
$class->tablename = $this->SourceTable;
if($clean==TRUE)
$class->Clean();
//array_push($this->Items,$class);
$this->Items[] =& $class;
return $class;
}
function Query_Item($sql, $offset=-1,$rows=-1)
{
global $Errors, $objConfig;
//echo "Method QItem [<b>".get_class($this).'</b>], sql: ['.$sql.']<br>';
$dummy =& $this->GetDummy();
if( !$dummy->TableExists() )
{
if($this->debuglevel) echo "ERROR: table <b>".$dummy->tablename."</b> missing.<br>";
$this->Clear();
return false;
}
//echo "<b>".get_class($this)."</b><br>";
//echo "Rows = $rows && Offset = $offset<br>";
if($rows>-1 && $offset>-1)
{
//print_pre(debug_backtrace());
//echo "<b>Executing SelectLimit</b> $sql <b>Offset:</b> $offset,$rows<br>\n";
$result = $this->adodbConnection->SelectLimit($sql, $rows,$offset);
}
else {
$result = $this->adodbConnection->Execute($sql);
}
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Query_Item");
if($this->debuglevel) {
echo '<br><br>'.$sql.'<br><br>';
echo "Error: ".$this->adodbConnection->ErrorMsg()."<br>";
}
$this->Clear();
return false;
}
$this->Clear();
if($this->debuglevel > 0)
{
echo "This SQL: $sql<br><br>";
if( ($this->debuglevel > 1) && ($result->RecordCount() > 0) )
{
echo '<pre>'.print_r($result->GetRows(), true).'</pre>';
$result->MoveFirst();
}
}
//echo "SQL: $sql<br><br>";
LogEntry("SQL Loop Start\n");
$count = 0;
while ($result && !$result->EOF)
{
$count++;
$data = $result->fields;
$this->AddItemFromArray($data,TRUE);
if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 )
adodb_movenext($result);
else
$result->MoveNext();
}
LogEntry("SQL Loop End ($count iterations)\n");
$result->Free();
return $this->Items;
}
function GetOrderClause($FieldVar,$OrderVar,$DefaultField,$DefaultVar,$Priority=TRUE,$UseTableName=FALSE)
{
global $objConfig, $objSession;
if($UseTableName)
{
$TableName = $this->SourceTable.".";
}
else
$TableName = "";
$PriorityClause = $TableName."EditorsPick DESC, ".$TableName."Priority DESC";
if(strlen(trim($FieldVar))>0)
{
if(is_object($objSession))
{
if(strlen($objSession->GetPersistantVariable($FieldVar))>0)
{
$OrderBy = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ".
$objSession->GetPersistantVariable($OrderVar));
$FieldUsed = $objSession->GetPersistantVariable($FieldVar);
}
}
$OrderBy = trim($OrderBy);
if (strlen(trim($OrderBy))==0)
{
if(!$UseTableName)
{
$OrderBy = trim($DefaultField." ".$DefaultVar);
}
else
{
if(strlen(trim($DefaultField))>0)
{
$OrderBy = $this->SourceTable.".".$DefaultField.".".$DefaultVar;
}
$FieldUsed=$DefaultField;
}
}
}
if(($FieldUsed != "Priority" || strlen($OrderBy)==0) && $Priority==TRUE)
{
if(strlen($OrderBy)==0)
{
$OrderBy = $PriorityClause;
}
else
$OrderBy = $PriorityClause.", ".$OrderBy;
}
return $OrderBy;
}
function GetResourceIDList()
{
$ret = array();
foreach($this->Items as $i)
array_push($ret,$i->Get("ResourceId"));
return $ret;
}
function GetFieldList($field)
{
$ret = array();
foreach($this->Items as $i)
array_push($ret,$i->Get($field));
return $ret;
}
function SetCommonField($FieldName,$FieldValue)
{
for($i=0;$i<$this->NumItems();$i++)
{
$this->Items[$i]->Set($FieldName,$fieldValue);
$this->Items[$i]->Update();
}
}
function ClearCategoryItems($CatId,$CatTable = "CategoryItems")
{
$CatTable = AddTablePrefix($CatTable);
$sql = "SELECT * FROM ".$this->SourceTable." INNER JOIN $CatTable ".
" ON (".$this->SourceTable.".ResourceId=$CatTable.ItemResourceId) WHERE CategoryId=$CatId";
$this->Clear();
$this->Query_Item($sql);
if($this->NumItems()>0)
{
foreach($this->Items as $i)
{
$i->DeleteCategoryItems($CatId,$CatTable);
}
}
}
function CopyToEditTable($idfield = null, $idlist = 0)
{
global $objSession;
if($idfield == null) $idfield = $this->GetIDField();
$edit_table = $objSession->GetEditTable($this->SourceTable);
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
if(is_array($idlist))
{
$list = implode(",",$idlist);
}
else
$list = $idlist;
$query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield IN ($list)";
$insert = "CREATE TABLE ".$edit_table." ".$query;
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
$this->adodbConnection->Execute($insert);
}
function CreateEmptyEditTable($idfield = null)
{
global $objSession;
if($idfield == null) $idfield = $this->GetIDField();
$edit_table = $objSession->GetEditTable($this->SourceTable);
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
$query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield = -1";
$insert = "CREATE TABLE ".$edit_table." ".$query;
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
$this->adodbConnection->Execute($insert);
//echo $insert."<br>";
}
function CopyFromEditTable($idfield = null)
{
global $objSession;
$GLOBALS['_CopyFromEditTable']=1;
$dropRelTableFlag = false;
if($idfield == null) $idfield = $this->GetIDField();
$edit_table = $objSession->GetEditTable($this->SourceTable);
$sql = "SELECT * FROM $edit_table";
$rs = $this->adodbConnection->Execute($sql);
$item_ids = Array();
while ($rs && !$rs->EOF) {
$data = $rs->fields;
$c = new $this->classname;
$c->SetFromArray($data);
$c->idfield = $idfield;
$c->Dirty();
if($c->Get($idfield) < 1)
{
$old_id = $c->Get($idfield);
$c->UnsetIdField();
if(!is_numeric($c->Get("OrgId")) || $c->Get("OrgId")==0)
{
$c->Clean(array("OrgId"));
}
else
{
if($c->Get("Status") != -2)
{
$org = new $this->classname();
$org->LoadFromDatabase($c->Get("OrgId"));
$org->DeleteCustomData();
$org->Delete(TRUE);
$c->Set("OrgId",0);
}
}
$c->Create();
}
$item_ids[] = $c->UniqueId(); // save item id for future use
if(is_numeric($c->Get("ResourceId")))
{
if( isset($c->Related) && is_object($c->Related) )
{
$r = $c->Related;
$r->CopyFromEditTable($c->Get("ResourceId"));
$dropRelTableFlag = true;
}
unset($r);
if( isset($c->Reviews) && is_object($c->Reviews) )
{
$r = $c->Reviews;
$r->CopyFromEditTable($c->Get("ResourceId"),true);
}
}
if(!is_numeric($c->Get("OrgId")) || $c->Get("OrgId")==0)
{
$c->Clean(array("OrgId"));
}
else
{
if($c->Get("Status") != -2)
{
$org = new $this->classname();
$org->LoadFromDatabase($c->Get("OrgId"));
$org->DeleteCustomData();
$org->Delete(TRUE);
$c->Set("OrgId",0);
}
}
$GLOBALS['_CopyFromEditTable']=1;
if(method_exists($c,"CategoryMemberList"))
{
$cats = $c->CategoryMemberList($objSession->GetEditTable("CategoryItems"));
$ci_table = $objSession->GetEditTable('CategoryItems');
$primary_cat = $c->GetPrimaryCategory($ci_table);
$c->Update();
UpdateCategoryItems($c,$cats,$primary_cat);
}
else
$c->Update();
unset($c);
unset($r);
$rs->MoveNext();
}
$objReviews = new clsItemReviewList();
$objReviews->PurgeEditTable();
if ($dropRelTableFlag)
{
$objRelGlobal = new clsRelationshipList();
$objRelGlobal->PurgeEditTable();
}
if($edit_table) @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$objSession->GetEditTable("CategoryItems"));
unset($GLOBALS['_CopyFromEditTable']);
return $item_ids;
}
function GetNextTempID()
{
// get next temporary id (lower then zero) from temp table
$db =& $this->adodbConnection;
$sql = 'SELECT MIN(%s) AS MinValue FROM %s';
return $db->GetOne( sprintf($sql, $this->GetIDField(), $this->SourceTable) ) - 1;
}
function PurgeEditTable($idfield = null)
{
global $objSession;
if($idfield == null) $idfield = $this->GetIDField();
$edit_table = $objSession->GetEditTable($this->SourceTable);
/* $rs = $this->adodbConnection->Execute("SELECT * FROM $edit_table");
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = new $this->classname;
$c->SetFromArray($data);
$c->id_field = $idfield;
$c->tablename = $edit_table;
$c->Delete();
$rs->MoveNext();
}*/
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$objSession->GetEditTable("CategoryItems"));
}
function CopyCatListToEditTable($idfield, $idlist)
{
global $objSession;
$edit_table = $objSession->GetEditTable("CategoryItems");
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
if(is_array($idlist))
{
$list = implode(",",$idlist);
}
else
$list = $idlist;
$query = "SELECT * FROM ".GetTablePrefix()."CategoryItems WHERE $idfield IN ($list)";
$insert = "CREATE TABLE ".$edit_table." ".$query;
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
$this->adodbConnection->Execute($insert);
}
function CreateEmptyCatListTable($idfield)
{
global $objSession;
$edit_table = $objSession->GetEditTable("CategoryItems");
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
$query = "SELECT * FROM ".GetTablePrefix()."CategoryItems WHERE $idfield = -1";
$insert = "CREATE TABLE ".$edit_table." ".$query;
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
$this->adodbConnection->Execute($insert);
}
function RefreshPage($page_var, $total_items)
{
global $objConfig, $objSession;
$this->QueryItemCount = $total_items;
if ( (int)GetVar('lpn') > 0)
{
$this->Page = $_GET['lpn'];
}
elseif ($objConfig->Get($page_var))
{
$this->Page = $objConfig->Get($page_var);
}
if ( ($this->Page > $this->GetNumPages($this->PerPage) || $this->Page == 0) && ($this->PerPage != -1) )
{
$this->Page = 1;
}
$objSession->SetVariable($page_var, $this->Page);
}
function PurgeCatListEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable("CategoryItems");
$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function AdminSearchWhereClause($SearchList)
{
$sql = "";
if( !is_array($SearchList) ) $SearchList = explode(",",$SearchList);
// remove empty elements
$SearchListTmp=Array();
for($f = 0; $f < count($SearchList); $f++)
if($SearchList[$f])
$SearchListTmp[]=$SearchList[$f];
$SearchList=$SearchListTmp;
if( !count($SearchList) || !count($this->AdminSearchFields) ) return '';
for($f = 0; $f < count($SearchList); $f++)
{
$value = $SearchList[$f];
if( strlen($value) )
{
$inner_sql = "";
for($i = 0; $i < count($this->AdminSearchFields); $i++)
{
$field = $this->AdminSearchFields[$i];
if( strlen( trim($value) ) )
{
if( strlen($inner_sql) ) $inner_sql .= " OR ";
$inner_sql .= $field." LIKE '%".$value."%'";
}
}
if( strlen($inner_sql) )
{
$sql .= '('.$inner_sql.') ';
if($f < count($SearchList) - 1) $sql .= " AND ";
}
}
}
return $sql;
}
function BackupData($OutFileName,$Start,$Limit)
{
$fp=fopen($Outfile,"a");
if($fp)
{
if($Start==1)
{
$sql = "DELETE FROM ".$this->SourceTable;
fputs($fp,$sql);
}
$this->Query_Item("SELECT * FROM ".$this->SourceTable." LIMIT $Start, $Limit");
foreach($this->Items as $i)
{
$sql = $i->CreateSQL();
fputs($fp,$sql);
}
fclose($fp);
$this->Clear();
}
}
function RestoreData($InFileName,$Start,$Limit)
{
$res = -1;
$fp=fopen($InFileName,"r");
if($fp)
{
fseek($fp,$Start);
$Line = 0;
while($Line < $Limit)
{
$sql = fgets($fp,16384);
$this->adodbConnection->Execute($sql);
$Line++;
}
$res = ftell($fp);
fclose($fp);
}
return $res;
}
function Delete_Item($Id, $DetectCategories = false)
{
global $objCatList;
$l =& $this->GetItem($Id);
$l->BasePermission=$this->BasePermission;
if (!$DetectCategories) {
$l->DeleteCategoryItems($objCatList->CurrentCategoryID());
}
else {
$l->RemoveFromAllCategories();
$l->Delete();
}
}
function Move_Item($Id, $OldCat, $ParentTo)
{
global $objCatList;
$l = $this->GetItem($Id);
$l->BasePermission=$this->BasePermission;
$l->AddtoCategory($ParentTo);
$l->RemoveFromCategory($OldCat);
}
function Copy_Item($Id, $ParentTo)
{
$l = $this->GetItem($Id);
$l->BasePermission=$this->BasePermission;
$l->AddtoCategory($ParentTo);
}
}/* clsItemCollection */
class clsItemList extends clsItemCollection
{
var $Page;
var $PerPageVar;
var $DefaultPerPage; // use this perpage value in case if no found in config
var $EnablePaging;
var $MaxListCount = 0;
var $PageEnvar;
var $PageEnvarIndex;
var $ListType;
var $LastLimitClause = ''; // used to store last limit cluse used in query
function setPageFromENV()
{
$this->Page=$GLOBALS[$this->PageEnvar][$this->PageEnvarIndex];
}
function clsItemList()
{
$this->clsItemCollection();
$this->EnablePaging = TRUE;
$this->PageEnvarIndex = "p";
}
function GetPageLimitSQL()
{
global $objConfig;
$limit = NULL;
if($this->EnablePaging)
{
if($this->Page<1)
$this->Page=1;
//echo "Limited to ".$objConfig->Get($this->PerPageVar)." items per page<br>\n";
if(is_numeric($objConfig->Get($this->PerPageVar)))
{
$Start = ($this->Page-1)*$objConfig->Get($this->PerPageVar);
$limit = "LIMIT ".$Start.",".$objConfig->Get($this->PerPageVar);
}
else
$limit = NULL;
}
else
{
if($this->MaxListCount)
{
$limit = 'LIMIT 0, '.$this->MaxListCount;
}
}
return $limit;
}
function GetPageOffset()
{
$Start = 0;
if($this->EnablePaging)
{
if($this->Page < 1) $this->Page = 1;
$PerPage = $this->GetPerPage();
$Start = ($this->Page - 1) * $PerPage;
}
else
{
if((int)$this->MaxListCount == 0) $Start = -1;
}
return $Start;
}
function GetPageRowCount()
{
if($this->EnablePaging)
{
if($this->Page < 1) $this->Page = 1;
//echo "Got PerPage: ".$this->GetPerPage()."<br>";
return $this->GetPerPage();
}
else
return (int)$this->MaxListCount;
}
function Query_Item($sql,$limit = null, $fix_method = 'set_first')
{
// query itemlist (module items) using $sql specified
// apply direct limit clause ($limit) or calculate it if not specified
// fix invalid page in case if needed by method specified in $fix_method
if(strlen($limit))
{
$sql .= " ".$limit;
return parent::Query_Item($sql);
}
else
{
//echo "page fix pre (class: ".get_class($this).")<br>";
$this->QueryItemCount = QueryCount($sql); // must get total item count before fixing
$this->FixInvalidPage($fix_method);
// specially made for cats delete
if ( GetVar('Action', true) != 'm_cat_delete') {
return parent::Query_Item($sql,$this->GetPageOffset(),$this->GetPageRowCount());
}
else {
return parent::Query_Item($sql);
}
}
}
function Query_List($whereClause,$orderByClause=NULL,$JoinCats=TRUE,$fix_method='set_first')
{
global $objSession, $Errors;
if($JoinCats)
{
$cattable = GetTablePrefix()."CategoryItems";
$t = $this->SourceTable;
$sql = "SELECT *,CategoryId FROM $t INNER JOIN $cattable ON $cattable.ItemResourceId=$t.ResourceId";
}
else
$sql = "SELECT * FROM ". $this->SourceTable;
if(trim($whereClause)!="")
{
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
}
if(strlen($orderByClause)>0)
{
if(substr($orderByClause,0,8)=="ORDER BY")
{
$sql .= " ".$orderByClause;
}
else
{
$sql .= " ORDER BY $orderByClause";
}
}
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql."<br>\n";
return $this->Query_Item($sql, null, $fix_method);
}
function GetPerPage()
{
//echo "Getting Per Page ".get_class($this)."<br>";
// return category perpage
global $objConfig;
$PerPage = $objConfig->Get( $this->PerPageVar );
if( !is_numeric($PerPage) ) $PerPage = $this->DefaultPerPage ? $this->DefaultPerPage : 10;
//print_pre(debug_backtrace());
//echo "Returning: $PerPage<br>";
return $PerPage;
}
/**
* Returns current page from env var
*
* @return int
*/
function getEnvPage()
{
$var_name = preg_replace('/(.*)_update$/', '\\1', $this->PageEnvar);
return $GLOBALS[$var_name]['p'];
}
function FixInvalidPage($fix_method = 'set_first')
{
// in case if current page > total page count,
// then set current page to last possible "set_last"
// or first possible "set_first"
$PerPage = $this->GetPerPage();
$NumPages = ceil( $this->GetNumPages($PerPage) );
/*
echo "=====<br>";
echo "Class <b>".get_class($this)."</b>: Page ".$this->Page." of $NumPages<br>";
echo "PerPage: $PerPage<br>";
echo "Items Queries: ".$this->QueryItemCount."<br>";
echo "=====<br>";
*/
// if ( $this->getEnvPage() ) $fix_method = 'set_current';
if( ($this->Page > $NumPages || $this->Page == 0) && $PerPage != -1)
{
switch($fix_method)
{
case 'set_first':
$this->Page = 1;
//echo "Move 2 First (class <b>".get_class($this)."</b>)<br>";
break;
case 'set_last':
$this->Page = $NumPages;
//echo "Move 2 Last (class <b>".get_class($this)."</b>)<br>";
break;
case 'set_current':
$this->Page = $this->getEnvPage();
//echo "Move 2 Page reflected in env (class <b>".get_class($this)."</b>)<br>";
break;
}
$this->SaveNewPage();
}
}
function SaveNewPage()
{
// redefine in each list, should save to env array new page value
}
function GetPageLinkList($dest_template=NULL,$page = "",$PagesToList=10, $HideEmpty=TRUE,$EnvSuffix = '', $extra_attributes = '')
{
global $objConfig, $var_list_update, $var_list;
$url_params = $EnvSuffix ? ExtractParams($EnvSuffix) : Array();
$v= $this->PageEnvar;
global ${$v};
// if(!strlen($page)) $page = GetIndexURL(2);
$PerPage = $objConfig->Get($this->PerPageVar);
if($PerPage < 1) $PerPage = 20;
$NumPages = ceil( $this->GetNumPages($PerPage) );
if($NumPages == 1 && $HideEmpty) return '';
$var_list_update['t'] = isset($dest_template) && $dest_template ? $dest_template : $var_list['t'];
$o = '';
if( $this->Page == 0 || !is_numeric($this->Page) ) $this->Page = 1;
if($this->Page > $NumPages) $this->Page = $NumPages;
$StartPage = (int)$this->Page - ($PagesToList / 2);
if($StartPage < 1) $StartPage = 1;
$EndPage = $StartPage + ($PagesToList - 1);
if($EndPage > $NumPages)
{
$EndPage = $NumPages;
$StartPage = $EndPage - ($PagesToList - 1);
if($StartPage < 1) $StartPage = 1;
}
$o = '';
if($StartPage > 1)
{
${$v}[$this->PageEnvarIndex] = $this->Page - $PagesToList;
$prev_url = HREF_Wrapper('', $url_params);
$o .= '<a href="'.$prev_url.'" '.$extra_attributes.'>&lt;&lt;</a>';
}
for($p = $StartPage; $p <= $EndPage; $p++)
{
if($p != $this->Page)
{
${$v}[$this->PageEnvarIndex] = $p;
$href = HREF_Wrapper('', $url_params);
$o .= ' <a href="'.$href.'"'.$extra_attributes.'>'.$p.'</a> ';
}
else
{
$o .= ' <span class="current-page">'.$p.'</span>';
}
}
if($EndPage < $NumPages && $EndPage > 0)
{
${$v}[$this->PageEnvarIndex] = $this->Page + $PagesToList;
$next_url = HREF_Wrapper('', $url_params);
$o .= '<a href="'.$next_url.'"'.$extra_attributes.'> &gt;&gt;</a>';
}
unset(${$v}[$this->PageEnvarIndex],$var_list_update["t"] );
return $o;
}
function GetAdminPageLinkList($url)
{
global $objConfig;
$update =& $GLOBALS[$this->PageEnvar]; // env_var_update
$page_backup = $update[$this->PageEnvarIndex];
// insteresting stuff :)
if(!$this->PerPageVar) $this->PerPageVar = "Perpage_Links";
$PerPage = $objConfig->Get($this->PerPageVar);
if($PerPage < 1) $PerPage = 20;
$NumPages = ceil($this->GetNumPages($PerPage));
//echo $this->CurrentPage." of ".$NumPages." Pages";
if($this->Page > $NumPages) $this->Page = $NumPages;
$StartPage = $this->Page - 5;
if($StartPage < 1) $StartPage = 1;
$EndPage = $StartPage + 9;
if($EndPage > $NumPages)
{
$EndPage = $NumPages;
$StartPage = $EndPage-9;
if($StartPage < 1) $StartPage = 1;
}
$o = '';
if($StartPage > 1)
{
$update[$this->PageEnvarIndex]= $this->Page - 10;
$prev_url = $url.'?env='.BuildEnv();
$o .= '<a href="'.$prev_url.'">&lt;&lt;</a>';
}
for($p = $StartPage; $p <= $EndPage; $p++)
{
if($p != $this->Page)
{
$update[$this->PageEnvarIndex] = $p;
$href = $url.'?env='.BuildEnv();
$o .= ' <a href="'.$href.'" class="NAV_URL">'.$p.'</a> ';
}
else
{
$o .= '<SPAN class="CURRENT_PAGE">'.$p.'</SPAN>';
}
}
if($EndPage < $NumPages)
{
$update[$this->PageEnvarIndex] = $this->Page + 10;
$next_url = $url.'?env='.BuildEnv();
$o .= '<a href="'.$next_url.'"> &gt;&gt;</a>';
}
$update[$this->PageEnvarIndex] = $page_backup;
return $o;
}
}
function ParseClipboard($clip)
{
$ret = array();
$parts = explode(".",$clip,3);
$command = $parts[0];
$table = $parts[1];
$prefix = GetTablePrefix();
if(substr($table,0,strlen($prefix))==$prefix)
$table = substr($table,strlen($prefix));
$subparts = explode("=",$parts[2],2);
$idfield = $subparts[0];
$idlist = $subparts[1];
$cmd = explode("-",$command);
$ret["command"] = $cmd[0];
$ret["source"] = $cmd[1];
$ret["table"] = $table;
$ret["idfield"] = $idfield;
$ret["ids"] = $idlist;
//print_pre($ret);
return $ret;
}
function UpdateCategoryItems($item,$NewCatList,$PrimaryCatId = false)
{
global $objCatList;
$CurrentList = explode(",",$item->CategoryMemberList());
$del_list = array();
$ins_list = array();
if(!is_array($NewCatList))
{
if(strlen(trim($NewCatList))==0)
$NewCatList = $objCatList->CurrentCategoryID();
$NewCatList = explode(",",$NewCatList);
}
//print_r($NewCatList);
for($i=0;$i<count($NewCatList);$i++)
{
$cat = $NewCatList[$i];
if(!in_array($cat,$CurrentList))
$ins_list[] = $cat;
}
for($i=0;$i<count($CurrentList);$i++)
{
$cat = $CurrentList[$i];
if(!in_array($cat,$NewCatList))
$del_list[] = $cat;
}
for($i=0;$i<count($ins_list);$i++)
{
$cat = $ins_list[$i];
$item->AddToCategory($cat);
}
for($i=0;$i<count($del_list);$i++)
{
$cat = $del_list[$i];
$item->RemoveFromCategory($cat);
}
if($PrimaryCatId !== false) $item->SetPrimaryCategory($PrimaryCatId);
}
class clsCatItemList extends clsItemList
{
var $PerPageVarLong;
var $PerPageShortVar;
var $Query_SortField;
var $Query_SortOrder;
var $ItemType;
function clsCatItemList()
{
$this->ClsItemList();
$this->Query_SortField = array();
$this->Query_SortOrder = array();
}
function QueryOrderByClause($EditorsPick=FALSE,$Priority=FALSE,$UseTableName=FALSE)
{
global $objSession;
if($UseTableName)
{
$TableName = $this->SourceTable.".";
}
else {
$TableName = "";
}
$Orders = array();
if($EditorsPick)
{
$Orders[] = $TableName."EditorsPick DESC";
}
if($Priority)
{
$Orders[] = $TableName."Priority DESC";
}
if(count($this->Query_SortField)>0)
{
for($x = 0; $x < count($this->Query_SortField); $x++)
{
$FieldVar = $this->Query_SortField[$x];
$OrderVar = $this->Query_SortOrder[$x];
if(is_object($objSession))
{
$FieldVarData = $objSession->GetPersistantVariable($FieldVar);
//echo "FieldVar: $FieldVar<br>";
if(strlen($FieldVarData)>0)
{
$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ".
$objSession->GetPersistantVariable($OrderVar));
}
}
}
}
if(count($Orders)>0)
{
$OrderBy = "ORDER BY ".implode(", ",$Orders);
}
else
$OrderBy="";
//echo "ORDER BY: $OrderBy<br>";
return $OrderBy;
}
function AddSortField($SortField, $SortOrder)
{
if(strlen($SortField))
{
$this->Query_SortField[] = $SortField;
$this->Query_SortOrder[] = $SortOrder;
}
}
function ClearSortFields()
{
$this->Query_SortField = array();
$this->Query_SortOrder = array();
}
/* skeletons in this closet */
function GetNewValue($CatId=NULL)
{
return 0;
}
function GetPopValue($CategoryId=NULL)
{
return 0;
}
/* end of skeletons */
function GetCountSQL($PermName,$CatId=NULL, $GroupId=NULL, $AdditonalWhere="")
{
global $objSession, $objPermissions, $objCatList;
$ltable = $this->SourceTable;
$acl = $objSession->GetACLClause();
$cattable = GetTablePrefix()."CategoryItems";
$CategoryTable = GetTablePrefix()."Category";
$ptable = GetTablePrefix()."PermCache";
$VIEW = $objPermissions->GetPermId($PermName);
$sql = "SELECT count(*) as CacheVal FROM $ltable ";
$sql .="INNER JOIN $cattable ON ($cattable.ItemResourceId=$ltable.ResourceId) ";
$sql .="INNER JOIN $CategoryTable ON ($CategoryTable.CategoryId=$cattable.CategoryId) ";
$sql .="INNER JOIN $ptable ON ($cattable.CategoryId=$ptable.CategoryId) ";
$sql .="WHERE ($acl AND PermId=$VIEW AND $cattable.PrimaryCat=1 AND $CategoryTable.Status=1) ";
if(strlen($AdditonalWhere)>0)
{
$sql .= "AND (".$AdditonalWhere.")";
}
return $sql;
}
function SqlCategoryList($attribs = array())
{
$CatTable = GetTablePrefix()."CategoryItems";
$t = $this->SourceTable;
$sql = "SELECT *,$CatTable.CategoryId FROM $t INNER JOIN $CatTable ON $CatTable.ItemResourceId=$t.ResourceId ";
$sql .="WHERE ($CatTable.CategoryId=".$catid." AND $t.Status=1)";
return $sql;
}
function CategoryCount($attribs=array())
{
global $objCatList, $objCountCache;
$cat = $attribs["_catid"];
if(!is_numeric($cat))
{
$cat = $objCatList->CurrentCategoryID();
}
if((int)$cat>0)
$c = $objCatList->GetCategory($cat);
$CatTable = GetTablePrefix()."CategoryItems";
$t = $this->SourceTable;
$sql = "SELECT count(*) as MyCount FROM $t INNER JOIN $CatTable ON ($CatTable.ItemResourceId=$t.ResourceId) ";
if($attribs["_subcats"])
{
$ctable = $objCatList->SourceTable;
$sql .= "INNER JOIN $ctable ON ($CatTable.CategoryId=$ctable.CategoryId) ";
$sql .= "WHERE (ParentPath LIKE '".$c->Get("ParentPath")."%' ";
if(!$attribs["_countcurrent"])
{
$sql .=" AND $ctable.CategoryId != $cat) AND ($t.Status=1)";
}
else
$sql .=") AND ($t.Status=1)";
}
else
$sql .="WHERE ($CatTable.CategoryId=".$cat." AND $t.Status=1) ";
if($attribs["_today"])
{
$today = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
$sql .= "AND ($t.CreatedOn>=$today) ";
}
//echo $sql."<br><br>\n";
$rs = $this->adodbConnection->Execute($sql);
$ret = "";
if($rs && !$rs->EOF)
$ret = (int)$rs->fields["MyCount"];
return $ret;
}
function SqlGlobalCount($attribs=array())
{
global $objSession;
$where = '';
$p = $this->BasePermission.'.VIEW';
$t = $this->SourceTable;
if( getArrayValue($attribs,'_today') )
{
$today = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
$where = "($t.CreatedOn>=$today)";
}
$GroupList = getArrayValue($attribs,'_grouponly') ? $objSession->Get('GroupList') : null;
$sql = $this->GetCountSQL($p,NULL,$GroupList,$where);
return $sql;
}
function DoGlobalCount($attribs)
{
global $objCountCache;
$cc = $objCountCache->GetValue($this->CacheListType("_"),$this->ItemType,$this->CacheListExtraId("_"),(int)getArrayValue($attribs,'_today'), 3600);
if(!is_numeric($cc))
{
$sql = $this->SqlGlobalCount($attribs);
$ret = QueryCount($sql);
$objCountCache->SetValue($this->CacheListType("_"),$this->ItemType,$this->CacheListExtraId("_"),(int)getArrayValue($attribs,'_today'),$ret);
}
else
$ret = $cc;
return $ret;
}
function CacheListExtraId($ListType)
{
global $objSession;
if(!strlen($ListType))
$ListType="_";
switch($ListType)
{
case "_":
$ExtraId = $objSession->Get("GroupList");
break;
case "category":
$ExtraId = $objSession->Get("GroupList");
break;
case "myitems":
$ExtraId = $objSession->Get("PortalUserId");
break;
case "hot":
$ExtraId = $objSession->Get("GroupList");
break;
case "pop":
$ExtraId = $objSession->Get("GroupList");
break;
case "pick":
$ExtraId = $objSession->Get("GroupList");
break;
case "favorites":
$ExtraId = $objSession->Get("PortalUserId");
break;
case "new":
$ExtraId = $objSession->Get("GroupList");
break;
}
return $ExtraId;
}
/**
* Return all listype (from tags) to id mappings
*
* @return Array
* @access private
*/
function GetListTypes()
{
return Array('_' => 0, 'category' => 1, 'myitems' => 2, 'hot' => 3, 'pop' => 4, 'pick' => 5, 'favorites' => 6, 'new' => 8);
}
function CacheListType($ListType)
{
if(empty($ListType))
$ListType='_';
$mapping = $this->GetListTypes();
return $mapping[$ListType];
}
function PerformItemCount($attribs=array())
{
global $objCountCache, $objSession;
$ret = "";
$sql = "";
$ListType = getArrayValue($attribs,'_listtype');
if(!strlen($ListType))
$ListType="_";
$ListTypeId = $this->CacheListType($ListType);
//echo "ListType: $ListType ($ListTypeId)<br>\n";
$ExtraId = $this->CacheListExtraId($ListType);
switch($ListType)
{
case "_":
$ret = $this->DoGlobalCount($attribs);
break;
case "category":
$ret = $this->CategoryCount($attribs);
break;
case "myitems":
$sql = $this->SqlMyItems($attribs);
break;
case "hot":
$sql = $this->SqlHotItems($attribs);
break;
case "pop":
$sql = $this->SqlPopItems($attribs);
break;
case "pick":
$sql = $this->SqlPickItems($attribs);
break;
case "favorites":
$sql = $this->SqlFavorites($attribs);
break;
case "search":
$sql = $this->SqlSearchItems($attribs);
break;
case "new":
$sql = $this->SqlNewItems($attribs);
break;
}
//echo "SQL: $sql<br>";
if(!empty($sql) && $ListType != "_")
{
if(is_numeric($ListTypeId) && $ListTypeId)
{
$cc = $objCountCache->GetValue($ListTypeId,$this->ItemType,$ExtraId,(int)getArrayValue($attribs,'_today'), 3600);
if(!is_numeric($cc) || $attribs['_nocache'] == 1)
{
$ret = QueryCount($sql);
$objCountCache->SetValue($ListTypeId,$this->ItemType,$ExtraId,(int)getArrayValue($attribs,'_today'),$ret);
}
else
$ret = $cc;
}
else
$ret = QueryCount($sql);
}
return $ret;
}
function GetJoinedSQL($PermName, $CatId=NULL, $AdditionalWhere="", $LoadOnlyPrimary = true)
{
global $objSession, $objPermissions;
$ltable = $this->SourceTable;
$acl = $objSession->GetACLClause();
$cattable = GetTablePrefix()."CategoryItems";
$CategoryTable = GetTablePrefix()."Category";
$ptable = GetTablePrefix()."PermCache";
$VIEW = $objPermissions->GetPermId($PermName);
$sql ="INNER JOIN $cattable ON ($cattable.ItemResourceId=$ltable.ResourceId) ";
$sql .="INNER JOIN $CategoryTable ON ($CategoryTable.CategoryId=$cattable.CategoryId) ";
$sql .= "INNER JOIN $ptable ON ($cattable.CategoryId=$ptable.CategoryId) ";
// here will come checking for PrimaryCat on search
if ($LoadOnlyPrimary) {
$sql .="WHERE ($acl AND PermId=$VIEW AND PrimaryCat=1 AND $CategoryTable.Status=1) ";
}
else {
$sql .="WHERE ($acl AND PermId=$VIEW AND $CategoryTable.Status=1) ";
}
if(is_numeric($CatId) && $CatId > 0)
{
$sql .= " AND ($CategoryTable.CategoryId=$CatId) ";
}
if(strlen($AdditionalWhere)>0)
{
$sql .= "AND (".$AdditionalWhere.")";
}
return $sql;
}
/**
* Not used in php files directly [comment by Alex]
*
* @param unknown_type $attribs
* @return unknown
*
*/
function CountFavorites($attribs)
{
if($attribs["_today"])
{
global $objSession, $objConfig, $objPermissions;
$acl = $objSession->GetACLClause();
$favtable = GetTablePrefix()."Favorites";
$ltable = $this->SourceTable;
$cattable = GetTablePrefix()."CategoryItems";
$CategoryTable = GetTablePrefix()."Category";
$ptable = GetTablePrefix()."PermCache";
$today = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
$where = "PortalUserId=".$objSession->Get("PortalUserId")." AND $ltable.Status=1";
$where .= " AND $favtable.Modified >= $today AND ItemTypeId=".$this->ItemType;
$p = $this->BasePermission.".VIEW";
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$sql = "SELECT $ltable.*,$CategoryTable.CategoryId,$CategoryTable.".$ml_formatter->LangFieldName('CachedNavBar')." AS CachedNavBar FROM $favtable INNER JOIN $ltable ON ($favtable.ResourceId=$ltable.ResourceId) ";
$sql .= $this->GetJoinedSQL($p,NULL,$where);
$ret = QueryCount($sql);
}
else
{
if (!$this->ListType == "favorites")
{
$this->ListType = "favorites";
$this->LoadFavorites($attribs);
$ret = $this->QueryItemCount;
}
else
$ret = $this->QueryItemCount;
}
return $ret;
}
function CountPickItems($attribs)
{
if (!$this->ListType == "pick")
{
$this->ListType = "pick";
$this->LoadPickItems($attribs);
$ret = $this->QueryItemCount;
}
else
$ret = $this->QueryItemCount;
return $ret;
}
function CountMyItems($attribs)
{
if (!$this->ListType == "myitems")
{
$this->ListType = "myitems";
$this->LoadMyItems($attribs);
$ret = $this->QueryItemCount;
}
else
$ret = $this->QueryItemCount;
return $ret;
}
function CountHotItems($attribs)
{
if (!$this->ListType == "hotitems")
{
$this->ListType = "hotitems";
$this->LoadHotItems($attribs);
$ret = $this->QueryItemCount;
}
else
$ret = $this->QueryItemCount;
return $ret;
}
function CountNewItems($attribs)
{
if (!$this->ListType == "newitems")
{
$this->ListType = "newitems";
$this->LoadNewItems($attribs);
$ret = $this->QueryItemCount;
}
else
$ret = $this->QueryItemCount;
return $ret;
}
function CountPopItems($attribs)
{
if (!$this->ListType == "popitems")
{
$this->ListType = "popitems";
$this->LoadPopItems($attribs);
$ret = $this->QueryItemCount;
}
else
$ret = $this->QueryItemCount;
return $ret;
}
function CountSearchItems($attribs)
{
if (!$this->ListType == "search")
{
$this->ListType = "search";
$this->LoadSearchItems($attribs);
$ret = $this->QueryItemCount;
}
else
$ret = $this->QueryItemCount;
return $ret;
}
function SqlFavorites($attribs)
{
global $objSession, $objConfig, $objPermissions;
$acl = $objSession->GetACLClause();
$favtable = GetTablePrefix()."Favorites";
$ltable = $this->SourceTable;
$cattable = GetTablePrefix()."CategoryItems";
$CategoryTable = GetTablePrefix()."Category";
$ptable = GetTablePrefix()."PermCache";
$where = "PortalUserId=".$objSession->Get("PortalUserId")." AND $ltable.Status=1";
if($attribs["_today"])
{
$today = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
$where .= " AND $favtable.Modified >= $today AND ItemTypeId=".$this->ItemType;
}
$p = $this->BasePermission.".VIEW";
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$sql = "SELECT $ltable.*,$CategoryTable.CategoryId,$CategoryTable.".$ml_formatter->LangFieldName('CachedNavBar')." AS CachedNavBar FROM $favtable INNER JOIN $ltable ON ($favtable.ResourceId=$ltable.ResourceId) ";
$sql .= $this->GetJoinedSQL($p,NULL,$where);
$OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
$sql .= " ".$OrderBy;
return $sql;
}
function LoadFavorites($attribs)
{
global $objSession, $objCountCache, $objConfig;
$sql = $this->SqlFavorites($attribs);
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
if($attribs["_shortlist"])
{
if ($objConfig->Get($this->PerPageShortVar) > 0) {
$this->PerPageVar = $this->PerPageShortVar;
}
else {
$this->PerPageVar = $this->PerPageVarLong;
}
}
else
$this->PerPageVar = $this->PerPageVarLong;
$CachedCount = $objCountCache->GetValue($this->CacheListType("favorites"),$this->ItemType,$this->CacheListExtraId("favorites"),(int)$attribs["_today"],3600);
if(!is_numeric($CachedCount))
{
$this->QueryItemCount = QueryCount($sql);
$objCountCache->SetValue($this->CacheListType("favorites"),$this->ItemType,$this->CacheListExtraId("favorites"),(int)$attribs["_today"],$this->QueryItemCount);
}
else
$this->QueryItemCount = (int)$CachedCount;
return $this->Query_Item($sql);
}
function SqlPickItems($attribs)
{
global $objSession, $objCatList;
$catid = (int)getArrayValue($attribs,'_catid');
$scope = (int)getArrayValue($attribs,'_scope');
//$JoinCats = (int)$attribs["_catinfo"] || $scope;
$TableName = $this->SourceTable;
if($scope)
{
if (!$catid)
{
$catid = $objCatList->CurrentCategoryID();
}
$where = GetTablePrefix()."CategoryItems.CategoryId =".$catid." AND ".$TableName.".EditorsPick=1 AND ".$TableName.".Status=1";
}
else
{
$where = $TableName.".EditorsPick=1 AND ".$TableName.".Status=1 ";
$catid=NULL;
}
if(getArrayValue($attribs,'_today'))
{
$today = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
$where .= " AND ($TableName.CreatedOn>=$today)";
}
$CategoryTable = GetTablePrefix()."Category";
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.".$ml_formatter->LangFieldName('CachedNavbar')." AS CachedNavBar FROM $TableName ";
$p = $this->BasePermission.".VIEW";
$sql .= $this->GetJoinedSQL($p,$catid,$where);
$OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
$sql .= " ".$OrderBy;
//echo "SQL: $sql<br>";
return $sql;
}
function LoadPickItems($attribs)
{
global $objSession, $objCountCache, $objConfig;
$sql = $this->SqlPickItems($attribs);
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
if($attribs["_shortlist"])
{
if ($objConfig->Get($this->PerPageShortVar) > 0) {
$this->PerPageVar = $this->PerPageShortVar;
}
else {
$this->PerPageVar = $this->PerPageVarLong;
}
}
else
$this->PerPageVar = $this->PerPageVarLong;
$CachedCount = $objCountCache->GetValue($this->CacheListType("pick"),$this->ItemType,$this->CacheListExtraId("pick"),(int)getArrayValue($attribs,'_today'),3600);
if(!is_numeric($CachedCount))
{
$this->QueryItemCount= QueryCount($sql);
$objCountCache->SetValue($this->CacheListType("pick"),$this->ItemType,$this->CacheListExtraId("pick"),(int)getArrayValue($attribs,'_today'),$this->QueryItemCount);
}
else
$this->QueryItemCount=$CachedCount;
return $this->Query_Item($sql);
}
function SqlMyItems($attribs= array())
{
global $objSession;
$TableName = $this->SourceTable;
$where = " ".$TableName.".Status>-1 AND ".$TableName.".CreatedById=".$objSession->Get("PortalUserId");
if(getArrayValue($attribs,'_today'))
{
$today = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
$where .= " AND ($TableName.CreatedOn>=$today)";
}
$CategoryTable = GetTablePrefix()."Category";
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.".$ml_formatter->LangFieldName('CachedNavbar')." AS CachedNavBar FROM $TableName ";
$p = $this->BasePermission.".VIEW";
$sql .= $this->GetJoinedSQL($p,null,$where); // maybe null should be replaced by some CategoryId
$OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
$sql .= " ".$OrderBy;
return $sql;
}
function LoadMyItems($attribs=array())
{
global $objSession,$objCountCache;
$sql = $this->SqlMyItems($attribs);
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
if($attribs["_shortlist"])
{
if ($objConfig->Get($this->PerPageShortVar) > 0) {
$this->PerPageVar = $this->PerPageShortVar;
}
else {
$this->PerPageVar = $this->PerPageVarLong;
}
}
else
$this->PerPageVar = $this->PerPageVarLong;
$CachedCount = $objCountCache->GetValue($this->CacheListType("myitems"),$this->ItemType,$this->CacheListExtraId("myitems"),(int)$attribs["_today"],3600);
if(!is_numeric($CachedCount))
{
$this->QueryItemCount= QueryCount($sql);
$objCountCache->SetValue($this->CacheListType("myitems"),$this->ItemType,$this->CacheListExtraId("myitems"),(int)$attribs["_today"],$this->QueryItemCount);
}
else
$this->QueryItemCount=$CachedCount;
return $this->Query_Item($sql);
}
function SqlNewItems($attribs = array())
{
global $objSession, $objCatList;
$catid = (int)getArrayValue($attribs,'_catid');
$scope = (int)getArrayValue($attribs,'_scope');
$show_since_last = (int)getArrayValue($attribs,'_show_since_last');
//$JoinCats = (int)$attribs["_catinfo"] || $scope;
//echo "Last: $scope<br><br>";
$TableName = $this->SourceTable;
if(getArrayValue($attribs,'_today'))
{
$cutoff = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
}
else
{
if($scope)
{
if (!$catid)
{
$catid = $objCatList->CurrentCategoryID();
}
if (!$show_since_last) {
$cutoff = $this->GetNewValue($catid);
}
else {
$cutoff = $scope;
}
}
else
$cutoff = $this->GetNewValue();
}
if($scope)
{
if (!$catid)
{
$catid = $objCatList->CurrentCategoryID();
}
if (!$show_since_last) {
$where = "CategoryId =".$catid." AND ((".$TableName.".CreatedOn >=".$cutoff." AND ".$TableName.".NewItem != 0) OR ".$TableName.".NewItem=1 ) AND ".$TableName.".Status=1 ";
}
else {
$where = $TableName.".CreatedOn >=".$cutoff." AND ".$TableName.".Status=1 ";
}
}
else
{
$where = "((".$TableName.".CreatedOn >=".$this->GetNewValue()." AND ".$TableName.".NewItem != 0) OR ".$TableName.".NewItem=1 ) AND ".$TableName.".Status=1 ";
}
$CategoryTable = GetTablePrefix()."Category";
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.".$ml_formatter->LangFieldName('CachedNavbar')." AS CachedNavBar FROM $TableName ";
$p = $this->BasePermission.".VIEW";
$sql .= $this->GetJoinedSQL($p,$catid,$where);
$OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
$sql .= " ".$OrderBy;
//echo "SQL: $sql<br><br>";
return $sql;
}
function LoadNewItems($attribs)
{
global $objSession,$objCountCache,$objConfig;
$sql = $this->SqlNewItems($attribs);
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
if( getArrayValue($attribs,'_shortlist') )
{
if ($objConfig->Get($this->PerPageShortVar) > 0) {
$this->PerPageVar = $this->PerPageShortVar;
}
else {
$this->PerPageVar = $this->PerPageVarLong;
}
}
else
$this->PerPageVar = $this->PerPageVarLong;
$CachedCount = $objCountCache->GetValue($this->CacheListType("new"),$this->ItemType,$this->CacheListExtraId("new"),(int)getArrayValue($attribs,'_today'),3600);
if(!is_numeric($CachedCount))
{
$this->QueryItemCount= QueryCount($sql);
$objCountCache->SetValue($this->CacheListType("new"),$this->ItemType,$this->CacheListExtraId("new"),(int)getArrayValue($attribs,'_today'),$this->QueryItemCount);
}
else
$this->QueryItemCount=$CachedCount;
$ret = $this->Query_Item($sql);
return $ret;
}
function SqlPopItems($attribs)
{
global $objSession, $objCatList;
$catid = (int)$attribs["_catid"];
$scope = (int)$attribs["_scope"];
//$JoinCats = (int)$attribs["_catinfo"] || $scope;
$TableName = $this->SourceTable;
if($scope)
{
if (!$catid)
{
$catid = $objCatList->CurrentCategoryID();
}
$where = "CategoryId =".$catid." AND ((".$TableName.".Hits >=".$this->GetLinkPopValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1";
}
else
{
$where = "((".$TableName.".CachedRating >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0 ) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 ";
$where = "((".$TableName.".Hits >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 ";
}
if($attribs["_today"])
{
$today = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
$where .= " AND ($TableName.CreatedOn>=$today)";
}
$CategoryTable = GetTablePrefix()."Category";
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.".$ml_formatter->LangFieldName('CachedNavbar')." AS CachedNavBar FROM $TableName ";
$p = $this->BasePermission.".VIEW";
$sql .= $this->GetJoinedSQL($p,$catid,$where);
$OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
$sql .= " ".$OrderBy;
return $sql;
}
function LoadPopItems($attribs)
{
global $objSession,$objCountCache;
$sql = $this->SqlPopItems($attribs);
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
if($attribs["_shortlist"])
{
if ($objConfig->Get($this->PerPageShortVar) > 0) {
$this->PerPageVar = $this->PerPageShortVar;
}
else {
$this->PerPageVar = $this->PerPageVarLong;
}
}
else
$this->PerPageVar = $this->PerPageVarLong;
$CachedCount = $objCountCache->GetValue($this->CacheListType("pop"),$this->ItemType,$this->CacheListExtraId("pop"),(int)$attribs["_today"],3600);
if(!is_numeric($CachedCount))
{
$this->QueryItemCount= QueryCount($sql);
$objCountCache->SetValue($this->CacheListType("pop"),$this->ItemType,$this->CacheListExtraId("pop"),(int)$attribs["_today"],$this->QueryItemCount);
}
else
$this->QueryItemCount=$CachedCount;
return $this->Query_Item($sql);
}
function SqlHotItems($attribs)
{
global $objSession, $objCatList;
$catid = (int)$attribs["_catid"];
$scope = (int)$attribs["_scope"];
// $JoinCats = (int)$attribs["_catinfo"] || $scope;
$TableName = $this->SourceTable;
$OrderBy = $TableName.".CachedRating DESC";
if($scope)
{
if (!$catid)
{
$catid = $objCatList->CurrentCategoryID();
}
$where = "CategoryId =".$catid." AND ((".$TableName.".CachedRating >=".$this->GetHotValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1";
}
else
{
$where = "((".$TableName.".CachedRating >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0 ) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 ";
}
if($attribs["_today"])
{
$today = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
$where .= " AND ($TableName.CreatedOn>=$today)";
}
$CategoryTable = GetTablePrefix()."Category";
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.".$ml_formatter->LangFieldName('CachedNavbar')." AS CachedNavBar FROM $TableName ";
$p = $this->BasePermission.".VIEW";
$CatId = !$scope? NULL : $catid;
$sql .= $this->GetJoinedSQL($p,$CatId,$where);
if(strlen($OrderBy))
$sql .= " ORDER BY $OrderBy ";
return $sql;
}
function LoadHotItems($attribs)
{
global $objSession,$objCountCache;
$sql = $this->SqlHotItems($attribs);
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
if($attribs["_shortlist"])
{
if ($objConfig->Get($this->PerPageShortVar) > 0) {
$this->PerPageVar = $this->PerPageShortVar;
}
else {
$this->PerPageVar = $this->PerPageVarLong;
}
}
else
$this->PerPageVar = $this->PerPageVarLong;
$CachedCount = $objCountCache->GetValue($this->CacheListType("hot"),$this->ItemType,$this->CacheListExtraId("hot"),(int)$attribs["_today"], 0);
if(!is_numeric($CachedCount))
{
$this->QueryItemCount= QueryCount($sql);
$objCountCache->SetValue($this->CacheListType("hot"),$this->ItemType,$this->CacheListExtraId("hot"),(int)$attribs["_today"],$this->QueryItemCount);
}
else
$this->QueryItemCount=$CachedCount;
return $this->Query_Item($sql);
}
function SqlSearchItems($attribs = array())
{
global $objConfig, $objItemTypes, $objSession, $objPermissions, $CountVal;
$acl = $objSession->GetACLClause();
$this->Clear();
//$stable = "ses_".$objSession->GetSessionKey()."_Search";
$stable = $objSession->GetSearchTable();
$ltable = $this->SourceTable;
$catitems = GetTablePrefix()."CategoryItems";
$cattable = GetTablePrefix()."Category";
$ptable = GetTablePrefix()."PermCache";
$p = $this->BasePermission.".VIEW";
$i = new $this->classname();
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$sql = "SELECT $cattable.CategoryId,$cattable.".$ml_formatter->LangFieldName('CachedNavbar')." AS CachedNavbar,$ltable.*, Relevance FROM $stable ";
$sql .= "INNER JOIN $ltable ON ($stable.ItemId=$ltable.".$i->id_field.") ";
$where = "ItemType=".$this->ItemType." AND $ltable.Status=1";
$load_multiple = $objConfig->Get("Search_ShowMultiple_".$attribs['multiple']);
$LoadOnlyPrimary = true;
if ($load_multiple == 1) {
$LoadOnlyPrimary = false;
}
$sql .= $this->GetJoinedSQL($p,NULL,$where, $LoadOnlyPrimary);
$tmp = $this->QueryOrderByClause(FALSE,TRUE,TRUE);
//echo "TMP: $tmp<br>";
//$tmp = substr($tmp,9);
if(strlen($tmp))
{
$sql .= $tmp.", ";
}
$sql .= " EdPick DESC,Relevance DESC ";
//echo "SQL Search Items: $sql<br><br>";
return $sql;
}
function LoadSearchItems($attribs = array())
{
global $CountVal, $objSession;
//echo "Loading <b>".get_class($this)."</b> Search Items<br>";
$sql = $this->SqlSearchItems($attribs);
//echo "$sql<br>";
$this->Query_Item($sql);
$Keywords = GetKeywords($objSession->GetVariable("Search_Keywords"));
//echo "SQL Loaded ItemCount (<b>".get_class($this).'</b>): '.$this->NumItems().'<br>';
for($i = 0; $i < $this->NumItems(); $i++)
{
$this->Items[$i]->Keywords = $Keywords;
}
if(is_numeric($CountVal[$this->ItemType]))
{
$this->QueryItemCount = $CountVal[$this->ItemType];
//echo "CACHE: <pre>"; print_r($CountVal); echo "</pre><BR>";
}
else
{
$this->QueryItemCount = QueryCount($sql);
//echo "<b>SQL</b>: ".$sql."<br><br>";
$CountVal[$this->ItemType] = $this->QueryItemCount;
}
}
/**
* Updates count cache for selected ids in list
*
* @param Array $item_ids
* @access protected
*/
function FlushCache($item_ids)
{
$db =& GetADODBConnection();
if(is_array($item_ids)) $item_ids=implode(',',$item_ids);
$sql = 'SELECT ResourceId FROM '.$this->SourceTable.' WHERE '.$this->GetIDField().' IN ('.$item_ids.')';
$resource_ids=$db->GetCol($sql);
$sql='SELECT CategoryId FROM '.GetTablePrefix().'CategoryItems WHERE ItemResourceId IN ('.implode(',',$resource_ids).')';
$cat_ids=$db->GetCol($sql);
UpdateCategoryCount($this->ItemType, $cat_ids, $this->GetListTypes());
}
function PasteFromClipboard($TargetCat,$NameField="")
{
global $objSession,$objCatList;
$clip = $objSession->GetVariable("ClipBoard");
if(strlen($clip))
{
$ClipBoard = ParseClipboard($clip);
$IsCopy = (substr($ClipBoard["command"],0,4)=="COPY") || ($ClipBoard["source"] == $TargetCat);
$item_ids = explode(",",$ClipBoard["ids"]);
for($i=0;$i<count($item_ids);$i++)
{
$item = $this->GetItem($item_ids[$i]);
if(!$IsCopy) // paste to other category then current
{
$item->MoveToCategory($ClipBoard["source"],$TargetCat);
$clip = str_replace("CUT","COPY",$clip);
$objSession->SetVariable("ClipBoard",$clip);
}
else
{
$item->CopyToNewResource($TargetCat,$NameField); // create item copy, but with new ResourceId
$item->AddToCategory($TargetCat);
UpdateCategoryCount($item->type,$TargetCat, $this->GetListTypes() );
}
}
}
}
function AdminPrintItems($template)
{
// prints item listing for admin (browse/advanced view) tabs
$o = '<table border="0" cellspacing="2" width="100%"><tbody><tr>';
$i = 1;
$topleft = 0;
$topright = 0;
$rightcount = 0;
$total_items = $this->NumItems();
$topleft = ceil($total_items / 2);
$topright = $total_items - $topleft;
for($x = 0; $x < $topleft; $x++)
{
//printingleft
$item = $this->Items[$x];
if ($i > 2)
{
$o .= "</tr>\n<tr>";
$i = 1;
}
$o .= $item->AdminParseTemplate($template);
$i++;
//printingright
if ($rightcount < $topright && ( ($x + $topleft) < $total_items) )
{
$item = $this->Items[ $x + $topleft ];
if ($i > 2)
{
$o.="</tr>\n<tr>";
$i = 1;
}
$o .= $item->AdminParseTemplate($template);
$i++;
$rightcount++;
}
}
$o .= "\n</tr></tbody></table>\n";
return $o;
}
}
// -------------- NEW CLASSES -----------------------
class DBList {
// table related attributes
var $db = null;
var $table_name = '';
var $LiveTable = '';
var $EditTable = '';
// record related attributes
var $records = Array();
var $record_count = 0;
var $cur_rec = -1; // "-1" means no records, or record index otherwise
// query related attributes
var $SelectSQL = "SELECT * FROM %s";
function DBList()
{
// use $this->SetTable('live', 'table name');
// in inherited constructors to set table for list
$this->db =&GetADODBConnection();
}
function SetTable($action, $table_name = null)
{
// $action = {'live', 'restore','edit'}
switch($action)
{
case 'live':
$this->LiveTable = $table_name;
$this->table_name = $this->LiveTable;
break;
case 'restore':
$this->table_name = $this->LiveTable;
break;
case 'edit':
global $objSession;
$this->table_name = $objSession->GetEditTable($this->LiveTable);
break;
}
}
function Clear()
{
// no use of this method at a time :)
$this->records = Array();
$this->record_count = 0;
$this->cur_rec = -1;
}
function Query()
{
// query list
$sql = sprintf($this->SelectSQL, $this->table_name);
// echo "SQL: $sql<br>";
$rs =& $this->db->Execute($sql);
if( $this->db->ErrorNo() == 0 )
{
$this->records = $rs->GetRows();
$this->record_count = count($this->records);
//$this->cur_rec = $this->record_count ? 0 : -1;
}
else
return false;
}
function ProcessList($callback_method)
{
// process list using user-defined method called
// with one parameter - current record fields
// (associative array)
if($this->record_count > 0)
{
$this->cur_rec = 0;
while($this->cur_rec < $this->record_count)
{
if( method_exists($this, $callback_method) )
$this->$callback_method( $this->GetCurrent() );
$this->cur_rec++;
}
}
}
function &GetCurrent()
{
// return currently processed record (with change ability)
return ($this->cur_rec != -1) ? $this->records[$this->cur_rec] : false;
}
function GetDBField($field_name)
{
$rec =& $this->GetCurrent();
return is_array($rec) && isset($rec[$field_name]) ? $rec[$field_name] : false;
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/kernel/include/parseditem.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.92
\ No newline at end of property
+1.92.2.1
\ No newline at end of property
Index: branches/RC/kernel/include/advsearch.php
===================================================================
--- branches/RC/kernel/include/advsearch.php (revision 9285)
+++ branches/RC/kernel/include/advsearch.php (revision 9286)
@@ -1,358 +1,358 @@
<?php
class clsAdvancedSearchResults extends clsItemCollection
{
var $ResultTable;
var $FieldList;
var $FieldWeight;
var $WhereClauses;
var $SourceTable;
var $Relationships;
var $Ignored_Words;
var $CatClause;
var $Keywords;
var $Phrase = "";
var $SearchType;
var $RequiredRelevance;
var $PctRelevance;
var $PctPop;
var $PctRating;
var $SearchLogRecord = Array();
function clsAdvancedSearchResults($SearchSource,$DataClass, $ItemType = 0)
{
global $objConfig, $objSearchConfig;
$this->clsItemCollection();
$this->SourceTable = $SearchSource;
$this->SetResultTable($SearchSource,$DataClass);
$this->FieldList = array();
$this->Relationships = array();
$this->Ignored_Words = array();
$this->WhereClauses = array();
$this->FieldWeight = array();
$this->Keywords = GetKeywords("");
$this->SearchType = 0; //simple
$this->RequiredRelevance=0;
$this->PctRelevance = $objConfig->Get("SearchRel_DefaultKeyword")/100;
$this->PctPop = $objConfig->Get("SearchRel_DefaultPop")/100;
$this->PctRating = $objConfig->Get("SearchRel_DefaultRating")/100;
if(!is_object($objSearchConfig))
$objSearchConfig = new clsSearchConfigList();
$objSearchConfig->Clear();
if ($ItemType == 0) {
$objSearchConfig->Query_Item("SELECT * FROM ".$objSearchConfig->SourceTable." WHERE TableName='$SearchSource' AND AdvancedSearch=1 ORDER BY DisplayOrder");
}
else {
$tables = Array(1 => 'Category', 2 => 'News',
3 => 'Topic', 4 => 'Link',
11 => 'Products');
$table = $tables[$ItemType];
$sql = "SELECT sc.* FROM ".$objSearchConfig->SourceTable." AS sc LEFT JOIN ".GetTablePrefix()."CustomField AS cf ON sc.CustomFieldId = cf.CustomFieldId WHERE TableName='$table' OR ((TableName='".GetTablePrefix()."CustomField' OR TableName='CustomField') AND cf.Type = $ItemType) AND AdvancedSearch=1 ORDER BY sc.DisplayOrder";
$objSearchConfig->Query_Item($sql);
}
}
function SetResultTable($SearchSource,$DataClass)
{
global $objSession;
//$this->ResultTable = $objSession->GetSessionKey()."_Search";
$this->ResultTable = $objSession->GetSessionTable('Search', '');
$this->classname= $DataClass;
}
function LoadSearchResults($Start=0,$PerPage=NULL)
{
if($PerPage)
{
$limit = "LIMIT $Start,$PerPage";
}
$sql = "SELECT * FROM ".$this->ResultTable." ".$limit;
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
return $this->Query_Item($sql);
}
function SetCategoryClause($whereclause)
{
$this->CatClause=$whereclause;
}
function AddRelationship($JoinTable,$JoinExpression=NULL)
{
$this->Relationships[$JoinTable]=$JoinExpression;
}
function SetKeywords($keywords)
{
$this->Phrase=$keywords;
$this->keywords = GetKeywords($keywords);
}
function AddAdvancedField($TableName,$FieldName,$Verb,$Value,$conj, $main_prefix)
{
global $objSearchConfig, $objConfig;
static $x = 0, $customs_joined = Array();
// echo 'Adding ADVANCED SearchField: ['.$TableName.']; ['.$FieldName.']; ['.$Verb.']; ['.$Value.']; ['.$conj.']<br />';
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
if(!is_object($objSearchConfig))
$objSearchConfig = new clsSeachConfigList();
if ($TableName == GetTablePrefix().'CustomField') {
// stupid custom fields already have prefix in SearchConfig table (not for in-commerce module :D)
$prefix = '';
}
else {
$prefix = GetTablePrefix();
}
$f = $prefix.$TableName.".".$FieldName;
$FieldConfig = $objSearchConfig->GetItemByName($TableName,$FieldName);
if(!is_object($FieldConfig)) {
return false;
}
if ($FieldConfig->Get('ForeignField')) {
$x++;
$parts = explode(".",$FieldConfig->Get("ForeignField"));
$Table = $parts[0];
$pseudo = 'c'.$x;
$Table = AddTablePrefix($Table);
$Field = $parts[1];
$join = $FieldConfig->Get("JoinClause");
$join = str_replace($Table, $pseudo, $join);
$join = str_replace("{ForeignTable}", $pseudo, $join);
$join = str_replace("{LocalTable}", $TableName, $join);
$join = str_replace("{Table}", AddTablePrefix($this->SourceTable), $join);
$join = '('.$join.' AND '.$pseudo.'.CustomFieldId='.$FieldConfig->Get('CustomFieldId').')';
$this->AddRelationship($Table.' AS '.$pseudo, $join);
// for items that does not have appropriate records in CustomMetaData table
if ($Verb == 'notcontains' || $Verb == 'isnot') {
$or_not_null = ' OR '.$pseudo.'.'.$Field.' IS NULL';
}
else {
$or_not_null = '';
}
$FieldItem["where"] = str_replace('CustomMetaData', $pseudo, $FieldConfig->GetWhereClause($Verb,$Value)).$or_not_null;
$FieldItem["Field"] = $FieldConfig->Get("ForeignField");
$FieldItem["Table"] = $pseudo;
$FieldItem["conjuction"] = $conj;
$FieldItem["weight"] = $FieldConfig->Get("Priority");
}
else {
$classes = Array(
'Link' => '_clsLinkList',
'News' => '_clsNewsList',
'Topic' => '_clsTopicList',
'Category' => 'clsCatList');
$list_class = getArrayValue($classes, $TableName);
if ($list_class) {
- $objList =& new $list_class();
+ $objList = new $list_class();
}
$prefix_fields = $this->Application->getUnitOption($main_prefix, 'Fields');
if (isset($prefix_fields[$FieldName]) && $prefix_fields[$FieldName]['formatter'] == 'kMultiLanguage') {
$FieldConfig->Set('FieldName', $ml_formatter->LangFieldName($FieldName));
}
if ($FieldConfig->Get('CustomFieldId')) {
$FieldConfig->Set('FieldName', $ml_formatter->LangFieldName('cust_'.$FieldConfig->Get('CustomFieldId')));
}
switch ($FieldName) {
case 'HotItem':
$cutoff = $objList->GetHotValue();
$Value == 1 ? $not = '' : $not = 'NOT ';
$where_clause = $FieldConfig->GetWhereClause($Verb, $Value);
$where_clause .= ' OR ('.AddTablePrefix($TableName).'.HotItem=2 AND '.
$not.'('.AddTablePrefix($TableName).
'.Hits>='.$cutoff.'))';
break;
case 'PopItem':
$cutoff = $objList->GetPopValue();
$Value == 1 ? $not = '' : $not = 'NOT ';
$where_clause = $FieldConfig->GetWhereClause($Verb, $Value);
$where_clause .= ' OR ('.AddTablePrefix($TableName).'.PopItem=2 AND '.
$not.'('.AddTablePrefix($TableName).
'.CachedRating>='.$cutoff.'))';
break;
case 'NewItem':
$NewTime = $objConfig->Get($TableName.'_NewDays')*3600*24;
$Value == 1 ? $not = '' : $not = 'NOT ';
$where_clause = $FieldConfig->GetWhereClause($Verb, $Value);
$where_clause .= ' OR ('.AddTablePrefix($TableName).'.NewItem=2 AND '.
$not.'('.adodb_mktime().'-'.AddTablePrefix($TableName).
'.CreatedOn<'.$NewTime.'))';
break;
default:
$where_clause = $FieldConfig->GetWhereClause($Verb, $Value);
break;
}
$FieldItem = Array();
if ($FieldConfig->Get('CustomFieldId')) {
if (!getArrayValue($customs_joined, $main_prefix)) {
$item_table = $this->Application->getUnitOption($main_prefix, 'TableName');
$custom_table = $this->Application->getUnitOption($main_prefix.'-cdata', 'TableName');
$this->AddRelationship($custom_table.' AS '.$main_prefix.'_custom_data', $main_prefix.'_custom_data.ResourceId = '.$item_table.'.ResourceId');
$customs_joined[$main_prefix] = true;
}
$FieldItem['Table'] = $main_prefix.'_custom_data';
$FieldItem['Field'] = $FieldConfig->Get('FieldName');
}
else {
$FieldItem['Table'] = AddTablePrefix($TableName);
$FieldItem['Field'] = $FieldName;
}
$FieldItem['where'] = $FieldItem['Table'].'.'.$where_clause;
$FieldItem['conjuction'] = $conj;
$FieldItem['weight'] = $FieldConfig->Get('Priority');
}
$this->FieldList[] = $FieldItem;
// create search record
$this->SearchLogRecord[] = language('la_Field').' "'.$FieldConfig->getHumanField().'" '.$FieldConfig->getHumanVerb($Verb).' '.language('la_Value').' "'.$FieldConfig->getHumanValue($Value).'" '.language('lu_'.$conj);
unset($FieldItem);
}
function getKeywords(&$FieldConfig)
{
$ret = implode('<br />', $this->SearchLogRecord);
return preg_replace('/(.*) '.preg_quote(language('lu_and'), '/').'|'.preg_quote(language('lu_or'), '/').'$/is', '\\1', $ret);
}
/* function AddAdvancedCustomFields()
{
$sql = "SELECT * FROM ".GetTablePrefix()."SearchConfig WHERE TableName='".$this->SourceTable."' AND AdvancedSearch=1 AND CustomFieldId>0";
//echo $sql;
foreach($this->Relationships as $Table=>$clause)
{
if(strlen($Table)>0 && $Table != "Category")
$sql .= " OR TableName='".$Table."'";
}
$ctable = GetTablePrefix()."CustomMetaData";
$rs = $this->adodbConnection->Execute($sql);
$CustomJoined = FALSE;
while($rs && !$rs->EOF)
{
$x = $rs->fields["CustomFieldId"];
$t = $ctable." as c".$x;
$join = "(c$x.ResourceId=".GetTablePrefix().$this->SourceTable.".ResourceId AND c$x.CustomFieldId=".$rs->fields["CustomFieldId"].")";
$this->AddRelationship($t,$join);
$f = "c".$x.".Value ";
$this->FieldList[] = $f;
$this->FieldWeight[$f] = $rs->fields["Priority"];
$rs->MoveNext();
}
}
function AddAdvancedFields()
{
$sql = "SELECT * FROM ".GetTablePrefix()."SearchConfig WHERE TableName='".$this->SourceTable."' AND AdvancedSearch=1 AND CustomFieldId=0";
//echo $sql;
foreach($this->Relationships as $Table=>$clause)
{
if(strlen($Table)>0 && $Table != "Category")
$sql .= " OR TableName='".$Table."'";
}
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$f = GetTablePrefix().$rs->fields["TableName"].".".$rs->fields["FieldName"];
$this->FieldList[] = $f;
$this->FieldWeight[$f] = $rs->fields["Priority"];
$rs->MoveNext();
}
$this->AddAdvancedCustomFields();
}*/
/* ready to write the code to build the query and go */
function BuildWhereClause()
{
$where = "";
foreach($this->FieldList as $f)
$where .= " (".$f["where"].") ".$f["conjuction"];
$cut_length = substr($where, -2) == 'OR' ? 2 : substr($where, -3) == 'AND' ? 3 : 0;
$where = substr($where, 0, strlen($where) - $cut_length);
return $where;
}
function PerformSearch($ItemType,$OrderBy=NULL,$InitTable=FALSE, $idlist=NULL)
{
static $SelectSQL, $OldItemType;
global $objSession, $objItemTypes;
// add recrod to log
$objSearchList = new clsSearchLogList();
$objSearchList->UpdateKeyword($this->getKeywords(), 1);
$ctype = $objItemTypes->GetItem($ItemType);
$idField = $ctype->Get("SourceTable")."Id";
$this->SourceTable = AddTablePrefix($ctype->Get("SourceTable"));
$result=0;
$PopField = $ctype->Get("PopField");
$RateField = $ctype->Get("RateField");
$typestr = str_pad($ItemType,2,"0",STR_PAD_LEFT);
$SelectSQL = "SELECT ".$this->SourceTable.".".$idField." as ItemId, ". $this->SourceTable.".Priority as Relevance, ".$this->SourceTable.".ResourceId, CONCAT($typestr) as ItemType, EditorsPick as EdPick FROM ".$this->SourceTable." ";
foreach($this->Relationships as $JoinTable=>$OnClause)
{
$SelectSQL .= "LEFT JOIN $JoinTable ON ($OnClause) ";
}
$first=1;
$WhereClause = $this->BuildWhereClause();
if(strlen($WhereClause)>0)
{
$SelectSQL .= " WHERE ".$WhereClause;
}
$SelectSQL .= " GROUP BY $idField ";
//echo $SelectSQL;
$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$this->ResultTable);
$full_sql = "CREATE TABLE ".$this->ResultTable." ".$indexSQL.$SelectSQL;
$this->adodbConnection->Execute($full_sql);
// if advanced seaech used, then delete simple search keywords
$objSession->SetVariable('Search_Keywords', '');
//print_pre($full_sql);
}
function BuildIndexes()
{
$sql = "ALTER TABLE ".$this->ResultTable." ADD INDEX (Relevance), ";
$sql .="ADD INDEX (ItemId), ";
$sql .="ADD INDEX (ItemType), ";
$sql .=" ADD INDEX sorting (EdPick,Relevance)";
$this->adodbConnection->Execute($sql);
}
function Result_IdList()
{
/* returns an array contain a resource ID list */
$sql = "SELECT DISTINCT(ResourceId) FROM ".$this->ResultTable;
$rs = $this->adodbConnection->Execute($sql);
$result = array();
while($rs && !$rs->EOF)
{
$result[] = $rs->fields["ResourceId"];
$rs->MoveNext();
}
return $result;
}
function SetRelevence($ItemType, $IdField)
{
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/kernel/include/advsearch.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.13
\ No newline at end of property
+1.13.2.1
\ No newline at end of property
Index: branches/RC/kernel/include/globals.php
===================================================================
--- branches/RC/kernel/include/globals.php (revision 9285)
+++ branches/RC/kernel/include/globals.php (revision 9286)
@@ -1,2013 +1,2013 @@
<?php
if (!function_exists('parse_portal_ini')) {
function parse_portal_ini($file, $parse_section = false) {
if (!file_exists($file)) return false;
if(file_exists($file) && !is_readable($file))
die('Could Not Open Ini File');
$contents = file($file);
$retval = array();
$section = '';
$ln = 1;
$resave = false;
foreach($contents as $line) {
if ($ln == 1 && $line != '<'.'?'.'php die() ?'.">\n") {
$resave = true;
}
$ln++;
$line = trim($line);
$line = eregi_replace(';[.]*','',$line);
if(strlen($line) > 0) {
//echo $line . " - ";
if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) {
//echo 'section';
$section = substr($line,1,(strlen($line)-2));
if ($parse_section) {
$retval[$section] = array();
}
continue;
} elseif(eregi('=',$line)) {
//echo 'main element';
list($key,$val) = explode(' = ',$line);
if (!$parse_section) {
$retval[trim($key)] = str_replace('"', '', $val);
}
else {
$retval[$section][trim($key)] = str_replace('"', '', $val);
}
} //end if
//echo '<br />';
} //end if
} //end foreach
if ($resave) {
$fp = fopen($file, "w");
reset($contents);
fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
foreach($contents as $line) fwrite($fp,"$line");
fclose($fp);
}
return $retval;
}
}
$vars = parse_portal_ini(FULL_PATH.'/config.php');
if ($vars) {
foreach ($vars as $config_key => $config_value) {
$GLOBALS['g_'.$config_key] = $config_value;
}
unset($config_key, $config_value);
}
/*list the tables which contain item data */
$ItemTables = array();
$KeywordIgnore = array();
global $debuglevel;
$debuglevel = 0;
//$GLOBALS['debuglevel'] = 0;
/*New, Hot, Pop field values */
define('NEVER', 0);
define('ALWAYS', 1);
define('AUTO', 2);
/*Status Values */
if( !defined('STATUS_DISABLED') ) define('STATUS_DISABLED', 0);
if( !defined('STATUS_ACTIVE') ) define('STATUS_ACTIVE', 1);
if( !defined('STATUS_PENDING') ) define('STATUS_PENDING', 2);
if( !defined('STATUS_PENDING_EDITING') ) define('STATUS_PENDING_EDITING', -2);
$LogLevel = 0;
$LogFile = NULL;
/**
* Returns reference to database connection
*
* @param bool $new_type Return Kernel4 or in-portal connection object
* @return kDBConnection
*/
function &GetADODBConnection($new_type = false)
{
static $DB = null;
global $g_DBType, $g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName, $g_DebugMode;
global $ADODB_FETCH_MODE, $ADODB_COUNTRECS, $ADODB_CACHE_DIR, $pathtoroot;
if ($new_type) {
$application =& kApplication::Instance();
return $application->GetADODBConnection();
}
if( !isset($DB) && strlen($g_DBType) > 0 )
{
$DB = ADONewConnection($g_DBType);
$connected = $DB->Connect($g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName);
if(!$connected) die("Error connecting to database $g_DBHost <br>\n");
$ADODB_CACHE_DIR = $pathtoroot."cache";
$ADODB_FETCH_MODE = 2;
$ADODB_COUNTRECS = false;
$DB->debug = defined('ADODB_OUTP') ? 1 : 0;
$DB->cacheSecs = 3600;
$DB->Execute('SET SQL_BIG_SELECTS = 1');
}
elseif( !strlen($g_DBType) )
{
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>';
if ( !preg_match('/admin/', __FILE__) ) $ins = 'admin/';
echo '<a href="'.$rootURL.$ins.'install.php">Go to installation script</a><br><br>';
flush();
exit;
}
return $DB;
}
function GetNextResourceId($Increment=1)
{
global $objModules, $pathtoroot;
$table_name = GetTablePrefix().'IdGenerator';
$db = &GetADODBConnection();
// dummy protection: get maximal resource id used actually and fix last_id used
$max_resourceid = 0;
$m = GetModuleArray();
foreach($m as $key=>$value)
{
$path = $pathtoroot. $value."admin/include/parser.php";
if(file_exists($path))
{
include_once($path);
}
}
$table_info = $objModules->ExecuteFunction('GetModuleInfo', 'dupe_resourceids');
$sql_template = 'SELECT MAX(ResourceId) FROM '.GetTablePrefix().'%s';
foreach($table_info as $module_name => $module_info)
{
foreach($module_info as $module_sub_info)
{
$sql = sprintf($sql_template,$module_sub_info['Table']);
$tmp_resourceid = $db->GetOne($sql);
if($tmp_resourceid > $max_resourceid) $max_resourceid = $tmp_resourceid;
}
}
// update lastid to be next resourceid available
$db->Execute('LOCK TABLES '.$table_name.' WRITE');
$last_id = $db->GetOne('SELECT lastid FROM '.$table_name);
if ($last_id - 1 > $max_resourceid) $max_resourceid = $last_id - 1;
$id_diff = $db->GetOne('SELECT '.$max_resourceid.' + 1 - lastid FROM '.$table_name);
if($id_diff) $Increment += $id_diff;
$sql = 'UPDATE '.$table_name.' SET lastid = lastid + '.$Increment; // set new id in db
$db->Execute($sql);
$val = $db->GetOne('SELECT lastid FROM '.$table_name);
if($val === false)
{
$db->Execute('INSERT INTO '.$table_name.' (lastid) VALUES ('.$Increment.')');
$val = $Increment;
}
$db->Execute('UNLOCK TABLES');
return $val - $Increment + $id_diff; // return previous free id (-1) ?
}
function AddSlash($s)
{
if(substr($s,-1) != "/")
{
return $s."/";
}
else
return $s;
}
function StripNewline($s)
{
$bfound = false;
while (strlen($s)>0 && !$bfound)
{
if(ord(substr($s,-1))<32)
{
$s = substr($s,0,-1);
}
else
$bfound = true;
}
return $s;
}
function DeleteElement($array, $indice)
{
for($i=$indice;$i<count($array)-1;$i++)
$array[$i] = $array[$i+1];
unset($array[count($array)-1]);
return $array;
}
function DeleteElementValue($needle, &$haystack)
{
while(($gotcha = array_search($needle,$haystack)) > -1)
unset($haystack[$gotcha]);
}
function TableCount($TableName, $where="",$JoinCats=1)
{
$db = &GetADODBConnection();
if(!$JoinCats)
{
$sql = "SELECT count(*) as TableCount FROM $TableName";
}
else
$sql = "SELECT count(*) as TableCount FROM $TableName INNER JOIN ".GetTablePrefix()."CategoryItems ON ".GetTablePrefix()."CategoryItems.ItemResourceId=$TableName.ResourceId";
if(strlen($where)>0)
$sql .= " WHERE ".$where;
$rs = $db->Execute($sql);
// echo "SQL TABLE COUNT: ".$sql."<br>\n";
$res = $rs->fields["TableCount"];
return $res;
}
Function QueryCount($sql)
{
$sql = preg_replace('/SELECT(.*)FROM[ \n\r](.*)/is','SELECT COUNT(*) AS TableCount FROM $2', $sql);
$sql = preg_replace('/(.*)[ \n\r]LIMIT[ \n\r](.*)/is','$1', $sql);
$sql = preg_replace('/(.*)ORDER BY(.*)/is','$1', $sql);
//echo $sql;
$db =& GetADODBConnection();
return $db->GetOne($sql);
}
function GetPageCount($ItemsPerPage,$NumItems)
{
if($ItemsPerPage==0 || $NumItems==0)
{
return 1;
}
$value = $NumItems/$ItemsPerPage;
return ceil($value);
}
/**
* @return string
* @desc Returns database table prefix entered while installation
*/
function GetTablePrefix()
{
global $g_TablePrefix;
return $g_TablePrefix;
}
function TableHasPrefix($t)
{
$pre = GetTablePrefix();
if(strlen($pre)>0)
{
if(substr($t,0,strlen($pre))==$pre)
{
return TRUE;
}
else
return FALSE;
}
else
return TRUE;
}
function AddTablePrefix($t)
{
if(!TableHasPrefix($t))
$t = GetTablePrefix().$t;
return $t;
}
function ThisDomain()
{
global $objConfig, $g_Domain;
if($objConfig->Get("DomainDetect"))
{
$d = $_SERVER['HTTP_HOST'];
}
else
$d = $g_Domain;
return $d;
}
function GetIndexUrl($secure=0)
{
global $indexURL, $rootURL, $secureURL;
if ( class_exists('kApplication') )
{
$application =& kApplication::Instance();
return $application->BaseURL().'index.php';
}
switch($secure)
{
case 0:
$ret = $indexURL;
break;
case 1:
$ret = $secureURL."index.php";
break;
case 2:
$ret = $rootURL."index.php";
break;
default:
$ret = $i;
break;
}
return $ret;
}
function GetLimitSQL($Page,$PerPage)
{
if($Page<1)
$Page=1;
if(is_numeric($PerPage))
{
if($PerPage==0)
$PerPage = 20;
$Start = ($Page-1)*$PerPage;
$limit = "LIMIT ".$Start.",".$PerPage;
}
else
$limit = NULL;
return $limit;
}
function filelist ($currentdir, $startdir=NULL,$ext=NULL)
{
global $pathchar;
//chdir ($currentdir);
// remember where we started from
if (!$startdir)
{
$startdir = $currentdir;
}
$d = @opendir($currentdir);
$files = array();
if(!$d)
return $files;
//list the files in the dir
while (false !== ($file = readdir($d)))
{
if ($file != ".." && $file != ".")
{
if (is_dir($currentdir."/".$file))
{
// If $file is a directory take a look inside
$a = filelist ($currentdir."/".$file, $startdir,$ext);
if(is_array($a))
$files = array_merge($files,$a);
}
else
{
if($ext!=NULL)
{
$extstr = stristr($file,".".$ext);
if(strlen($extstr))
$files[] = $currentdir."/".$file;
}
else
$files[] = $currentdir.'/'.$file;
}
}
}
closedir ($d);
return $files;
}
function DecimalToBin($dec,$WordLength=8)
{
$bits = array();
$str = str_pad(decbin($dec),$WordLength,"0",STR_PAD_LEFT);
for($i=$WordLength;$i>0;$i--)
{
$bits[$i-1] = (int)substr($str,$i-1,1);
}
return $bits;
}
/*
function inp_escape($in, $html_enable=0)
{
$out = stripslashes($in);
$out = str_replace("\n", "\n^br^", $out);
if($html_enable==0)
{
$out=ereg_replace("<","&lt;",$out);
$out=ereg_replace(">","&gt;",$out);
$out=ereg_replace("\"","&quot;",$out);
$out = str_replace("\n^br^", "\n<br />", $out);
}
else
$out = str_replace("\n^br^", "\n", $out);
$out=addslashes($out);
return $out;
}
*/
function inp_escape($var,$html=0)
{
if($html)return $var;
if(is_array($var))
foreach($var as $k=>$v)
$var[$k]=inp_escape($v);
else
// $var=htmlspecialchars($var,ENT_NOQUOTES);
$var=strtr($var,Array('<'=>'&lt;','>'=>'&gt;',));
return $var;
}
function inp_striptags($var,$html=0)
{
if($html)return $var;
if(is_array($var))
foreach($var as $k=>$v)
$var[$k]=inp_striptags($v);
else
$var=strip_tags($var);
return $var;
}
function inp_unescape($in)
{
// if (get_magic_quotes_gpc())
return $in;
$out=stripslashes($in);
return $out;
}
function inp_textarea_unescape($in)
{
// if (get_magic_quotes_gpc())
return $in;
$out=stripslashes($in);
$out = str_replace("\n<br />", "\n", $out);
return $out;
}
function HighlightKeywords($Keywords, $html, $OpenTag="", $CloseTag="")
{
global $objConfig;
if(!strlen($OpenTag))
$OpenTag = "<B>";
if(!strlen($CloseTag))
$CloseTag = "</B>";
$r = preg_split('((>)|(<))', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($Keywords as $k) {
for ($i = 0; $i < count($r); $i++) {
if ($r[$i] == "<") {
$i++; continue;
}
$r[$i] = preg_replace('/('.preg_quote($k, '/').')/i', "$OpenTag\\1$CloseTag", $r[$i]);
}
}
return join("", $r);
}
/*
function HighlightKeywords($Keywords,$html, $OpenTag="", $CloseTag="")
{
global $objConfig;
if(!strlen($OpenTag))
$OpenTag = "<B>";
if(!strlen($CloseTag))
$CloseTag = "</B>";
$ret = strip_tags($html);
foreach ($Keywords as $k)
{
if(strlen($k))
{
//$html = str_replace("<$k>", ":#:", $html);
//$html = str_replace("</$k>", ":##:", $html);
//$html = strip_tags($html);
if ($html = preg_replace("/($k)/Ui","$OpenTag\\1$CloseTag", $html))
//if ($html = preg_replace("/(>[^<]*)($k)([^<]*< )/Ui","$OpenTag\\1$CloseTag", $html))
$ret = $html;
//$ret = str_replace(":#:", "<$k>", $ret);
//$ret = str_replace(":##:", "</$k>", $ret);
}
}
return $ret;
}
*/
function ExtractDatePart($part, $datestamp)
{
if ($datestamp <= 0) return '';
$formats = Array( 'month' => 'm', 'day' => 'd', 'year' => 'Y',
'time_24hr' => 'H:i', 'time_12hr' => 'g:i a', 'time' => GetTimeFormat(), 'date' => GetDateFormat() );
$format = isset($formats[$part]) ? $formats[$part] : $part;
return adodb_date($format, $datestamp);
}
function GetLocalTime($TimeStamp, $TargetZone = null)
{
global $objConfig;
if ($TargetZone == null) {
$TargetZone = $objConfig->Get('Config_Site_Time');
}
$server = $objConfig->Get('Config_Server_Time');
if ($TargetZone != $server) {
$offset = ($server - $TargetZone) * -1;
$TimeStamp = $TimeStamp + (3600 * $offset);
}
return $TimeStamp;
}
function _unhtmlentities ($string)
{
$trans_tbl = get_html_translation_table (HTML_ENTITIES);
$trans_tbl = array_flip ($trans_tbl);
return strtr ($string, $trans_tbl);
}
function getLastStr($hay, $need){
$getLastStr = 0;
$pos = strpos($hay, $need);
if (is_int ($pos)){ //this is to decide whether it is "false" or "0"
while($pos) {
$getLastStr = $getLastStr + $pos + strlen($need);
$hay = substr ($hay , $pos + strlen($need));
$pos = strpos($hay, $need);
}
return $getLastStr - strlen($need);
} else {
return -1; //if $need wasn´t found it returns "-1" , because it could return "0" if it´s found on position "0".
}
}
// --- bbcode processing function: begin ----
function PreformatBBCodes($text)
{
// convert phpbb url bbcode to valid in-bulletin's format
// 1. urls
$text = preg_replace('/\[url=(.*)\](.*)\[\/url\]/Ui','[url href="$1"]$2[/url]',$text);
$text = preg_replace('/\[url\](.*)\[\/url\]/Ui','[url href="$1"]$1[/url]',$text);
// 2. images
$text = preg_replace('/\[img\](.*)\[\/img\]/Ui','[img src="$1" border="0"][/img]',$text);
// 3. color
$text = preg_replace('/\[color=(.*)\](.*)\[\/color\]/Ui','[font color="$1"]$2[/font]',$text);
// 4. size
$text = preg_replace('/\[size=(.*)\](.*)\[\/size\]/Ui','[font size="$1"]$2[/font]',$text);
// 5. lists
$text = preg_replace('/\[list(.*)\](.*)\[\/list\]/Uis','[ul]$2[/ul]',$text);
// 6. email to link
$text = preg_replace('/\[email\](.*)\[\/email\]/Ui','[url href="mailto:$1"]$1[/url]',$text);
//7. b tag
$text = preg_replace('/\[(b|i|u):(.*)\](.*)\[\/(b|i|u):(.*)\]/Ui','[$1]$3[/$4]',$text);
//8. code tag
$text = preg_replace('/\[code:(.*)\](.*)\[\/code:(.*)\]/Uis','[code]$2[/code]',$text);
return $text;
}
/**
* @return string
* @param string $BBCode
* @param string $TagParams
* @param string $TextInside
* @param string $ParamsAllowed
* @desc Removes not allowed params from tag and returns result
*/
function CheckBBCodeAttribs($BBCode, $TagParams, $TextInside, $ParamsAllowed)
{
// $BBCode - bbcode to check, $TagParams - params string entered by user
// $TextInside - text between opening and closing bbcode tag
// $ParamsAllowed - list of allowed parameter names ("|" separated)
$TagParams=str_replace('\"','"',$TagParams);
$TextInside=str_replace('\"','"',$TextInside);
if( $ParamsAllowed && preg_match_all('/ +([^=]*)=["\']?([^ "\']*)["\']?/is',$TagParams,$params,PREG_SET_ORDER) )
{
$ret = Array();
foreach($params as $param)
{
// remove spaces in both parameter name & value & lowercase parameter name
$param[1] = strtolower(trim($param[1])); // name lowercased
if(($BBCode=='url')&&($param[1]=='href'))
if(false!==strpos(strtolower($param[2]),'script:'))
return $TextInside;
// $param[2]='about:blank';
if( isset($ParamsAllowed[ $param[1] ]) )
$ret[] = $param[1].'="'.$param[2].'"';
}
$ret = count($ret) ? ' '.implode(' ',$ret) : '';
return '<'.$BBCode.$ret.'>'.$TextInside.'</'.$BBCode.'>';
}
else
return '<'.$BBCode.'>'.$TextInside.'</'.$BBCode.'>';
return false;
}
function ReplaceBBCode($text)
{
global $objConfig;
// convert phpbb bbcodes to in-bulletin bbcodes
$text = PreformatBBCodes($text);
// $tag_defs = 'b:;i:;u:;ul:type|align;font:color|face|size;url:href;img:src|border';
$tags_defs = $objConfig->Get('BBTags');
foreach(explode(';',$tags_defs) as $tag)
{
$tag = explode(':',$tag);
$tag_name = $tag[0];
$tag_params = $tag[1]?array_flip(explode('|',$tag[1])):0;
$text = preg_replace('/\['.$tag_name.'(.*)\](.*)\[\/'.$tag_name.' *\]/Uise','CheckBBCodeAttribs("'.$tag_name.'",\'$1\',\'$2\',$tag_params);', $text);
}
// additional processing for [url], [*], [img] bbcode
$text = preg_replace('/<url>(.*)<\/url>/Usi','<url href="$1">$1</url>',$text);
$text = preg_replace('/<font>(.*)<\/font>/Usi','$1',$text); // skip empty fonts
$text = str_replace( Array('<url','</url>','[*]'),
Array('<a target="_blank"','</a>','<li>'),
$text);
// bbcode [code]xxx[/code] processing
$text = preg_replace('/\[code\](.*)\[\/code\]/Uise', "ReplaceCodeBBCode('$1')", $text);
return $text;
}
function leadSpace2nbsp($x)
{
return "\n".str_repeat('&nbsp;',strlen($x));
}
function ReplaceCodeBBCode($input_string)
{
$input_string=str_replace('\"','"',$input_string);
$input_string=$GLOBALS['objSmileys']->UndoSmileys(_unhtmlentities($input_string));
$input_string=trim($input_string);
$input_string=inp_htmlize($input_string);
$input_string=str_replace("\r",'',$input_string);
$input_string = str_replace("\t", " ", $input_string);
$input_string = preg_replace('/\n( +)/se',"leadSpace2nbsp('$1')",$input_string);
$input_string='<div style="border:1px solid #888888;width:100%;background-color:#eeeeee;margin-top:6px;margin-bottom:6px"><div style="padding:10px;"><code>'.$input_string.'</code></div></div>';
// $input_string='<textarea wrap="off" style="border:1px solid #888888;width:100%;height:200px;background-color:#eeeeee;">'.inp_htmlize($input_string).'</textarea>';
return $input_string;
if(false!==strpos($input_string,'<'.'?'))
{
$input_string=str_replace('<'.'?','<'.'?php',$input_string);
$input_string=str_replace('<'.'?phpphp','<'.'?php',$input_string);
$input_string=@highlight_string($input_string,1);
}
else
{
$input_string = @highlight_string('<'.'?php'.$input_string.'?'.'>',1);
$input_string = str_replace('&lt;?php', '', str_replace('?&gt;', '', $input_string));
}
return str_replace('<br />','',$input_string);
}
// --- bbcode processing function: end ----
function GetMinValue($Table,$Field, $Where=NULL)
{
$ret = 0;
$sql = "SELECT min($Field) as val FROM $Table ";
if(strlen($where))
$sql .= "WHERE $Where";
$ado = &GetADODBConnection();
$rs = $ado->execute($sql);
if($rs)
$ret = (int)$rs->fields["val"];
return $ret;
}
if (!function_exists( 'getmicrotime' ) ) {
function getmicrotime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
}
function SetMissingDataErrors($f)
{
global $FormError;
$count = 0;
if(is_array($_POST))
{
if(is_array($_POST["required"]))
{
foreach($_POST["required"] as $r)
{
$found = FALSE;
if(is_array($_FILES))
{
if( isset($_FILES[$r]) && $_FILES[$r]['size'] > 0 ) $found = TRUE;
}
if(!strlen(trim($_POST[$r])) && !$found)
{
$count++;
if (($r == "dob_day") || ($r == "dob_month") || ($r == "dob_year"))
$r = "dob";
$tag = isset($_POST["errors"]) ? $_POST["errors"][$r] : '';
if(!strlen($tag))
$tag = "lu_ferror_".$f."_".$r;
$FormError[$f][$r] = language($tag);
}
}
}
}
return $count;
}
function makepassword($length=10)
{
$pass_length=$length;
$p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
$p2=array('a','e','i','o','u');
$p3=array('1','2','3','4','5','6','7','8','9');
$p4=array('(','&',')',';','%'); // if you need real strong stuff
// how much elements in the array
// can be done with a array count but counting once here is faster
$s1=21;// this is the count of $p1
$s2=5; // this is the count of $p2
$s3=9; // this is the count of $p3
$s4=5; // this is the count of $p4
// possible readable combinations
$c1='121'; // will be like 'bab'
$c2='212'; // will be like 'aba'
$c3='12'; // will be like 'ab'
$c4='3'; // will be just a number '1 to 9' if you dont like number delete the 3
// $c5='4'; // uncomment to active the strong stuff
$comb='4'; // the amount of combinations you made above (and did not comment out)
for ($p=0;$p<$pass_length;)
{
mt_srand((double)microtime()*1000000);
$strpart=mt_rand(1,$comb);
// checking if the stringpart is not the same as the previous one
if($strpart<>$previous)
{
$pass_structure.=${'c'.$strpart};
// shortcutting the loop a bit
$p=$p+strlen(${'c'.$strpart});
}
$previous=$strpart;
}
// generating the password from the structure defined in $pass_structure
for ($g=0;$g<strlen($pass_structure);$g++)
{
mt_srand((double)microtime()*1000000);
$sel=substr($pass_structure,$g,1);
$pass.=${'p'.$sel}[mt_rand(0,-1+${'s'.$sel})];
}
return $pass;
}
function LogEntry($text,$writefile=FALSE)
{
global $g_LogFile,$LogFile, $LogData, $LogLevel, $timestart;
static $last;
if(strlen($g_LogFile))
{
$el = str_pad(getmicrotime()- $timestart,10," ");
if($last>0)
$elapsed = getmicrotime() - $last;
if(strlen($el)>10)
$el = substr($el,0,10);
$indent = str_repeat(" ",$LogLevel);
$text = str_pad($text,$LogLevel,"==",STR_PAD_LEFT);
$LogData .= "$el:". round($elapsed,6).":$indent $text";
$last = getmicrotime();
if($writefile==TRUE && is_writable($g_LogFile))
{
if(!$LogFile)
{
if(file_exists($g_LogFile))
unlink($g_LogFile);
$LogFile=@fopen($g_LogFile,"w");
}
if($LogFile)
{
fputs($LogFile,$LogData);
}
}
}
}
function ValidEmail($email)
{
if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email))
{
return TRUE;
}
else
{
return FALSE;
}
}
function language($phrase, $LangId = 0)
{
$application =& kApplication::Instance();
return $application->Phrase($phrase);
}
function admin_language($phrase, $lang = 0, $LinkMissing = false)
{
return language($phrase, $lang);
}
function prompt_language($phrase, $lang = 0)
{
return language($phrase, $lang);
}
function GetPrimaryTranslation($Phrase)
{
global $objLanguages;
$l = $objLanguages->GetPrimary();
return language($Phrase,$l);
}
function CategoryNameCount($ParentId,$Name)
{
$cat_table = GetTablePrefix()."Category";
$sql = "SELECT Name from $cat_table WHERE ParentId=$ParentId AND ";
$sql .="(Name LIKE '".addslashes($Name)."' OR Name LIKE 'Copy of ".addslashes($Name)."' OR Name LIKE 'Copy % of ".addslashes($Name)."')";
$ado = &GetADODBConnection();
$rs = $ado->Execute($sql);
$ret = array();
while($rs && !$rs->EOF)
{
$ret[] = $rs->fields["Name"];
$rs->MoveNext();
}
return $ret;
}
function CategoryItemNameCount($CategoryId,$Table,$Field,$Name)
{
$Name=addslashes($Name);
$cat_table = GetTablePrefix()."CategoryItems";
$sql = "SELECT $Field FROM $Table INNER JOIN $cat_table ON ($Table.ResourceId=$cat_table.ItemResourceId) ";
$sql .=" WHERE ($Field LIKE 'Copy % of $Name' OR $Field LIKE '$Name' OR $Field LIKE 'Copy of $Name') AND CategoryId=$CategoryId";
//echo $sql."<br>\n ";
$ado = &GetADODBConnection();
$rs = $ado->Execute($sql);
$ret = array();
while($rs && !$rs->EOF)
{
$ret[] = $rs->fields[$Field];
$rs->MoveNext();
}
return $ret;
}
function &GetItemCollection($ItemName)
{
global $objItemTypes;
if(is_numeric($ItemName))
{
$item = $objItemTypes->GetItem($ItemName);
}
else
$item = $objItemTypes->GetTypeByName($ItemName);
if(is_object($item))
{
$module = $item->Get("Module");
$prefix = ModuleTagPrefix($module);
$func = $prefix."_ItemCollection";
if(function_exists($func))
{
$var =& $func();
}
}
return $var;
}
function UpdateCategoryCount($item_type,$CategoriesIds,$ListType='')
{
global $objCountCache, $objItemTypes;
$db=&GetADODBConnection();
if( !is_numeric($item_type) )
{
$sql = 'SELECT ItemType FROM '.$objItemTypes->SourceTable.' WHERE ItemName=\''.$item_type.'\'';
$item_type=$db->GetOne($sql);
}
$objCountCache->EraseGlobalTypeCache($item_type);
if($item_type)
{
if(is_array($CategoriesIds))
{
$CategoriesIds=implode(',',$CategoriesIds);
}
if (!$CategoriesIds)
{
}
if(!is_array($ListType)) $ListType=Array($ListType=>'opa');
$sql = 'SELECT ParentPath FROM '.GetTablePrefix().'Category WHERE CategoryId IN ('.$CategoriesIds.')';
$rs = $db->Execute($sql);
$parents = Array();
while (!$rs->EOF)
{
$tmp=$rs->fields['ParentPath'];
$tmp=substr($tmp,1,strlen($tmp)-2);
$tmp=explode('|',$tmp);
foreach ($tmp as $tmp_cat_id) {
$parents[$tmp_cat_id]=1;
}
$rs->MoveNext();
}
$parents=array_keys($parents);
$list_types=array_keys($ListType);
foreach($parents as $ParentCategoryId)
{
foreach ($list_types as $list_type) {
$objCountCache->DeleteValue($list_type, $item_type, $ParentCategoryId, 0); // total count
$objCountCache->DeleteValue($list_type, $item_type, $ParentCategoryId, 1); // total count today
}
}
}
else
{
die('wrong item type passed to "UpdateCategoryCount"');
}
/* if(is_object($item))
{
$ItemType = $item->Get("ItemType");
$sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType";
if( is_numeric($ListType) ) $sql .= " AND ListType=$ListType";
$objCountCache->adodbConnection->Execute($sql);
} */
}
function ResetCache($CategoryId)
{
global $objCountCache;
$db =& GetADODBConnection();
$sql = 'SELECT ParentPath FROM '.GetTablePrefix().'Category WHERE CategoryId = '.$CategoryId;
$parents = $db->GetOne($sql);
$parents = substr($parents,1,strlen($parents)-2);
$parents = explode('|',$parents);
foreach($parents as $ParentCategoryId)
{
$objCountCache->DeleteValue('_', TYPE_TOPIC, $ParentCategoryId, 0); // total topic count
$objCountCache->DeleteValue('_', TYPE_TOPIC, $ParentCategoryId, 1); // total
}
}
function UpdateModifiedCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$ExtraId=NULL)
{
}
function UpdateGroupCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$GroupId=NULL)
{
}
function GetTagCache($module,$tag,$attribs,$env)
{
global $objSystemCache, $objSession, $objConfig;
if($objConfig->Get("SystemTagCache") && !$objSession->Get('PortalUserId'))
{
$name = $tag;
if(is_array($attribs))
{
foreach($attribs as $n => $val)
{
$name .= "-".$val;
}
}
$CachedValue = $objSystemCache->GetContextValue($name,$module,$env, $objSession->Get("GroupList"));
}
else
$CachedValue="";
return $CachedValue;
}
function SaveTagCache($module, $tag, $attribs, $env, $newvalue)
{
global $objSystemCache, $objSession, $objConfig;
if($objConfig->Get("SystemTagCache"))
{
$name = $tag;
if(is_array($attribs))
{
foreach($attribs as $a => $val)
{
$name .= "-".$val;
}
}
$objSystemCache->EditCacheItem($name,$newvalue,$module,0,$env,$objSession->Get("GroupList"));
}
}
function DeleteTagCache($name,$extraparams, $env="")
{
global $objSystemCache, $objConfig;
if($objConfig->Get("SystemTagCache"))
{
$where = "Name LIKE '$name%".$extraparams."'";
if(strlen($env))
$where .= " AND Context LIKE $env";
$objSystemCache->DeleteCachedItem($where);
}
}
/**
* Deletes whole tag cache for
* selected module
*
* @param string $module
* @param string $name
* @access public
*/
function DeleteModuleTagCache($module, $tagname='')
{
global $objSystemCache, $objConfig;
if($objConfig->Get("SystemTagCache"))
{
$where = 'Module LIKE \''.$module.'\'';
if(strlen($tagname))
{
$where .= ' AND Name LIKE \''.$tagname.'\'';
}
$objSystemCache->DeleteCachedItem($where);
}
}
/*function ClearTagCache()
{
global $objSystemCache, $objConfig;
if($objConfig->Get("SystemTagCache"))
{
$where = '';
$objSystemCache->DeleteCachedItem($where);
}
}*/
/*function EraseCountCache()
{
// global $objSystemCache, $objConfig;
$db =& GetADODBConnection();
$sql = 'DELETE * FROM '.GetTablePrefix().'CountCache';
return $db->Execute($sql) ? true : false;
}*/
function ParseTagLibrary()
{
$objTagList = new clsTagList();
$objTagList->ParseInportalTags();
unset($objTagList);
}
function GetDateFormat($LangId = 0, $is_input = false)
{
global $objLanguages;
if (!$LangId) {
$LangId = $objLanguages->GetPrimary();
}
$l = $objLanguages->GetItem($LangId);
$fmt = is_object($l) ? $l->Get(($is_input ? 'Input' : '').'DateFormat') : 'm-d-Y';
if (getArrayValue($GLOBALS, 'FrontEnd')) {
return $fmt;
}
return preg_replace('/y+/i','Y', $fmt);
}
function GetTimeFormat($LangId = 0, $is_input = false)
{
global $objLanguages;
if (!$LangId) {
$LangId = $objLanguages->GetPrimary();
}
$l = $objLanguages->GetItem($LangId);
$fmt = is_object($l) ? $l->Get(($is_input ? 'Input' : '').'TimeFormat') : 'H:i:s';
return $fmt;
}
/**
* Gets one of currently selected language options
*
* @param string $optionName
* @param int $LangId
* @return string
* @access public
*/
function GetRegionalOption($optionName,$LangId=0)
{
global $objLanguages, $objSession;
if(!$LangId) $LangId=$objSession->Get('Language');
if(!$LangId) $LangId=$objLanguages->GetPrimary();
$l = $objLanguages->GetItem($LangId);
return is_object($l)?$l->Get($optionName):false;
}
/**
* Returns formatted timestamp
*
* @param int $TimeStamp
* @param int $LangId
* @param bool $is_input use input date format instead of display date format
* @return string
*/
function LangDate($TimeStamp = null, $LangId = 0, $is_input = false)
{
$fmt = GetDateFormat($LangId, $is_input);
return adodb_date($fmt, $TimeStamp);
}
/**
* Returns formatted timestamp
*
* @param int $TimeStamp
* @param int $LangId
* @param bool $is_input use input time format instead of display time format
* @return string
*/
function LangTime($TimeStamp = null, $LangId = 0, $is_input = false)
{
$fmt = GetTimeFormat($LangId, $is_input);
return adodb_date($fmt, $TimeStamp);
}
function LangNumber($Num,$DecPlaces=NULL,$LangId=0)
{
global $objLanguages;
if(!$LangId)
$LangId= $objLanguages->GetPrimary();
$l = $objLanguages->GetItem($LangId);
if(is_object($l))
{
$ret = number_format($Num,$DecPlaces,$l->Get("DecimalPoint"),$l->Get("ThousandSep"));
}
else
$ret = $num;
return $ret;
}
function replacePngTags($x, $spacer="images/spacer.gif")
{
global $rootURL,$pathtoroot;
// make sure that we are only replacing for the Windows versions of Internet
// Explorer 5+, and not Opera identified as MSIE
$msie='/msie\s([5-9])\.?[0-9]*.*(win)/i';
$opera='/opera\s+[0-9]+/i';
if(!isset($_SERVER['HTTP_USER_AGENT']) ||
!preg_match($msie,$_SERVER['HTTP_USER_AGENT']) ||
preg_match($opera,$_SERVER['HTTP_USER_AGENT']))
return $x;
// find all the png images in backgrounds
preg_match_all('/background-image:\s*url\(\'(.*\.png)\'\);/Uis',$x,$background);
for($i=0;$i<count($background[0]);$i++){
// simply replace:
// "background-image: url('image.png');"
// with:
// "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
// enabled=true, sizingMethod=scale src='image.png');"
// haven't tested to see if background-repeat styles work...
$x=str_replace($background[0][$i],'filter:progid:DXImageTransform.'.
'Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale'.
' src=\''.$background[1][$i].'\');',$x);
}
// OK, time to find all the IMG tags with ".png" in them
preg_match_all('/(<img.*\.png.*>|<input.*type=([\'"])image\\2.*\.png.*>)/Uis',$x,$images);
while(list($imgnum,$v)=@each($images[0])){
$original=$v;
$atts=''; $width=0; $height=0;
// If the size is defined by styles, find
preg_match_all('/style=".*(width: ([0-9]+))px.*'.
'(height: ([0-9]+))px.*"/Ui',$v,$arr2);
if(is_array($arr2) && count($arr2[0])){
// size was defined by styles, get values
$width=$arr2[2][0];
$height=$arr2[4][0];
}
// size was not defined by styles, get values
preg_match_all('/width=\"?([0-9]+)\"?/i',$v,$arr2);
if(is_array($arr2) && count($arr2[0])){
$width=$arr2[1][0];
}
preg_match_all('/height=\"?([0-9]+)\"?/i',$v,$arr2);
if(is_array($arr2) && count($arr2[0])){
$height=$arr2[1][0];
}
preg_match_all('/src=\"([^\"]+\.png)\"/i',$v,$arr2);
if(isset($arr2[1][0]) && !empty($arr2[1][0]))
$image=$arr2[1][0];
else
$image=NULL;
// We do this so that we can put our spacer.gif image in the same
// directory as the image
$tmp=split('[\\/]',$image);
array_pop($tmp);
$image_path=join('/',$tmp);
if(substr($image,0,strlen($rootURL))==$rootURL)
{
$path = str_replace($rootURL,$pathtoroot,$image);
}
else
{
$path = $pathtoroot."themes/telestial/$image";
}
// echo "Sizing $path.. <br>\n";
// echo "Full Tag: ".htmlentities($image)."<br>\n";
//if(!$height || !$width)
//{
$g = imagecreatefrompng($path);
if($g)
{
$height = imagesy($g);
$width = imagesx($g);
}
//}
if(strlen($image_path)) $image_path.='/';
// end quote is already supplied by originial src attribute
$replace_src_with=$spacer.'" style="width: '.$width.
'px; height: '.$height.'px; filter: progid:DXImageTransform.'.
'Microsoft.AlphaImageLoader(src=\''.$image.'\', sizingMethod='.
'\'scale\')';
// now create the new tag from the old
$new_tag=str_replace($image,$replace_src_with,$original);
// now place the new tag into the content
$x=str_replace($original,$new_tag,$x);
}
return $x;
}
function GetOptions($field) // by Alex
{
// get dropdown values from custom field
- $tmp =& new clsCustomField();
+ $tmp = new clsCustomField();
$tmp->LoadFromDatabase($field, 'FieldName');
$tmp_values = $tmp->Get('ValueList');
unset($tmp);
$tmp_values = explode(',', $tmp_values);
foreach($tmp_values as $mixed)
{
$elem = explode('=', trim($mixed));
$ret[ $elem[0] ] = $elem[1];
}
return $ret;
}
function ResetPage($module_prefix, $page_variable = 'p')
{
// resets page in specific module when category is changed
global $objSession;
if( !is_object($objSession) ) // when changing pages session doesn't exist -> InPortal BUG
{
global $var_list, $SessionQueryString, $FrontEnd;
$objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));
}
$last_cat = $objSession->GetVariable('last_category');
$prev_cat = $objSession->GetVariable('prev_category');
//echo "Resetting Page [$prev_cat] -> [$last_cat]<br>";
if($prev_cat != $last_cat) $GLOBALS[$module_prefix.'_var_list'][$page_variable] = 1;
}
if( !function_exists('GetVar') )
{
/**
* @return string
* @param string $name
* @param bool $post_priority
* @desc Get's variable from http query
*/
function GetVar($name, $post_priority = false)
{
if(!$post_priority) // follow gpc_order in php.ini
return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
else // get variable from post 1stly if not found then from get
return isset($_POST[$name]) && $_POST[$name] !== false ? $_POST[$name] : ( isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false );
}
}
function SetVar($VarName, $VarValue)
{
$_REQUEST[$VarName] = $VarValue;
$_POST[$VarName] = $VarValue;
$_GET[$VarName] = $VarValue;
}
function PassVar(&$source)
{
// source array + any count of key names in passed array
$params = func_get_args();
array_shift($params);
if( count($params) )
{
$ret = Array();
foreach($params as $var_name)
if( isset($source[$var_name]) )
$ret[] = $var_name.'='.$source[$var_name];
$ret = '&'.implode('&', $ret);
}
return $ret;
}
function GetSubmitVariable(&$array, $postfix)
{
// gets edit status of module
// used in case if some modules share
// common action parsed by kernel parser,
// but each module uses own EditStatus variable
$modules = Array('In-Link' => 'Link', 'In-News' => 'News', 'In-Bulletin' => 'Topic', 'In-Portal'=>'Review');
foreach($modules as $module => $prefix)
if( isset($array[$prefix.$postfix]) )
return Array('Module' => $module, 'variable' => $array[$prefix.$postfix]);
return false;
}
function GetModuleByAction()
{
$prefix2module = Array('m' => 'In-Portal', 'l' => 'In-Link', 'n' => 'In-News', 'bb' => 'In-Bulletin');
$action = GetVar('Action');
if($action)
{
$module_prefix = explode('_', $action);
return $prefix2module[ $module_prefix[0] ];
}
else
return false;
}
function dir_size($dir) {
// calculates folder size based on filesizes inside it (recursively)
$totalsize=0;
if ($dirstream = @opendir($dir)) {
while (false !== ($filename = readdir($dirstream))) {
if ($filename!="." && $filename!="..")
{
if (is_file($dir."/".$filename))
$totalsize+=filesize($dir."/".$filename);
if (is_dir($dir."/".$filename))
$totalsize+=dir_size($dir."/".$filename);
}
}
}
closedir($dirstream);
return $totalsize;
}
function size($bytes) {
// shows formatted file/directory size
$types = Array("la_bytes","la_kilobytes","la_megabytes","la_gigabytes","la_terabytes");
$current = 0;
while ($bytes > 1024) {
$current++;
$bytes /= 1024;
}
return round($bytes,2)." ".language($types[$current]);
}
function echod($str)
{
// echo debug output
echo str_replace( Array('[',']'), Array('[<b>', '</b>]'), $str).'<br>';
}
function PrepareParams($source, $to_lower, $mapping)
{
// prepare array with form values to use with item
$result = Array();
foreach($to_lower as $field)
$result[ $field ] = $source[ strtolower($field) ];
if( is_array($mapping) )
{
foreach($mapping as $field_from => $field_to)
$result[$field_to] = $source[$field_from];
}
return $result;
}
function GetELT($field, $phrases = Array())
{
// returns FieldOptions equivalent in In-Portal
$ret = Array();
foreach($phrases as $phrase)
$ret[] = admin_language($phrase);
$ret = "'".implode("','", $ret)."'";
return 'ELT('.$field.','.$ret.')';
}
function GetModuleImgPath($module)
{
global $rootURL, $admin;
return $rootURL.$module.'/'.$admin.'/images';
}
function ActionPostProcess($StatusField, $ListClass, $ListObjectName = '', $IDField = null)
{
// each action postprocessing stuff from admin
if( !isset($_REQUEST[$StatusField]) ) return false;
$list =& $GLOBALS[$ListObjectName];
if( !is_object($list) ) $list = new $ListClass();
$SFValue = $_REQUEST[$StatusField]; // status field value
switch($SFValue)
{
case 1: // User hit "Save" button
$list->CopyFromEditTable($IDField);
break;
case 2: // User hit "Cancel" button
$list->PurgeEditTable($IDField);
break;
}
if( function_exists('SpecificProcessing') ) SpecificProcessing($StatusField, $SFValue);
if($SFValue == 1 || $SFValue == 2) $list->Clear();
}
function MakeHTMLTag($element, $attrib_prefix)
{
$result = Array();
$ap_length = strlen($attrib_prefix);
foreach($element->attributes as $attib_name => $attr_value)
if( substr($attib_name, $ap_length) == $ap_length )
$result[] = substr($attib_name, $ap_length, strlen($attib_name)).'="'.$attr_value.'"';
return count($result) ? implode(' ', $result) : false;
}
function GetImportScripts()
{
// return currently installed import scripts
static $import_scripts = Array();
if( count($import_scripts) == 0 )
{
$sql = 'SELECT imp.* , m.LoadOrder
FROM '.TABLE_PREFIX.'ImportScripts imp
LEFT JOIN '.TABLE_PREFIX.'Modules m ON m.Name = imp.is_Module
WHERE m.Loaded = 1
ORDER BY m.LoadOrder';
$db =& GetADODBConnection();
$rs = $db->Execute($sql);
if ($rs && $rs->RecordCount() > 0) {
while (!$rs->EOF) {
$rec =& $rs->fields;
$import_scripts[ $rec['is_id'] ] = Array( 'label' => $rec['is_label'], 'url' => $rec['is_script'],
'enabled' => $rec['is_enabled'], 'field_prefix' => $rec['is_field_prefix'],
'id' => $rec['is_string_id'], 'required_fields' => $rec['is_requred_fields'],
'module' => strtolower($rec['is_Module']) );
$rs->MoveNext();
}
}
else {
$import_scripts = Array();
}
}
return $import_scripts;
}
function GetImportScript($id)
{
$scripts = GetImportScripts();
return isset($scripts[$id]) ? $scripts[$id] : false;
}
function GetNextTemplate($current_template)
{
// used on front, returns next template to make
// redirect to
$dest = GetVar('dest', true);
if(!$dest) $dest = GetVar('DestTemplate', true);
return $dest ? $dest : $current_template;
}
// functions for dealign with enviroment variable construction
function GenerateModuleEnv($prefix, $var_list)
{
// globalize module varible arrays
$main =& $GLOBALS[$prefix.'_var_list'];
$update =& $GLOBALS[$prefix.'_var_list_update'];
//echo "VAR: [$main]; VAR_UPDATE: [$update]<br>";
// if update var count is zero, then do nothing
if( !is_array($update) || count($update) == 0 ) return '';
// ensure that we have no empty values in enviroment variable
foreach($update as $vl_key => $vl_value) {
if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]);
}
foreach($main as $vl_key => $vl_value) {
// we need to skip wid here, otherwise empty wid will become 0 and the window name for javascript will be changed (to main_0),
// making all links to original (main) window open in new window
if ($vl_key == 'wid') continue;
if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]);
}
$ret = Array();
foreach($var_list as $var_name) {
$value = GetEnvVar($prefix, $var_name);
if(!$value && $var_name == 'id') $value = '0';
$ret[] = $value;
}
// Removing all var_list_udpate
$keys = array_keys($update);
foreach ($keys as $key) {
unset($update[$key]);
}
return ':'.$prefix.implode('-',$ret);
}
// functions for dealign with enviroment variable construction
function GenerateModuleEnv_NEW($prefix, $var_list)
{
// globalize module varible arrays
$main =& $GLOBALS[$prefix.'_var_list'];
$update =& $GLOBALS[$prefix.'_var_list_update'];
//echo "VAR: [$main]; VAR_UPDATE: [$update]<br>";
if ( isset($update) && $update )
{
// ensure that we have no empty values in enviroment variable
foreach($update as $vl_key => $vl_value) {
if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]);
}
$app =& kApplication::Instance();
$passed = $app->GetVar('prefixes_passed');
$passed[] = $prefix;
$app->SetVar('prefixes_passed', $passed);
}
else
{
return Array();
}
if ($main) {
foreach($main as $vl_key => $vl_value) {
if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]);
}
}
$ret = Array();
foreach($var_list as $src_name => $dst_name) {
$ret[$dst_name] = GetEnvVar($prefix, $src_name);
}
// Removing all var_list_udpate
if ( isset($update) && $update )
{
$keys = array_keys($update);
foreach ($keys as $key) unset($update[$key]);
}
return $ret;
}
function GetEnvVar($prefix, $name)
{
// get variable from template variable's list
// (used in module parsers to build env string)
$main =& $GLOBALS[$prefix.'_var_list'];
$update =& $GLOBALS[$prefix.'_var_list_update'];
// if part of env found in POST, then use it first
$submit_value = GetVar($prefix.'_'.$name);
if ($submit_value !== false) {
return $submit_value;
}
return isset($update[$name]) ? $update[$name] : ( isset($main[$name]) ? $main[$name] : '');
}
/**
* Checks if debug mode is active
*
* @return bool
*/
function IsDebugMode($check_debugger = true)
{
$application =& kApplication::Instance();
return $application->isDebugMode($check_debugger);
}
/**
* Checks if we are in admin
*
* @return bool
*/
function IsAdmin()
{
$application =& kApplication::Instance();
return $application->IsAdmin();
}
/**
* Two strings in-case-sensitive compare.
* Returns >0, when string1 > string2,
* <0, when string1 > string2,
* 0, when string1 = string2
*
* @param string $string1
* @param string $string2
* @return int
*/
function stricmp ($string1, $string2) {
return strcmp(strtolower($string1), strtolower($string2));
}
/**
* Generates unique code
*
* @return string
*/
function GenerateCode()
{
list($usec, $sec) = explode(" ",microtime());
$id_part_1 = substr($usec, 4, 4);
$id_part_2 = mt_rand(1,9);
$id_part_3 = substr($sec, 6, 4);
$digit_one = substr($id_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$id_part_1 = ereg_replace("^0","",$id_part_1);
$id_part_1=$digit_one.$id_part_1;
}
return $id_part_1.$id_part_2.$id_part_3;
}
function bracket_comp($elem1, $elem2)
{
if( ($elem1['End']>$elem2['End'] || $elem1['End'] == -1) && $elem2['End'] != -1 )
{
return 1;
}
elseif ( ($elem1['End']<$elem2['End'] || $elem2['End'] == -1) && $elem1['End'] != -1 )
{
return -1;
}
else
{
return 0;
}
}
function bracket_id_sort($first_id, $second_id)
{
$first_abs = abs($first_id);
$second_abs = abs($second_id);
$first_sign = ($first_id == 0) ? 0 : $first_id / $first_abs;
$second_sign = ($second_id == 0) ? 0 : $second_id / $second_abs;
if($first_sign != $second_sign)
{
if($first_id > $second_id) {
$bigger =& $first_abs;
$smaller =& $second_abs;
}
else {
$bigger =& $second_abs;
$smaller =& $first_abs;
}
$smaller = $bigger + $smaller;
}
if($first_abs > $second_abs) {
return 1;
}
elseif ($first_abs < $second_abs)
{
return -1;
}
else
{
return 0;
}
}
function ap_bracket_comp($elem1, $elem2)
{
if ($elem1['FromAmount']!="" && $elem1['ToAmount']=="" && $elem2['FromAmount']!="" && $elem2['ToAmount']!="") return 1;
if ($elem1['FromAmount']!="" && $elem1['ToAmount']=="" && $elem2['FromAmount']=="" && $elem2['ToAmount']=="") return -1;
if ($elem1['ToAmount']=="" && $elem2['ToAmount']!="") return 1;
if ($elem1['ToAmount']!="" && $elem2['ToAmount']=="") return -1;
if( ($elem1['ToAmount']>$elem2['ToAmount'] && $elem2['ToAmount']!=-1) || ($elem1['ToAmount'] == -1 && $elem2['ToAmount'] != -1 ))
{
return 1;
}
elseif ( ($elem1['ToAmount']<$elem2['ToAmount']) || ($elem2['ToAmount'] == -1 && $elem1['ToAmount'] != -1 ))
{
return -1;
}
else
{
return 0;
}
}
function inp_htmlize($var, $strip = 0)
{
if( is_array($var) )
{
foreach($var as $k => $v) $var[$k] = inp_htmlize($v, $strip);
}
else
{
$var = htmlspecialchars($strip ? stripslashes($var) : $var);
}
return $var;
}
/**
* Sets in-portal cookies, that will not harm K4 to breath free :)
*
* @param string $name
* @param mixed $value
* @param int $expire
* @author Alex
*/
function set_cookie($name, $value, $expire = 0, $cookie_path = null)
{
if (!isset($cookie_path))
{
$cookie_path = IsAdmin() ? rtrim(BASE_PATH, '/').'/admin' : BASE_PATH;
}
setcookie($name, $value, $expire, $cookie_path, $_SERVER['HTTP_HOST']);
}
/**
* If we are on login required template, but we are not logged in, then logout user
*
* @return bool
*/
function require_login($condition = null, $redirect_params = 'logout=1', $pass_env = false)
{
if( !isset($condition) ) $condition = !admin_login();
if(!$condition) return false;
global $objSession, $adminURL;
if( !headers_sent() ) set_cookie(SESSION_COOKIE_NAME, ' ', adodb_mktime() - 3600);
$objSession->Logout();
if($pass_env) $redirect_params = 'env='.BuildEnv().'&'.$redirect_params;
header('Location: '.$adminURL.'/index.php?'.$redirect_params);
exit;
}
/**
* Builds up K4 url from data supplied by in-portal
*
* @param string $t template
* @param Array $params
* @param string $index_file
* @return string
*/
function HREF_Wrapper($t = '', $params = null, $index_file = null)
{
$url_params = BuildEnv_NEW();
if( isset($params) ) $url_params = array_merge_recursive2($url_params, $params);
if(!$t)
{
$t = $url_params['t'];
unset($url_params['t']);
}
$app =& kApplication::Instance();
return $app->HREF($t, '', $url_params, $index_file);
}
/**
* Set url params based on tag params & mapping hash passed
*
* @param Array $url_params - url params before change
* @param Array $tag_attribs - tag attributes
* @param Array $params_map key - tag_param, value - url_param
*/
function MapTagParams(&$url_params, $tag_attribs, $params_map)
{
foreach ($params_map as $tag_param => $url_param)
{
if( getArrayValue($tag_attribs, $tag_param) ) $url_params[$url_param] = $tag_attribs[$tag_param];
}
}
function ExtractParams($params_str, $separator = '&')
{
if(!$params_str) return Array();
$ret = Array();
$parts = explode($separator, trim($params_str, $separator) );
foreach ($parts as $part)
{
list($var_name, $var_value) = explode('=', $part);
$ret[$var_name] = $var_value;
}
return $ret;
}
function &recallObject($var_name, $class_name)
{
if (!isset($GLOBALS[$var_name]) || !is_object($GLOBALS[$var_name]))
{
$GLOBALS[$var_name] = new $class_name();
}
return $GLOBALS[$var_name];
}
/**
* Returns true in case of AM/PM time
*
* @return bool
*/
function is12HourMode()
{
return preg_match('/(a|A)/', GetTimeFormat() );
}
/**
* Saves custom fields for old in-portal items
*
* @param string $prefix K4 prefix of item
* @param int $resource_id resource id of item
* @param int $item_type type of custom fields
*/
function saveCustomFields($prefix, $resource_id, $item_type)
{
$objCustomEdit = new clsCustomDataList();
$CustomFields = new clsCustomFieldList($item_type);
$data_changed = false;
for ($i = 0; $i < $CustomFields->NumItems(); $i++) {
$objField =& $CustomFields->GetItemRefByIndex($i);
$field_name = $objField->Get('FieldName');
$element_type = $objField->Get('ElementType');
$value = getCustomValue($field_name);
if ($element_type == 'checkbox' && $value === false) {
// unchecked checkboxes are not submitted
$value = 0;
}
if ($value !== false) {
$objCustomEdit->SetFieldValue($objField->Get('CustomFieldId'), $resource_id, $value);
$data_changed = true;
}
}
if ($data_changed) {
$objCustomEdit->SaveData($prefix, $resource_id);
}
}
/**
* Returns custom field value from submit
*
* @param string $field_name
* @return mixed
*/
function getCustomValue($field_name)
{
if (IsAdmin()) {
$field_name = '_'.$field_name;
}
elseif (isset($_POST[strtolower($field_name)])) {
$field_name = strtolower($field_name);
}
return GetVar($field_name);
}
function checkActionPermission($action_mapping, $action, $system = 0)
{
$application =& kApplication::Instance();
if (!isset($action_mapping[$action])) {
// if no permission mapping defined, then action is allowed in any case
return true;
}
$perm_status = false;
$action_mapping = explode('|', $action_mapping[$action]);
foreach ($action_mapping as $perm_name) {
$perm_status = $application->CheckPermission($perm_name, $system);
if ($perm_status) {
break;
}
}
if (!$perm_status) {
$application->Redirect($application->IsAdmin() ? 'no_permission' : $application->ConfigValue('NoPermissionTemplate'), null, '', 'index.php');
}
return true;
}
function checkViewPermission($section_name, $system = 1)
{
$application =& kApplication::Instance();
$application->InitParser();
$application->ProcessParsedTag('m', 'RequireLogin', Array('permissions' => $section_name.'.view', 'system' => $system, 'index_file' => 'index.php'));
}
?>
Property changes on: branches/RC/kernel/include/globals.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/core/kernel/processors/tag_processor.php
===================================================================
--- branches/RC/core/kernel/processors/tag_processor.php (revision 9285)
+++ branches/RC/core/kernel/processors/tag_processor.php (revision 9286)
@@ -1,228 +1,228 @@
<?php
class TagProcessor extends kBase {
/**
* Processes tag
*
* @param Tag $tag
* @return string
* @access public
*/
function ProcessTag(&$tag)
{
return $this->ProcessParsedTag($tag->Tag, $tag->NP, $tag->getPrefixSpecial());
/*$Method=$tag->Tag;
if(method_exists($this, $Method))
{
//echo htmlspecialchars($tag->GetFullTag()).'<br>';
return $this->$Method($tag->NP);
}
else
{
if ($this->Application->hasObject('TagsAggregator')) {
$aggregator =& $this->Application->recallObject('TagsAggregator');
$tag_mapping = $aggregator->GetArrayValue($tag->Prefix, $Method);
if ($tag_mapping) {
- $mapped_tag =& new Tag('', $this->Application->Parser);
+ $mapped_tag = new Tag('', $this->Application->Parser);
$mapped_tag->CopyFrom($tag);
$mapped_tag->Processor = $tag_mapping[0];
$mapped_tag->Tag = $tag_mapping[1];
$mapped_tag->NP['PrefixSpecial'] = $tag->getPrefixSpecial();
$mapped_tag->RebuildTagData();
return $mapped_tag->DoProcessTag();
}
}
trigger_error('Tag '.$Method.' Undefined in '.get_class($this).'[Agregated Tag]:<br><b>'.$tag->RebuildTagData().'</b>',E_USER_WARNING);
return false;
}*/
}
function CheckTag($tag, $prefix)
{
$Method = $tag;
if(method_exists($this, $Method))
{
return true;
}
else {
if ($this->Application->hasObject('TagsAggregator')) {
$aggregator =& $this->Application->recallObject('TagsAggregator');
$tmp = $this->Application->processPrefix($prefix);
$tag_mapping = $aggregator->GetArrayValue($tmp['prefix'], $Method);
if ($tag_mapping) {
return true;
}
}
}
}
function ProcessParsedTag($tag, $params, $prefix, $file='unknown', $line=0)
{
$Method = $tag;
if(method_exists($this, $Method))
{
if ($this->Application->isDebugMode() && constOn('DBG_SHOW_TAGS')) {
$this->Application->Debugger->appendHTML('Processing PreParsed Tag '.$Method.' in '.$this->Prefix);
}
$backup_prefix = $this->Prefix;
$backup_special = $this->Special;
$flag_values = $this->PreparePostProcess($params);
// pass_params for non ParseBlock tags :)
if ($flag_values['pass_params']) {
$params = array_merge_recursive2($this->Application->Parser->Params, $params);
}
$ret = $this->$Method($params);
$this->Prefix = $backup_prefix;
$this->Special = $backup_special;
$ret = $this->PostProcess($ret, $flag_values);
return $ret;
}
else
{
if ($this->Application->hasObject('TagsAggregator')) {
$aggregator =& $this->Application->recallObject('TagsAggregator');
$tmp = $this->Application->processPrefix($prefix);
$tag_mapping = $aggregator->GetArrayValue($tmp['prefix'], $Method);
if ($tag_mapping) {
$tmp = $this->Application->processPrefix($tag_mapping[0]);
$__tag_processor = $tmp['prefix'].'_TagProcessor';
$processor =& $this->Application->recallObject($__tag_processor);
$processor->Prefix = $tmp['prefix'];
$processor->Special = getArrayValue($tag_mapping, 2) ? $tag_mapping[2] : $tmp['special'];
$params['original_tag'] = $Method; // allows to define same method for different aggregated tags in same tag processor
$params['PrefixSpecial'] = $this->getPrefixSpecial(); // $prefix;
$ret = $processor->ProcessParsedTag($tag_mapping[1], $params, $prefix);
if (isset($params['result_to_var'])) {
$this->Application->Parser->SetParam($params['result_to_var'], $ret);
$ret = '';
}
return $ret;
}
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendTrace();
}
$this->Application->handleError(E_USER_ERROR, 'Tag <b>'.$Method.'</b> Undefined in '.get_class($this).'[Agregated Tag]:<br><b>'.$tag.'</b>', $file, $line);
}
$this->Application->handleError(E_USER_ERROR, 'Tag Undefined:<br><b>'.$prefix.':'.$tag.'</b>', $file, $line);
return false;
}
}
function PreparePostProcess(&$params)
{
$flags = Array('js_escape', 'result_to_var', 'pass_params', 'html_escape', 'strip_nl');
$flag_values = Array();
foreach ($flags as $flag_name) {
$flag_values[$flag_name] = false;
if (isset($params[$flag_name])) {
$flag_values[$flag_name] = $params[$flag_name];
unset($params[$flag_name]);
}
}
return $flag_values;
}
function PostProcess($ret, $flag_values)
{
if ($flag_values['js_escape']) {
$ret = addslashes($ret);
$ret = str_replace(Array("\r", "\n"), Array('\r', '\n'), $ret);
$ret = str_replace('</script>', "</'+'script>", $ret);
}
if ($flag_values['html_escape']) {
$ret = htmlspecialchars($ret);
}
if ($flag_values['strip_nl']) {
// 1 - strip \r,\n; 2 - strip tabs too
$ret = preg_replace($flag_values['strip_nl'] == 2 ? "/[\r\n\t]/" : "/[\r\n]/", '', $ret);
}
if ($flag_values['result_to_var']) {
$this->Application->Parser->SetParam($flag_values['result_to_var'], $ret);
$ret = '';
}
return $ret;
}
/**
* Not tag, method for parameter
* selection from list in this TagProcessor
*
* @param Array $params
* @param string $possible_names
* @return string
* @access public
*/
function SelectParam($params, $possible_names)
{
if (!is_array($params)) return;
if (!is_array($possible_names))
$possible_names = explode(',', $possible_names);
foreach ($possible_names as $name)
{
if( isset($params[$name]) ) return $params[$name];
}
return false;
}
}
/*class ProcessorsPool {
var $Processors = Array();
var $Application;
var $Prefixes = Array();
var $S;
function ProcessorsPool()
{
$this->Application =& KernelApplication::Instance();
$this->S =& $this->Application->Session;
}
function RegisterPrefix($prefix, $path, $class)
{
// echo " RegisterPrefix $prefix, $path, $class <br>";
$prefix_item = Array(
'path' => $path,
'class' => $class
);
$this->Prefixes[$prefix] = $prefix_item;
}
function CreateProcessor($prefix, &$tag)
{
// echo " prefix : $prefix <br>";
if (!isset($this->Prefixes[$prefix]))
$this->Application->ApplicationDie ("<b>Filepath and ClassName for prefix $prefix not defined while processing ".htmlspecialchars($tag->GetFullTag())."!</b>");
include_once($this->Prefixes[$prefix]['path']);
$ClassName = $this->Prefixes[$prefix]['class'];
- $a_processor =& new $ClassName($prefix);
+ $a_processor = new $ClassName($prefix);
$this->SetProcessor($prefix, $a_processor);
}
function SetProcessor($prefix, &$a_processor)
{
$this->Processors[$prefix] =& $a_processor;
}
function &GetProcessor($prefix, &$tag)
{
if (!isset($this->Processors[$prefix]))
$this->CreateProcessor($prefix, $tag);
return $this->Processors[$prefix];
}
}*/
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/processors/tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.22
\ No newline at end of property
+1.22.2.1
\ No newline at end of property
Index: branches/RC/core/kernel/session/session.php
===================================================================
--- branches/RC/core/kernel/session/session.php (revision 9285)
+++ branches/RC/core/kernel/session/session.php (revision 9286)
@@ -1,954 +1,954 @@
<?php
/*
The session works the following way:
1. When a visitor loads a page from the site the script checks if cookies_on varibale has been passed to it as a cookie.
2. If it has been passed, the script tries to get Session ID (SID) from the request:
3. Depending on session mode the script is getting SID differently.
The following modes are available:
smAUTO - Automatic mode: if cookies are on at the client side, the script relays only on cookies and
ignore all other methods of passing SID.
If cookies are off at the client side, the script relays on SID passed through query string
and referal passed by the client. THIS METHOD IS NOT 100% SECURE, as long as attacker may
get SID and substitude referal to gain access to user' session. One of the faults of this method
is that the session is only created when the visitor clicks the first link on the site, so
there is NO session at the first load of the page. (Actually there is a session, but it gets lost
after the first click because we do not use SID in query string while we are not sure if we need it)
smCOOKIES_ONLY - Cookies only: in this mode the script relays solely on cookies passed from the browser
and ignores all other methods. In this mode there is no way to use sessions for clients
without cookies support or cookies support disabled. The cookies are stored with the
full domain name and path to base-directory of script installation.
smGET_ONLY - GET only: the script will not set any cookies and will use only SID passed in
query string using GET, it will also check referal. The script will set SID at the
first load of the page
smCOOKIES_AND_GET - Combined mode: the script will use both cookies and GET right from the start. If client has
cookies enabled, the script will check SID stored in cookie and passed in query string, and will
use this SID only if both cookie and query string matches. However if cookies are disabled on the
client side, the script will work the same way as in GET_ONLY mode.
4. After the script has the SID it tries to load it from the Storage (default is database)
5. If such SID is found in the database, the script checks its expiration time. If session is not expired, it updates
its expiration, and resend the cookie (if applicable to session mode)
6. Then the script loads all the data (session variables) pertaining to the SID.
Usage:
-$session =& new Session(smAUTO); //smAUTO is default, you could just leave the brackets empty, or provide another mode
+$session = new Session(smAUTO); //smAUTO is default, you could just leave the brackets empty, or provide another mode
$session->SetCookieDomain('my.domain.com');
$session->SetCookiePath('/myscript');
$session->SetCookieName('my_sid_cookie');
$session->SetGETName('sid');
$session->InitSession();
...
//link output:
echo "<a href='index.php?'". ( $session->NeedQueryString() ? 'sid='.$session->SID : '' ) .">My Link</a>";
*/
//Implements session storage in the database
class SessionStorage extends kDBBase {
var $Expiration;
var $SessionTimeout=0;
var $DirectVars = Array();
var $ChangedDirectVars = Array();
var $PersistentVars = Array ();
var $OriginalData=Array();
var $TimestampField;
var $SessionDataTable;
var $DataValueField;
var $DataVarField;
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$this->setTableName('sessions');
$this->setIDField('sid');
$this->TimestampField = 'expire';
$this->SessionDataTable = 'SessionData';
$this->DataValueField = 'value';
$this->DataVarField = 'var';
}
function setSessionTimeout($new_timeout)
{
$this->SessionTimeout = $new_timeout;
}
function StoreSession(&$session, $additional_fields = Array())
{
if (defined('IS_INSTALL') && IS_INSTALL && !$this->Application->TableFound($this->TableName)) {
return false;
}
$fields_hash = Array (
$this->IDField => $session->SID,
$this->TimestampField => $session->Expiration
);
$this->Conn->doInsert($fields_hash, $this->TableName);
foreach ($additional_fields as $field_name => $field_value) {
$this->SetField($session, $field_name, $field_value);
}
}
function DeleteSession(&$session)
{
$query = ' DELETE FROM '.$this->TableName.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
$query = ' DELETE FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
$this->OriginalData = Array();
}
function UpdateSession(&$session, $timeout=0)
{
$this->SetField($session, $this->TimestampField, $session->Expiration);
$query = ' UPDATE '.$this->TableName.' SET '.$this->TimestampField.' = '.$session->Expiration.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
}
function LocateSession($sid)
{
$query = ' SELECT * FROM '.$this->TableName.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($sid);
$result = $this->Conn->GetRow($query);
if($result===false) return false;
$this->DirectVars = $result;
$this->Expiration = $result[$this->TimestampField];
return true;
}
function GetExpiration()
{
return $this->Expiration;
}
function LoadData(&$session)
{
$query = 'SELECT '.$this->DataValueField.','.$this->DataVarField.' FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->OriginalData = $this->Conn->GetCol($query, $this->DataVarField);
return $this->OriginalData;
}
/**
* Enter description here...
*
* @param Session $session
* @param string $var_name
* @param mixed $default
*/
function GetField(&$session, $var_name, $default = false)
{
return isset($this->DirectVars[$var_name]) ? $this->DirectVars[$var_name] : $default;
//return $this->Conn->GetOne('SELECT '.$var_name.' FROM '.$this->TableName.' WHERE `'.$this->IDField.'` = '.$this->Conn->qstr($session->GetID()) );
}
function SetField(&$session, $var_name, $value)
{
$value_changed = !isset($this->DirectVars[$var_name]) || ($this->DirectVars[$var_name] != $value);
if ($value_changed) {
$this->DirectVars[$var_name] = $value;
$this->ChangedDirectVars[] = $var_name;
$this->ChangedDirectVars = array_unique($this->ChangedDirectVars);
}
//return $this->Conn->Query('UPDATE '.$this->TableName.' SET '.$var_name.' = '.$this->Conn->qstr($value).' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->GetID()) );
}
function SaveData(&$session)
{
if(!$session->SID) return false; // can't save without sid
$ses_data = $session->Data->GetParams();
$replace = '';
foreach ($ses_data as $key => $value)
{
if ( isset($this->OriginalData[$key]) && $this->OriginalData[$key] == $value)
{
continue; //skip unchanged session data
}
else
{
$replace .= sprintf("(%s, %s, %s),",
$this->Conn->qstr($session->SID),
$this->Conn->qstr($key),
$this->Conn->qstr($value));
}
}
$replace = rtrim($replace, ',');
if ($replace != '') {
$query = ' REPLACE INTO '.$this->SessionDataTable. ' ('.$this->IDField.', '.$this->DataVarField.', '.$this->DataValueField.') VALUES '.$replace;
$this->Conn->Query($query);
}
if ($this->ChangedDirectVars) {
$changes = array();
foreach ($this->ChangedDirectVars as $var) {
$changes[] = $var.' = '.$this->Conn->qstr($this->DirectVars[$var]);
}
$query = 'UPDATE '.$this->TableName.' SET '.implode(',', $changes).' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->GetID());
$this->Conn->Query($query);
}
}
function RemoveFromData(&$session, $var)
{
$query = 'DELETE FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID).
' AND '.$this->DataVarField.' = '.$this->Conn->qstr($var);
$this->Conn->Query($query);
unset($this->OriginalData[$var]);
}
function GetFromData(&$session, $var)
{
return getArrayValue($this->OriginalData, $var);
}
function GetExpiredSIDs()
{
$query = ' SELECT '.$this->IDField.' FROM '.$this->TableName.' WHERE '.$this->TimestampField.' > '.adodb_mktime();
return $this->Conn->GetCol($query);
}
function DeleteExpired()
{
$expired_sids = $this->GetExpiredSIDs();
if ($expired_sids) {
$where_clause=' WHERE '.$this->IDField.' IN ("'.implode('","',$expired_sids).'")';
$sql = 'DELETE FROM '.$this->SessionDataTable.$where_clause;
$this->Conn->Query($sql);
$sql = 'DELETE FROM '.$this->TableName.$where_clause;
$this->Conn->Query($sql);
// delete debugger ouputs left of expired sessions
foreach ($expired_sids as $expired_sid) {
$debug_file = KERNEL_PATH.'/../cache/debug_@'.$expired_sid.'@.txt';
if (file_exists($debug_file)) {
@unlink($debug_file);
}
}
}
return $expired_sids;
}
function LoadPersistentVars(&$session)
{
$user_id = $session->RecallVar('user_id');
if ($user_id != -2) {
// root & normal users
$sql = 'SELECT VariableValue, VariableName
FROM '.TABLE_PREFIX.'PersistantSessionData
WHERE PortalUserId = '.$user_id;
$this->PersistentVars = $this->Conn->GetCol($sql, 'VariableName');
}
else {
$this->PersistentVars = Array ();
}
}
function StorePersistentVar(&$session, $var_name, $var_value)
{
$user_id = $session->RecallVar('user_id');
if ($user_id == -2 || $user_id === false) {
// -2 (when not logged in), false (when after u:OnLogout event)
return ;
}
$this->PersistentVars[$var_name] = $var_value;
$key_clause = 'PortalUserId = '.$user_id.' AND VariableName = '.$this->Conn->qstr($var_name);
$sql = 'SELECT VariableValue
FROM '.TABLE_PREFIX.'PersistantSessionData
WHERE '.$key_clause;
$record_found = $this->Conn->GetOne($sql);
$fields_hash = Array (
'PortalUserId' => $user_id,
'VariableName' => $var_name,
'VariableValue' => $var_value,
);
if ($record_found) {
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX.'PersistantSessionData', $key_clause);
}
else {
$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'PersistantSessionData');
}
}
function RecallPersistentVar(&$session, $var_name, $default = false)
{
return isset($this->PersistentVars[$var_name]) ? $this->PersistentVars[$var_name] : $default;
}
function RemovePersistentVar(&$session, $var_name)
{
unset($this->PersistentVars[$var_name]);
$user_id = $session->RecallVar('user_id');
if ($user_id != -2) {
$sql = 'DELETE FROM '.TABLE_PREFIX.'PersistantSessionData
WHERE PortalUserId = '.$user_id.' AND VariableName = '.$this->Conn->qstr($var_name);
$this->Conn->Query($sql);
}
}
}
define('smAUTO', 1);
define('smCOOKIES_ONLY', 2);
define('smGET_ONLY', 3);
define('smCOOKIES_AND_GET', 4);
class Session extends kBase {
var $Checkers;
var $Mode;
var $OriginalMode = null;
var $GETName = 'sid';
var $CookiesEnabled = true;
var $CookieName = 'sid';
var $CookieDomain;
var $CookiePath;
var $CookieSecure = 0;
var $SessionTimeout = 3600;
var $Expiration;
var $SID;
/**
* Enter description here...
*
* @var SessionStorage
*/
var $Storage;
var $CachedNeedQueryString = null;
var $Data;
function Session($mode=smAUTO)
{
parent::kBase();
$this->SetMode($mode);
}
function SetMode($mode)
{
$this->Mode = $mode;
$this->CachedNeedQueryString = null;
$this->CachedSID = null;
}
function SetCookiePath($path)
{
$this->CookiePath = $path;
}
function SetCookieDomain($domain)
{
$this->CookieDomain = '.'.ltrim($domain, '.');
}
function SetGETName($get_name)
{
$this->GETName = $get_name;
}
function SetCookieName($cookie_name)
{
$this->CookieName = $cookie_name;
}
function InitStorage($special)
{
$this->Storage =& $this->Application->recallObject('SessionStorage.'.$special);
$this->Storage->setSessionTimeout($this->SessionTimeout);
}
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$this->CheckIfCookiesAreOn();
if ($this->CookiesEnabled) $_COOKIE['cookies_on'] = 1;
$this->Checkers = Array();
$this->InitStorage($special);
- $this->Data =& new Params();
+ $this->Data = new Params();
$tmp_sid = $this->GetPassedSIDValue();
$check = $this->Check();
if( !(defined('IS_INSTALL') && IS_INSTALL) )
{
$expired_sids = $this->DeleteExpired();
if ( ( $expired_sids && in_array($tmp_sid,$expired_sids) ) || ( $tmp_sid && !$check ) ) {
$this->SetSession();
$this->Application->HandleEvent($event, 'u:OnSessionExpire');
return ;
}
}
if ($check) {
$this->SID = $this->GetPassedSIDValue();
$this->Refresh();
$this->LoadData();
}
else {
$this->SetSession();
}
if (!is_null($this->OriginalMode)) $this->SetMode($this->OriginalMode);
}
function IsHTTPSRedirect()
{
$http_referer = getArrayValue($_SERVER, 'HTTP_REFERER');
return (
( PROTOCOL == 'https://' && preg_match('#http:\/\/#', $http_referer) )
||
( PROTOCOL == 'http://' && preg_match('#https:\/\/#', $http_referer) )
);
}
function CheckReferer($for_cookies=0)
{
if (!$for_cookies) {
if ( !$this->Application->ConfigValue('SessionReferrerCheck') || $_SERVER['REQUEST_METHOD'] != 'POST') {
return true;
}
}
$path = preg_replace('/admin[\/]{0,1}$/', '', $this->CookiePath); // removing /admin for compatability with in-portal (in-link/admin/add_link.php)
$reg = '#^'.preg_quote(PROTOCOL.ltrim($this->CookieDomain, '.').$path).'#';
return preg_match($reg, getArrayValue($_SERVER, 'HTTP_REFERER') ) || (defined('IS_POPUP') && IS_POPUP);
}
/*function CheckDuplicateCookies()
{
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookie_str = $_SERVER['HTTP_COOKIE'];
$cookies = explode('; ', $cookie_str);
$all_cookies = array();
foreach ($cookies as $cookie) {
list($name, $value) = explode('=', $cookie);
if (isset($all_cookies[$name])) {
//double cookie name!!!
$this->RemoveCookie($name);
}
else $all_cookies[$name] = $value;
}
}
}
function RemoveCookie($name)
{
$path = $_SERVER['PHP_SELF'];
$path_parts = explode('/', $path);
$cur_path = '';
setcookie($name, false, null, $cur_path);
foreach ($path_parts as $part) {
$cur_path .= $part;
setcookie($name, false, null, $cur_path);
$cur_path .= '/';
setcookie($name, false, null, $cur_path);
}
}*/
function CheckIfCookiesAreOn()
{
// $this->CheckDuplicateCookies();
if ($this->Mode == smGET_ONLY)
{
//we don't need to bother checking if we would not use it
$this->CookiesEnabled = false;
return;
}
$http_query =& $this->Application->recallObject('HTTPQuery');
$cookies_on = isset($http_query->Cookie['cookies_on']); // not good here
$get_sid = getArrayValue($http_query->Get, $this->GETName);
if ($this->IsHTTPSRedirect() && $get_sid) { //Redirect from http to https on different domain
$this->OriginalMode = $this->Mode;
$this->SetMode(smGET_ONLY);
}
if (!$cookies_on || $this->IsHTTPSRedirect()) {
//If referer is our server, but we don't have our cookies_on, it's definetly off
$is_install = defined('IS_INSTALL') && IS_INSTALL;
if (!$is_install && $this->CheckReferer(1) && !$this->Application->GetVar('admin') && !$this->IsHTTPSRedirect()) {
$this->CookiesEnabled = false;
}
else {
//Otherwise we still suppose cookies are on, because may be it's the first time user visits the site
//So we send cookies on to get it next time (when referal will tell us if they are realy off
$this->SetCookie('cookies_on', 1, adodb_mktime() + 31104000); //one year should be enough
}
}
else
$this->CookiesEnabled = true;
return $this->CookiesEnabled;
}
/**
* Sets cookie for current site using path and domain
*
* @param string $name
* @param mixed $value
* @param int $expires
*/
function SetCookie($name, $value, $expires = null)
{
setcookie($name, $value, $expires, $this->CookiePath, $this->CookieDomain, $this->CookieSecure);
}
function Check()
{
// we should check referer if cookies are disabled, and in combined mode
// auto mode would detect cookies, get only mode would turn it off - so we would get here
// and we don't care about referal in cookies only mode
if ( $this->Mode != smCOOKIES_ONLY && (!$this->CookiesEnabled || $this->Mode == smCOOKIES_AND_GET) ) {
if (!$this->CheckReferer())
return false;
}
$sid = $this->GetPassedSIDValue();
if (empty($sid)) return false;
//try to load session by sid, if everything is fine
$result = $this->LoadSession($sid);
return $result;
}
function LoadSession($sid)
{
if( $this->Storage->LocateSession($sid) ) {
//if we have session with such SID - get its expiration
$this->Expiration = $this->Storage->GetExpiration();
//If session has expired
if ($this->Expiration < adodb_mktime()) return false;
//Otherwise it's ok
return true;
}
else //fake or deleted due to expiration SID
return false;
}
function GetPassedSIDValue($use_cache = 1)
{
if (!empty($this->CachedSID) && $use_cache) return $this->CachedSID;
$http_query =& $this->Application->recallObject('HTTPQuery');
$get_sid = getArrayValue($http_query->Get, $this->GETName);
if ($this->Application->GetVar('admin') == 1 && $get_sid) {
$sid = $get_sid;
}
else {
switch ($this->Mode) {
case smAUTO:
//Cookies has the priority - we ignore everything else
$sid = $this->CookiesEnabled ? $this->GetSessionCookie() : $get_sid;
break;
case smCOOKIES_ONLY:
$sid = $this->GetSessionCookie();
break;
case smGET_ONLY:
$sid = $get_sid;
break;
case smCOOKIES_AND_GET:
$cookie_sid = $this->GetSessionCookie();
//both sids should match if cookies are enabled
if (!$this->CookiesEnabled || ($cookie_sid == $get_sid))
{
$sid = $get_sid; //we use get here just in case cookies are disabled
}
else
{
$sid = '';
}
break;
}
}
$this->CachedSID = $sid;
return $this->CachedSID;
}
/**
* Returns session id
*
* @return int
* @access public
*/
function GetID()
{
return $this->SID;
}
/**
* Generates new session id
*
* @return int
* @access private
*/
function GenerateSID()
{
list($usec, $sec) = explode(" ",microtime());
$sid_part_1 = substr($usec, 4, 4);
$sid_part_2 = mt_rand(1,9);
$sid_part_3 = substr($sec, 6, 4);
$digit_one = substr($sid_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$sid_part_1 = ereg_replace("^0","",$sid_part_1);
$sid_part_1=$digit_one.$sid_part_1;
}
$this->setSID($sid_part_1.$sid_part_2.$sid_part_3);
return $this->SID;
}
/**
* Set's new session id
*
* @param int $new_sid
* @access private
*/
function setSID($new_sid)
{
$this->SID=$new_sid;
$this->Application->SetVar($this->GETName,$new_sid);
}
function SetSession()
{
$this->GenerateSID();
$this->Expiration = adodb_mktime() + $this->SessionTimeout;
switch ($this->Mode) {
case smAUTO:
if ($this->CookiesEnabled) {
$this->SetSessionCookie();
}
break;
case smGET_ONLY:
break;
case smCOOKIES_ONLY:
case smCOOKIES_AND_GET:
$this->SetSessionCookie();
break;
}
$this->Storage->StoreSession($this);
if ($this->Application->IsAdmin() || $this->Special == 'admin') {
$this->StoreVar('admin', 1);
}
if ($this->Special != '') {
// front-session called from admin or otherwise, then save it's data
$this->SaveData();
}
$this->Application->resetCounters('UserSession');
}
/**
* Returns SID from cookie
*
* @return int
*/
function GetSessionCookie()
{
return isset($this->Application->HttpQuery->Cookie[$this->CookieName]) ? $this->Application->HttpQuery->Cookie[$this->CookieName] : false;
}
/**
* Updates SID in cookie with new value
*
*/
function SetSessionCookie()
{
$this->SetCookie($this->CookieName, $this->SID, $this->Expiration);
$_COOKIE[$this->CookieName] = $this->SID; // for compatibility with in-portal
}
/**
* Refreshes session expiration time
*
* @access private
*/
function Refresh()
{
if ($this->CookiesEnabled) $this->SetSessionCookie(); //we need to refresh the cookie
$this->Storage->UpdateSession($this);
}
function Destroy()
{
$this->Storage->DeleteSession($this);
- $this->Data =& new Params();
+ $this->Data = new Params();
$this->SID = '';
if ($this->CookiesEnabled) $this->SetSessionCookie(); //will remove the cookie due to value (sid) is empty
$this->SetSession(); //will create a new session
}
function NeedQueryString($use_cache = 1)
{
if ($this->CachedNeedQueryString != null && $use_cache) return $this->CachedNeedQueryString;
$result = false;
switch ($this->Mode)
{
case smAUTO:
if (!$this->CookiesEnabled) $result = true;
break;
/*case smCOOKIES_ONLY:
break;*/
case smGET_ONLY:
case smCOOKIES_AND_GET:
$result = true;
break;
}
$this->CachedNeedQueryString = $result;
return $result;
}
function LoadData()
{
$this->Data->AddParams($this->Storage->LoadData($this));
}
function PrintSession($comment='')
{
if($this->Application->isDebugMode() && constOn('DBG_SHOW_SESSIONDATA')) {
// dump session data
$this->Application->Debugger->appendHTML('SessionStorage ('.$comment.'):');
$session_data = $this->Data->GetParams();
ksort($session_data);
foreach ($session_data as $session_key => $session_value) {
if (IsSerialized($session_value)) {
$session_data[$session_key] = unserialize($session_value);
}
}
$this->Application->Debugger->dumpVars($session_data);
}
if ($this->Application->isDebugMode() && constOn('DBG_SHOW_PERSISTENTDATA')) {
// dump persistent session data
if ($this->Storage->PersistentVars) {
$this->Application->Debugger->appendHTML('Persistant Session:');
$session_data = $this->Storage->PersistentVars;
ksort($session_data);
foreach ($session_data as $session_key => $session_value) {
if (IsSerialized($session_value)) {
$session_data[$session_key] = unserialize($session_value);
}
}
$this->Application->Debugger->dumpVars($session_data);
}
}
}
function SaveData()
{
if (!$this->Application->GetVar('skip_last_template') && $this->Application->GetVar('ajax') != 'yes') {
$this->SaveLastTemplate( $this->Application->GetVar('t') );
}
$this->PrintSession('after save');
$this->Storage->SaveData($this);
}
function SaveLastTemplate($t)
{
// save last_template
$wid = $this->Application->GetVar('m_wid');
$last_env = $this->getLastTemplateENV($t, Array('m_opener' => 'u'));
$last_template = basename($_SERVER['PHP_SELF']).'|'.substr($last_env, strlen(ENV_VAR_NAME) + 1);
$this->StoreVar(rtrim('last_template_'.$wid, '_'), $last_template);
$last_env = $this->getLastTemplateENV($t, null, false);
$last_template = basename($_SERVER['PHP_SELF']).'|'.substr($last_env, strlen(ENV_VAR_NAME) + 1);
$this->StoreVar(rtrim('last_template_popup_'.$wid, '_'), $last_template);
// save other last... variables for mistical purposes (customizations may be)
$this->StoreVar('last_url', $_SERVER['REQUEST_URI']); // needed by ord:StoreContinueShoppingLink
$this->StoreVar('last_env', substr($last_env, strlen(ENV_VAR_NAME)+1));
// save last_template in persistant session
if (!$wid) {
if ($this->Application->IsAdmin()) {
// only for main window, not popups, not login template, not temp mode (used in adm:MainFrameLink tag)
$temp_mode = false;
$passed = explode(',', $this->Application->GetVar('passed'));
foreach ($passed as $passed_prefix) {
if ($this->Application->GetVar($passed_prefix.'_mode')) {
$temp_mode = true;
break;
}
}
if (!$temp_mode) {
if (isset($this->Application->HttpQuery->Get['section'])) {
// check directly in GET, bacause LinkVar (session -> request) used on these vars
$last_template .= '&section='.$this->Application->GetVar('section').'&module='.$this->Application->GetVar('module');
}
$this->StorePersistentVar('last_template_popup', $last_template);
}
}
elseif ($this->Application->GetVar('admin') == 1) {
$admin_session =& $this->Application->recallObject('Session.admin');
/* @var $admin_ses Session */
$admin_session->StorePersistentVar('last_template_popup', '../'.$last_template);
}
}
}
function getLastTemplateENV($t, $params = null, $encode = true)
{
if (!isset($params)) {
$params = Array ();
}
$params['__URLENCODE__'] = 1; // uses "&" instead of "&amp;" for url part concatenation + replaces "\" to "%5C" (works in HTML)
$ret = $this->Application->BuildEnv($t, $params, 'all');
if (!$encode) {
// cancels 2nd part of replacements, that URLENCODE does
$ret = str_replace('%5C', '\\', $ret);
}
return $ret;
}
function StoreVar($name, $value)
{
$this->Data->Set($name, $value);
}
function StorePersistentVar($name, $value)
{
$this->Storage->StorePersistentVar($this, $name, $value);
}
function LoadPersistentVars()
{
$this->Storage->LoadPersistentVars($this);
}
function StoreVarDefault($name, $value)
{
$tmp = $this->RecallVar($name);
if($tmp === false || $tmp == '')
{
$this->StoreVar($name, $value);
}
}
function RecallVar($name, $default = false)
{
$ret = $this->Data->Get($name);
return ($ret === false) ? $default : $ret;
}
function RecallPersistentVar($name, $default = false)
{
return $this->Storage->RecallPersistentVar($this, $name, $default);
}
function RemoveVar($name)
{
$this->Storage->RemoveFromData($this, $name);
$this->Data->Remove($name);
}
function RemovePersistentVar($name)
{
return $this->Storage->RemovePersistentVar($this, $name);
}
/**
* Ignores session varible value set before
*
* @param string $name
*/
function RestoreVar($name)
{
return $this->StoreVar($name, $this->Storage->GetFromData($this, $name));
}
function GetField($var_name, $default = false)
{
return $this->Storage->GetField($this, $var_name, $default);
}
function SetField($var_name, $value)
{
$this->Storage->SetField($this, $var_name, $value);
}
/**
* Deletes expired sessions
*
* @return Array expired sids if any
* @access private
*/
function DeleteExpired()
{
return $this->Storage->DeleteExpired();
}
/**
* Allows to check if user in this session is logged in or not
*
* @return bool
*/
function LoggedIn()
{
$user_id = $this->RecallVar('user_id');
$ret = $user_id > 0;
if ($this->RecallVar('admin') == 1 && ($user_id == -1)) {
$ret = true;
}
return $ret;
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/session/session.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.59.2.1
\ No newline at end of property
+1.59.2.2
\ No newline at end of property
Index: branches/RC/core/kernel/nparser/nparser.php
===================================================================
--- branches/RC/core/kernel/nparser/nparser.php (revision 9285)
+++ branches/RC/core/kernel/nparser/nparser.php (revision 9286)
@@ -1,374 +1,374 @@
<?php
include_once(KERNEL_PATH.'/nparser/ntags.php');
class NParser extends kBase {
var $Stack = array();
var $Level = 0;
var $Buffers = array();
var $InsideComment = false;
var $Params = array();
var $ParamsStack = array();
var $ParamsLevel = 0;
var $Elements = array(); // holds dynamic elements to function names mapping during execution
var $DataExists = false;
function NParser()
{
parent::kBase();
}
function Compile($pre_parsed)
{
$data = file_get_contents($pre_parsed['tname']);
$code = "extract (\$_parser->Params);\n";
$this->Buffers[0] = '<?'."php $code ?>\n";
// finding all the tags
$reg = '(.*?)(<[\\/]?)inp2:([^>]*?)([\\/]?>(\r\n){0,1})';
preg_match_all('/'.$reg.'/s', $data, $results, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
$this->InsideComment = false;
foreach ($results as $tag_data) {
$tag = array(
'opening' => $tag_data[2][0],
'tag' => $tag_data[3][0],
'closing' => $tag_data[4][0],
'line' => substr_count(substr($data, 0, $tag_data[2][1]), "\n")+1,
'file' => $pre_parsed['tname'],
);
// the idea is to count number of comment openings and closings before current tag
// if the numbers do not match we inverse the status of InsideComment
if (substr_count($tag_data[1][0], '<!--') != substr_count($tag_data[1][0], '-->')) {
$this->InsideComment = !$this->InsideComment;
}
// appending any text/html data found before tag
$this->Buffers[$this->Level] .= $tag_data[1][0];
if (!$this->InsideComment) {
if ($this->ProcessTag($tag) === false) {
return false;
}
}
else {
$this->Buffers[$this->Level] .= $tag_data[2][0].$tag_data[3][0].$tag_data[4][0];
}
}
if ($this->Level > 0) {
$this->Application->handleError(E_USER_ERROR, 'Unclosed tag opened by '.$this->TagInfo($this->Stack[$this->Level]->Tag), $this->Stack[$this->Level]->Tag['file'], $this->Stack[$this->Level]->Tag['line']);
return false;
}
// appending text data after last tag (after its closing pos),
// if no tag was found at all ($tag_data is not set) - append the whole $data
$this->Buffers[$this->Level] .= isset($tag_data) ? substr($data, $tag_data[4][1]+strlen($tag_data[4][0])) : $data;
// saving compiled version
$compiled = fopen($pre_parsed['fname'], 'w');
if (!fwrite($compiled, $this->Buffers[0])) {
trigger_error('Saving compiled template failed', E_USER_ERROR);
}
fclose($compiled);
return true;
}
function SplitParamsStr($params_str)
{
preg_match_all('/([\${}a-zA-Z0-9_.\\-\\\\#\\[\\]]+)=(["\']{1,1})(.*?)(?<!\\\)\\2/s', $params_str, $rets, PREG_SET_ORDER);
$values = Array();
// we need to replace all occurences of any current param $key with {$key} for correct variable substitution
foreach ($rets AS $key => $val){
$values[$val[1]] = str_replace('\\' . $val[2], $val[2], $val[3]);
}
return $values;
}
function SplitTag($tag)
{
if (!preg_match('/([^_ \t\n]*)[_]?([^ \t\n]*)[ \t\n]*(.*)$$/s', $tag['tag'], $parts)) {
// this is virtually impossible, but just in case
$this->Application->handleError(E_USER_ERROR, 'Incorrect tag format: '.$tag['tag'], $tag['file'], $tag['line']);
return false;
}
$splited['prefix'] = $parts[2] ? $parts[1] : '__auto__';
$splited['name'] = $parts[2] ? $parts[2] : $parts[1];
$splited['attrs'] = $parts[3];
return $splited;
}
function ProcessTag($tag)
{
$splited = $this->SplitTag($tag);
if ($splited === false) return false;
$tag = array_merge($tag, $splited);
$tag['processed'] = false;
$tag['NP'] = $this->SplitParamsStr($tag['attrs']);
$o = '';
$tag['is_closing'] = $tag['opening'] == '</' || $tag['closing'] == '/>';
if (class_exists('_Tag_'.$tag['name'])) { // block tags should have special handling class
if ($tag['opening'] == '<') {
$class = '_Tag_'.$tag['name'];
$instance = new $class($tag);
$instance->Parser =& $this;
/* @var $instance _BlockTag */
$this->Stack[++$this->Level] =& $instance;
$this->Buffers[$this->Level] = '';
$open_code = $instance->Open($tag);
if ($open_code === false) return false;
$o .= $open_code;
}
if ($tag['is_closing']) { // not ELSE here, because tag may be <empty/> and still has a handler-class
if ($this->Level == 0) {
$dump = array();
foreach ($this->Stack as $instance) {
$dump[] = $instance->Tag;
}
print_pre($dump);
$this->Application->handleError(E_USER_ERROR, 'Closing tag without an opening: '.$this->TagInfo($tag).' <b> - probably opening tag was removed or nested tags error</b>', $tag['file'], $tag['line']);
return false;
}
if ($this->Stack[$this->Level]->Tag['name'] != $tag['name']) {
$opening_tag = $this->Stack[$this->Level]->Tag;
$this->Application->handleError(E_USER_ERROR,
'Closing tag '.$this->TagInfo($tag).' does not match
opening tag at current nesting level ('.$this->TagInfo($opening_tag).'
opened at line '.$opening_tag['line'].')', $tag['file'], $tag['line']);
return false;
}
$o .= $this->Stack[$this->Level]->Close($tag); // DO NOT use $this->Level-- here because it's used inside Close
$this->Level--;
}
}
else { // regular tags - just compile
if (!$tag['is_closing']) {
$this->Application->handleError(E_USER_ERROR, 'Tag without a handler: '.$this->TagInfo($tag).' <b> - probably missing &lt;empty <span style="color: red">/</span>&gt; tag closing</b>', $tag['file'], $tag['line']);
return false;
}
if ($this->Level > 0) $o .= $this->Stack[$this->Level]->PassThrough($tag);
if (!$tag['processed']) {
$compiled = $this->CompileTag($tag);
if ($compiled === false) return false;
$o .= '<?'.'php '.$compiled." ?>\n";
}
}
$this->Buffers[$this->Level] .= $o;
return true;
}
function TagInfo($tag, $with_params=false)
{
return "<b>{$tag['prefix']}_{$tag['name']}".($with_params ? ' '.$tag['attrs'] : '')."</b>";
}
function CompileParamsArray($arr)
{
$to_pass = 'Array(';
foreach ($arr as $name => $val) {
$to_pass .= '"'.$name.'" => "'.str_replace('"', '\"', $val).'",';
}
$to_pass .= ')';
return $to_pass;
}
function CompileTag($tag)
{
$to_pass = $this->CompileParamsArray($tag['NP']);
$code = '';
if ($tag['prefix'] == '__auto__') {
$prefix = $this->GetParam('PrefixSpecial');
$code .= '$_p_ =& $_parser->GetProcessor($PrefixSpecial);'."\n";
$code .= 'echo $_p_->ProcessParsedTag(\''.$tag['name'].'\', '.$to_pass.', "$PrefixSpecial", \''.$tag['file'].'\', '.$tag['line'].');'."\n";
}
else {
$prefix = $tag['prefix'];
$code .= '$_p_ =& $_parser->GetProcessor("'.$tag['prefix'].'");'."\n";
$code .= 'echo $_p_->ProcessParsedTag(\''.$tag['name'].'\', '.$to_pass.', "'.$tag['prefix'].'", \''.$tag['file'].'\', '.$tag['line'].');'."\n";
}
if (isset($tag['NP']['result_to_var'])) {
$code .= "\$params['{$tag['NP']['result_to_var']}'] = \$_parser->GetParam('{$tag['NP']['result_to_var']}');\n";
$code .= "\${$tag['NP']['result_to_var']} = \$params['{$tag['NP']['result_to_var']}'];\n";
}
if ($prefix && strpos($prefix, '$') === false) {
$p =& $this->GetProcessor($prefix);
if (!$p->CheckTag($tag['name'], $tag['prefix'])) {
$this->Application->handleError(E_USER_ERROR, 'Unknown tag: '.$this->TagInfo($tag).' <b> - incorrect tag name or prefix </b>', $tag['file'], $tag['line']);
return false;
}
}
return $code;
}
function CheckTemplate($t, $silent=null)
{
$pre_parsed = $this->Application->TemplatesCache->GetPreParsed($t);
if (!$pre_parsed) {
if (!$silent) {
if ($this->Application->isDebugMode()) $this->Application->Debugger->appendTrace();
trigger_error("Cannot include $t - file does not exist", E_USER_ERROR);
}
return false;
}
if (!$pre_parsed || !$pre_parsed['active'] || defined('DBG_NPARSER_FORCE_COMPILE') && DBG_NPARSER_FORCE_COMPILE) {
- $inc_parser =& new NParser();
+ $inc_parser = new NParser();
if (!$inc_parser->Compile($pre_parsed)) return false;
}
return $pre_parsed;
}
function Run($t, $silent=null)
{
$pre_parsed = $this->CheckTemplate($t, $silent);
if (!$pre_parsed) return false;
ob_start();
$_parser =& $this;
if ($pre_parsed['mode'] == 'file') {
include($pre_parsed['fname']);
}
else {
eval('?'.'>'.$pre_parsed['content']);
}
$output = ob_get_contents();
ob_end_clean();
return $output;
}
function &GetProcessor($prefix)
{
static $Processors = array();
if (!isset($Processors[$prefix])) {
$Processors[$prefix] = $this->Application->recallObject($prefix.'_TagProcessor');
}
return $Processors[$prefix];
}
function SelectParam($params, $possible_names)
{
if (!is_array($params)) return;
if (!is_array($possible_names))
$possible_names = explode(',', $possible_names);
foreach ($possible_names as $name)
{
if( isset($params[$name]) ) return $params[$name];
}
return false;
}
function SetParams($params)
{
$this->Params = $params;
$keys = array_keys($this->Params);
}
function GetParam($name)
{
return isset($this->Params[$name]) ? $this->Params[$name] : false;
}
function SetParam($name, $value)
{
$this->Params[$name] = $value;
}
function PushParams($params)
{
$this->ParamsStack[$this->ParamsLevel++] = $this->Params;
$this->Params = $params;
}
function PopParams()
{
$this->Params = $this->ParamsStack[--$this->ParamsLevel];
}
function ParseBlock($params, $pass_params=false)
{
if ($pass_params || isset($params['pass_params'])) $params = array_merge($this->Params, $params);
$this->PushParams($params);
$data_exists_bak = $this->DataExists;
// if we are parsing design block and we have block_no_data - we need to wrap block_no_data into design,
// so we should set DataExists to true manually, otherwise the design block will be skipped because of data_exists in params
//
// keep_data_exists is used by block RenderElement (always added in ntags.php), to keep the DataExists value
// from inside-content block, otherwise when parsing the design block DataExists will be reset to false resulting missing design block
$this->DataExists = isset($params['keep_data_exists']) && $this->DataExists || (isset($params['design']) && isset($params['block_no_data']) && $params['name'] == $params['design']);
if (!isset($this->Elements[$params['name']])) {
$pre_parsed = $this->Application->TemplatesCache->GetPreParsed($params['name']);
if ($pre_parsed) {
return $this->IncludeTemplate($params);
}
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendTrace();
}
$trace_results = debug_backtrace();
$this->Application->handleError(E_USER_ERROR, '<b>Rendering of undefined element '.$params['name'].'</b>', $trace_results[0]['file'], $trace_results[0]['line']);
}
$m_processor =& $this->GetProcessor('m');
$flag_values = $m_processor->PreparePostProcess($params);
$f_name = $this->Elements[$params['name']];
$ret = $f_name($this, $params);
$ret = $m_processor->PostProcess($ret, $flag_values);
$this->PopParams();
$this->CheckNoData($ret, $params);
$this->DataExists = $data_exists_bak || $this->DataExists;
return $ret;
}
function IncludeTemplate($params, $silent=null)
{
$t = is_array($params) ? $this->SelectParam($params, 't,template,block,name') : $params;
$t = eregi_replace("\.tpl$", '', $t);
$data_exists_bak = $this->DataExists;
$this->DataExists = false;
if ($t == 'platform/elements/content_boxes/sub_categories') {
echo '';
}
$this->PushParams($params);
$ret = $this->Run($t, $silent);
$this->PopParams();
$this->CheckNoData($ret, $params);
$this->DataExists = $data_exists_bak || $this->DataExists;
return $ret;
}
function CheckNoData(&$ret, $params)
{
if (isset($params['data_exists']) && !$this->DataExists) {
$block_no_data = isset($params['BlockNoData']) ? $params['BlockNoData'] : (isset($params['block_no_data']) ? $params['block_no_data'] : false);
if ($block_no_data) {
$ret = $this->ParseBlock(array('name'=>$block_no_data));
}
else {
$ret = '';
}
}
}
}
\ No newline at end of file
Property changes on: branches/RC/core/kernel/nparser/nparser.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1.2.2
\ No newline at end of property
+1.1.2.3
\ No newline at end of property
Index: branches/RC/core/kernel/parser/template.php
===================================================================
--- branches/RC/core/kernel/parser/template.php (revision 9285)
+++ branches/RC/core/kernel/parser/template.php (revision 9286)
@@ -1,267 +1,267 @@
<?php
class Template {
var $Body = '';
var $BasePath = '';
var $Filename = '';
function Template($base_path=null, $filename=null, $silent=0)
{
if ($this->SetBasePath($base_path)) {
if (isset($filename)) {
$this->Filename = $filename;
$this->LoadTemplate($silent);
}
}
}
function SetBasePath($base_path=null)
{
if (isset($base_path)) {
$base_path = eregi_replace("/$", '', $base_path); //Cutting possible last slash
$this->BasePath = $base_path;
return true;
}
return false;
}
function GetFullPath()
{
return $this->BasePath.'/'.ltrim($this->Filename, '/').'.tpl';
}
/**
* Enter description here...
*
* @param int $silent template not found {0 - fatal error, 1 - warning, 2 - nothing}
* @return bool
*/
function LoadTemplate($silent = 0)
{
$filename = $this->GetFullPath();
if (file_exists($filename)) {
if (filesize ($filename) == 0) {
trigger_error("Template file size is 0: <b>$filename</b>", ($silent ? E_USER_NOTICE : E_USER_ERROR) );
}
// stripping out special comments
$this->SetBody(preg_replace('/<!--##.*##-->/sU', '', file_get_contents($filename)));
/*$handle = fopen ($filename, "r");
$contents = fread ($handle, filesize ($filename));
$this->SetBody($contents);
fclose ($handle);*/
return true;
}
else {
if (($silent != 2) && !$silent) {
$application =& kApplication::Instance();
if ($application->isDebugMode()) {
$application->Debugger->appendTrace();
}
trigger_error('File or block not found: <b>'.$filename.'</b> at '.$application->Parser->TemplateName, E_USER_ERROR);
}
return false;
}
}
function SetBody($body)
{
$this->Body = $body;
}
function GetBody()
{
return $this->Body;
}
}
class TemplatesCache extends kBase {
var $Templates = Array();
var $BasePath;
var $FileNames = Array();
function TemplatesCache()
{
parent::kBase();
$this->BasePath = FULL_PATH.THEMES_PATH;
$conn =& $this->Application->GetADODBConnection();
}
/**
* Based on template name gets it's location on disk and owner module
*
* @param string $filename
* @return Array 0 - path on disk, 1 - template name
*/
function GetTemplatePaths($filename)
{
if ($this->Application->IsAdmin() && isset($this->Application->ReplacementTemplates[$filename])) {
$filename = $this->Application->ReplacementTemplates[$filename];
}
// allows to use non-replaced version of replaced template
$filename = preg_replace('/^original:(.*)/', '\\1', $filename);
if (preg_match('#^[\/]{0,1}([^\/]*)\/(.*)#', $filename, $regs)) {
$module_filename = $regs[2];
$first_dir = $regs[1];
}
else {
$first_dir = '';
$module_filename = $filename;
}
// !preg_match for backward compatability with full-path plugins
if ($this->Application->IsAdmin() && $first_dir == 'plugins' && !preg_match('/admin_templates/', $module_filename)) {
if (preg_match('#^[\/]{0,1}([^\/]*)\/(.*)#', $module_filename, $regs)) {;
$path = MODULES_PATH.'/'.strtolower($first_dir).'/'.$regs[1].'/admin_templates';
$module_filename = $regs[2];
}
else {
$first_dir = '';
$module_filename = $filename;
}
}
elseif ( $this->Application->IsAdmin() && $this->Application->findModule('Name', $first_dir)) {
if ($first_dir == 'in-portal') {
$first_dir = 'kernel';
}
$path = MODULES_PATH.'/'.strtolower($first_dir).'/admin_templates';
}
else {
$path = $this->BasePath;
$module_filename = $first_dir.'/'.$module_filename;
}
return Array ($path, $module_filename);
}
function LoadTemplate($filename, $title=NULL, $silent=0)
{
list ($path, $module_filename) = $this->GetTemplatePaths($filename);
- $template =& new Template($path, $module_filename, $silent);
+ $template = new Template($path, $module_filename, $silent);
if (!isset($title)) $title = $filename;
$this->SetTemplate($title, $template);
}
function GetRealFilename($filename)
{
list ($path, $module_filename) = $this->GetTemplatePaths($filename);
return $path.'/'.trim($module_filename, '/');
}
function SetTemplate($title, &$template, $filename=null)
{
if (!isset($filename)) $filename=$title;
$this->Templates[$title] = $template;
$this->FileNames[$title] = $filename;
}
function &GetTemplate($title, $silent=0)
{
if (!isset($this->Templates[$title])) {
$this->LoadTemplate($title, null, $silent);
}
return $this->Templates[$title];
}
function GetTemplateBody($title, $silent=0)
{
$template =& $this->GetTemplate($title, $silent);
if ( !is_object($template) ) {
return '';
}
return $template->GetBody();
}
function GetTemplateFileName($title)
{
return getArrayValue($this->FileNames, $title);
}
function SetTemplateBody($title, $body)
{
- $template =& new Template();
+ $template = new Template();
$template->SetBody($body);
$this->SetTemplate($title, $template);
}
function ParseTemplate($template_name)
{
- $Parser =& new TemplateParser($this->Application);
+ $Parser = new TemplateParser($this->Application);
return $Parser->Parse( $this->GetTemplateBody($template_name) );
}
function TemplateExists($filename)
{
$real_file = $this->GetRealFilename($filename);
if (!preg_match('/\.tpl$/', $real_file)) {
$real_file .= '.tpl';
}
return file_exists($real_file);
}
function GetPreParsed($template)
{
$real_name = $this->GetRealFilename($template);
$fname = $real_name.'.php';
$fname = str_replace(FULL_PATH, defined('WRITEABLE') ? WRITEABLE.'/cache' : FULL_PATH.'/kernel/cache', $fname);
$tname = $real_name.'.tpl';
if (!file_exists($tname)) {
return false;
}
if (defined('SAFE_MODE') && SAFE_MODE) {
$conn =& $this->Application->GetADODBConnection();
$cached = $conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'Cache WHERE VarName = "'.$fname.'"');
if ($cached !== false && $cached['Cached'] > filemtime($tname)) {
return array('active' => 1, 'fname' => $fname, 'tname' => $tname, 'mode' => 'db', 'content' => $cached['Data']);
}
}
else {
if (file_exists($fname) && file_exists($tname) && filemtime($fname) > filemtime($tname)) {
return array('active' => 1, 'fname' => $fname, 'tname' => $tname, 'mode' => 'file');
}
if (!file_exists($fname)) {
// make sure to create directory if pre-parsed file does not exist
$this->CheckDir(dirname($fname), defined('WRITEABLE') ? WRITEABLE.'/cache' : FULL_PATH.'/kernel/cache');
}
}
return array('active' => 0, 'fname' => $fname, 'tname' => $tname, 'mode'=>'file');
}
/**
* Recursive mkdir
*
* @param string $dir
* @param string $base_path base path to directory where folders should be created in
*/
function CheckDir($dir, $base_path = '')
{
if (file_exists($dir)) {
return;
}
else {
// remove $base_path from beggining because it is already created during install
$dir = preg_replace('/^'.preg_quote($base_path.'/', '/').'/', '', $dir, 1);
$segments = explode('/', $dir);
$cur_path = $base_path;
foreach ($segments as $segment) {
// do not add leading / for windows paths (c:\...)
$cur_path .= preg_match('/^[a-zA-Z]{1}:/', $segment) ? $segment : '/'.$segment;
if (!file_exists($cur_path)) {
mkdir($cur_path);
}
}
}
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/parser/template.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.26
\ No newline at end of property
+1.26.2.1
\ No newline at end of property
Index: branches/RC/core/kernel/parser/tags.php
===================================================================
--- branches/RC/core/kernel/parser/tags.php (revision 9285)
+++ branches/RC/core/kernel/parser/tags.php (revision 9286)
@@ -1,463 +1,463 @@
<?php
define ('parse', 0);
define ('skip', 1);
define ('skip_tags', 2);
class MyTagHolder extends kBase {
var $_Tag;
function MyTagHolder()
{
}
function &GetTag($tag_data, &$parser, $inp_tag = 0)
{
if (!isset($this->_Tag)) {
- $this->_Tag =& new Tag($tag_data, $parser, $inp_tag);
+ $this->_Tag = new Tag($tag_data, $parser, $inp_tag);
}
else {
// $this->_Tag->Parser =& $parser;
$this->_Tag->TagData = $tag_data;
if ($tag_data != '') $this->_Tag->ParseTagData($tag_data);
$this->_Tag->NP =& $this->_Tag->NamedParams;
}
$this->_Tag->TemplateName = $parser->TemplateName;
return $this->_Tag;
}
}
class Tag extends kBase {
var $Processor;
var $Tag;
var $Params = Array();
var $NamedParams = Array();
var $NP;
var $TemplateName;
/**
* Enter description here...
*
* @var TemplateParser
*/
var $Parser;
var $TagData = '';
function Tag($tag_data, &$parser, $inp_tag=0)
{
parent::kBase();
$this->Parser =& $parser;
$this->TagData = $tag_data;
if ($tag_data != '') $this->ParseTagData($tag_data);
$this->NP =& $this->NamedParams;
}
function CopyFrom(&$tag)
{
$this->Processor = $tag->Processor;
$this->Tag = $tag->Tag;
$this->TagData = $tag->TagData;
$this->Params = $tag->Params;
$this->NamedParams = $tag->NamedParams;
$this->Parser =& $tag->Parser;
$this->TemplateName = $tag->TemplateName;
}
function GetFullTag()
{
return '<%'.$this->TagData.'%>';
}
function RebuildTagData()
{
$res = $this->Processor.':'.$this->Tag.' ';
foreach ($this->NamedParams as $name => $value) {
$res .= "$name='$value' ";
}
return $res;
}
/**
* Escape chars in phrase translation, that could harm parser to process tag
*
* @param string $text
* @return string
* @access private
*/
function EscapeReservedChars($text)
{
$reserved = Array('"',"'"); // =
$replacement = Array('\"',"\'"); // \=
return str_replace($reserved,$replacement,$text);
}
function ReplaceParams($tag_data)
{
//print_pre($this->Parser->Pattern, $tag_data);
$values = $this->Parser->Values;
foreach($values as $param_name => $param_value)
{
$values[$param_name] = $this->EscapeReservedChars($param_value);
}
if (is_array($this->Parser->Params)) {
$tag_data = preg_replace($this->Parser->Pattern, $values, $tag_data);
}
//echo "got: $tag_data<br>";
return $tag_data;
}
function PreParseReplaceParams($tag_data)
{
//print_pre($this->Parser->Pattern, $tag_data);
$values = $this->Parser->Values;
foreach($values as $param_name => $param_value)
{
$values[$param_name] = $this->EscapeReservedChars($param_value);
}
/*$patterns = Array();
if ( is_array($this->Parser->Args) ) {
foreach ($this->Parser->Args as $arg) {
}
}*/
if ($this->Parser->SkipMode == parse) {
if (is_array($this->Parser->Params)) {
$tag_data = preg_replace($this->Parser->Pattern, $values, $tag_data);
}
}
//echo "got: $tag_data<br>";
return $tag_data;
}
function CmpParams($a, $b)
{
$a_len = strlen($a);
$b_len = strlen($b);
if ($a_len == $b_len) return 0;
return $a_len > $b_len ? -1 : 1;
}
/**
* Set's Prefix and Special for Tag object
* based on ones from tagname
*
* @param string $tag_data
* @access protected
*/
function ParseTagData($tag_data)
{
if (defined('EXPERIMENTAL_PRE_PARSE') ) {
$this->OriginalTagData = $tag_data;
$tag_data = $this->PreParseReplaceParams($tag_data) . ' ';
}
else {
$tag_data = $this->ReplaceParams($tag_data) . ' ';
// $tag_data = $this->Application->ReplaceLanguageTags($tag_data);
}
list ($key_data, $params) = split("[ \t\n]{1}", $tag_data, 2);
$key_data = trim($key_data);
$tmp=explode(':',$key_data);
$this->Tag=$tmp[1];
$tmp=$this->Application->processPrefix($tmp[0]);
$this->Prefix=$tmp['prefix'];
$this->Special=$tmp['special'];
$this->Processor=$this->Prefix;
if ($params != '') {
$this->ParseNamedParams($params);
}
else {
$this->NamedParams = array();
}
}
function ParseNamedParams($params_str)
{
- $params =& new Params($params_str);
+ $params = new Params($params_str);
$this->NamedParams = $params->_Params;
}
function GetParam($param)
{
if (isset($this->NP[$param]))
return $this->NP[$param];
else
return false;
}
/**
* Process IF tags in specific way
*
*/
function Process()
{
$short_closing = false;
if (isset($this->NP['_short_closing_'])) {
unset($this->NP['_short_closing_']);
$this->TagData = str_replace(' _short_closing_="1"', '', $this->TagData);
$short_closing = true;
}
if ($this->Processor == 'm' || $this->Processor == 'm_TagProcessor') { //if we are procssing Main tags
if ($this->Tag == 'block' || $this->Tag == 'DefineElement' || ($this->Tag == 'RenderElement' && $short_closing)) {
- $tag =& new BlockTag('', $this->Parser);
+ $tag = new BlockTag('', $this->Parser);
$tag->CopyFrom($this);
$tag->Process();
}
elseif($this->Tag == 'Capture') {
- $tag =& new CaptureTag('', $this->Parser);
+ $tag = new CaptureTag('', $this->Parser);
$tag->CopyFrom($this);
$tag->Process();
}
elseif ($this->Parser->SkipMode == skip_tags) {
return;
}
elseif (
$this->Tag == 'if' ||
$this->Tag == 'ifnot' ||
$this->Tag == 'else' ||
$this->Tag == 'elseif'
)
{
if ( defined('EXPERIMENTAL_PRE_PARSE') ) {
$this->Parser->AppendCompiledCode( $this->GetCode() );
}
- $tag =& new ConstructTag('', $this->Parser);
+ $tag = new ConstructTag('', $this->Parser);
$tag->CopyFrom($this);
$tag->Process();
}
else {
if ($this->Parser->SkipMode == skip) {
if ( defined('EXPERIMENTAL_PRE_PARSE') ) {
$this->Parser->AppendCompiledCode( $this->GetCode() );
}
return;
}
$this->ProcessTag();
if ( defined('EXPERIMENTAL_PRE_PARSE') ) {
$this->Parser->AppendCompiledCode( $this->GetCode() );
}
}
}
else { //normal tags - processors other than main
if ($this->Parser->SkipMode == skip) { // inside if - add statements inside if to compiled code
if ( defined('EXPERIMENTAL_PRE_PARSE') ) {
$this->Parser->AppendCompiledCode( $this->GetCode() );
}
return;
}
elseif ($this->Parser->SkipMode == skip_tags) return; //do not parse if we skipping tags
$this->ProcessTag();
if ( defined('EXPERIMENTAL_PRE_PARSE') ) {
$this->Parser->AppendCompiledCode( $this->GetCode() );
}
}
}
/**
* Set's Prefix and Special for TagProcessor
* based on tag beeing processed
*
* @return string
* @access protected
*/
function DoProcessTag()
{
// $tag->Prefix - l_TagProcessor
$tmp = $this->Application->processPrefix($this->Processor);
if (isset($this->NamedParams['_ignore_missing_'])) {
if (!$this->Application->prefixRegistred($tmp['prefix'])) return '';
}
$processor =& $this->Application->recallObject($tmp['prefix'].'_TagProcessor'); // $this->Processor
$tmp=explode('_',$tmp['prefix'],2);
$processor->Prefix=$tmp[0];
$processor->Special=$this->Special;
// pass_params for non ParseBlock tags :)
$parser_params = $this->Application->Parser->Params;
if( getArrayValue($this->NamedParams,'pass_params') )
{
unset( $this->NamedParams['pass_params'] );
$this->NamedParams = array_merge_recursive2($parser_params, $this->NamedParams);
}
return $processor->ProcessTag($this);
}
function ProcessTag()
{
$o = $this->DoProcessTag();
if ($o !== false)
{
$this->Parser->AppendOutput($o);
}
else
{
trigger_error('can\'t process tag '.$this->Tag.' in '.$this->Prefix,E_USER_WARNING);
}
}
function GetCode($echo=false)
{
$tmp_params = $this->NamedParams;
$splited = split("[ \t\n]{1}", $this->OriginalTagData, 2);
if (isset($splited[1]) && $splited[1]) {
$this->ParseNamedParams($splited[1]);
}
$pass_params = $this->NamedParams;
$this->NamedParams = $tmp_params;
$code = Array();
$to_pass = 'Array(';
foreach ($pass_params as $name => $val) {
$to_pass .= '"'.$name.'" => "'.str_replace('"', '\"', $val).'",';
}
$to_pass .= ')';
if ($echo) $code[] = '$o = '."'';\n";
switch ( strtolower($this->Tag) ) {
case 'defaultparam':
foreach ($this->NP as $key => $val) {
$code[] = 'if (!isset($'.$key.')) $application->Parser->SetParam(\''.$key.'\', \''.$val.'\');';
$code[] = '$'.$key.' = isset($'.$key.') ? $'.$key.' : \''.$val.'\';';
}
return $code;
case 'param':
case 'Param':
$code[] = 'if (isset($application->LateParsed["'.$this->NP['name'].'"])) {';
$code[] = '$__f = $application->PreParsedBlocks[\'capture_'.$this->NP['name'].'\'];';
$code[] = '$application->Parser->SetParam(\''.$this->NP['name'].'\', $__f(array())'.');';
$code[] = '$'.$this->NP['name'].' = $application->Parser->GetParam(\''.$this->NP['name'].'\');';
$code[] = '$params[\''.$this->NP['name'].'\'] = $'.$this->NP['name'].';';
$code[] = '}';
$code[] = '$p =& $application->recallObject(\'m_TagProcessor\');';
$code[] = '$tag_params = '.$to_pass.';';
$param_code = '$o .= $p->PostProcess($params["'.$this->NP['name'].'"], $p->PreparePostProcess($tag_params))';
if (isset($this->NP['plus'])) {
$param_code .= ' + '.$this->NP['plus'];
}
$code[] = $param_code.';';
return $code;
case 'if':
if (isset($this->NP['_closing_tag_'])) {
$code[] = ' }';
}
else {
$check = isset($pass_params['check']) && $pass_params['check'] ? $pass_params['check'] : false; // $this->GetParam('check');
if ($check) {
if (strpos($check, '_') !== false) {
list($prefix, $function) = explode('_', $check, 2);
}
else {
$function = $check;
$prefix = '$PrefixSpecial'; // $this->Parser->GetParam('PrefixSpecial');
}
}
else {
$prefix = $pass_params['prefix']; // $this->GetParam('prefix');
$function = $pass_params['function']; // $this->GetParam('function');
}
$code[] = '$tmp = $application->processPrefix("'.$prefix.'");'."\n";
$code[] = '$__tp = $tmp[\'prefix\'].\'_TagProcessor\';'."\n";
$code[] = '$p =& $application->recallObject($__tp);'."\n";
$code[] = '$p->Prefix = $tmp[\'prefix\'];'."\n";
$code[] = '$p->Special = $tmp[\'special\'];'."\n";
$code[] = '$if_result = $p->ProcessParsedTag(\''.$function.'\', '.$to_pass.', "'.$prefix.'");'."\n";
if (isset($pass_params['inverse'])) {
$code[] = 'if (!$if_result) {';
}
else {
$code[] = 'if ($if_result) {';
}
}
return $code;
case 'endif':
$code[] = ' }';
return $code;
case 'else':
$code[] = ' }';
$code[] = ' else {';
return $code;
}
/* $tmp_pref = $this->getPrefixSpecial();
$tmp = $this->Application->processPrefix($tmp_pref);
$tmp_processor = $tmp['prefix'].'_TagProcessor';
if (strpos($tmp['prefix'], '$') !== false) {
$processor_to_check = '{'.$tmp['prefix'].'}_TagProcessor';
}
else {
$processor_to_check = $tmp_processor;
} */
if (isset($this->NamedParams['_auto_prefix_'])) {
$prefix = '$PrefixSpecial';
}
else {
// use original prefix_special found in templates (parameter names in form $ParamName found in it will not be replaced with values)
list ($prefix, $tag) = explode(':', $splited[0], 2); //$prefix = $this->getPrefixSpecial();
if (isset($this->NamedParams['_ignore_missing_'])) {
if (!$this->Application->prefixRegistred($prefix)) return array();
}
}
$code[] = '$tmp = $application->processPrefix("'.$prefix.'");'."\n";
/*if (!isset($this->Application->CompilationCache[$this->getPrefixSpecial()])) {
$code[] = '$tmp = $application->processPrefix("'.$this->getPrefixSpecial().'");'."\n";
$code[] = '$__tp = $tmp[\'prefix\'].\'_TagProcessor\';'."\n";
$code[] = '$application->CachedProcessors["'.$this->getPrefixSpecial().'"] =& $application->recallObject($__tp);'."\n";
$this->Application->CompilationCache[$this->getPrefixSpecial()] = true;
if (strpos($tmp_pref, '$') === false) {
$this->Application->CachedProcessors[$this->getPrefixSpecial()] =& $this->Application->recallObject($tmp_processor);
}
}
$this->Parser->UsedProcessors[] = $tmp['prefix'];*/
$code[] = '$__tp = $tmp[\'prefix\'].\'_TagProcessor\';'."\n";
$code[] = '$p =& $application->recallObject($__tp);'."\n";
$code[] = '$p->Prefix = $tmp[\'prefix\'];'."\n";
$code[] = '$p->Special = $tmp[\'special\'];'."\n";
$tag_func = $this->Tag;
if ($tag_func == 'include') $tag_func = 'MyInclude';
// $code[] = '$o .= $application->CachedProcessors["'.$this->getPrefixSpecial().'"]->ProcessParsedTag(\''.$tag_func.'\', '.$to_pass.', "'.$this->Processor.'");'."\n";
$code[] = '$o .= $p->ProcessParsedTag(\''.$tag_func.'\', '.$to_pass.', "'.$prefix.'");'."\n"; // $this->Processor
/*$code = ' $processor =& $application->recallObject(\''.$this->Processor.'_TagProcessor\');
$o .= $processor->ProcessParsedTag(\''.$this->Tag.'\', unserialize(\''.serialize($this->NP).'\'));';*/
if (isset($pass_params['result_to_var'])) {
$code[] = '$'.$pass_params['result_to_var'].' = $application->Parser->GetParam(\''.$pass_params['result_to_var'].'\');';
$code[] = '$params[\''.$pass_params['result_to_var'].'\'] = $'.$pass_params['result_to_var'].';';
$echo = false;
}
if ($echo) $code[] = ' echo $o;'."\n";
return $code;
//return '$o .= \'tag:'. $this->Tag .'\'';
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/parser/tags.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.21
\ No newline at end of property
+1.21.2.1
\ No newline at end of property
Index: branches/RC/core/kernel/parser/construct_tags.php
===================================================================
--- branches/RC/core/kernel/parser/construct_tags.php (revision 9285)
+++ branches/RC/core/kernel/parser/construct_tags.php (revision 9286)
@@ -1,378 +1,378 @@
<?php
define('CM_PARSE', 1);
define('CM_LATE_PARSE', 2);
//Template language contruct tags (if, block...) which has opening and ending
class ConstructTag extends Tag {
var $StopTag = '';
var $SkipMode = 0;
var $Logic = 0;
function SetStopTag($tag)
{
$this->StopTag = $tag;
}
function StoreSkipMode()
{
$this->SkipMode = $this->Parser->SkipMode;
}
function RestoreSkipMode()
{
$this->Parser->SetSkipMode($this->SkipMode);
}
function RestoreThisLevelSkipMode()
{
$this->SkipMode = $this->Parser->Recursion[$this->Parser->RecursionIndex]->SkipMode;
}
function SuggestSkipMode($mode)
{
if ($mode >= 1) //if we need to skip - always forcing it
$this->Parser->SetSkipMode($mode);
else { //if we need to turn of skipping
if ($this->SkipMode == parse) //check if initially skipping was off
$this->Parser->SetSkipMode(parse); //set it to off only then
}
}
function GetLogic()
{
if ($this->Parser->SkipMode != parse) {
$this->Logic = false;
return;
}
$check = $this->GetParam('check');
if ($check) {
if (strpos($check, '_') !== false) {
list($prefix, $function) = explode('_', $check, 2);
}
else {
$function = $check;
$prefix = $this->Parser->GetParam('PrefixSpecial');
}
}
else {
$prefix = $this->GetParam('prefix');
$function = $this->GetParam('function');
}
$this->NP['prefix'] = $prefix;
$this->NP['function'] = $function;
$inverse = $this->GetParam('inverse');
if ($prefix !== false) {
- $tag =& new Tag('', $this->Parser);
+ $tag = new Tag('', $this->Parser);
$tag->Tag = $function;
$tmp = $this->Application->processPrefix($prefix);
$tag->Processor = $tmp['prefix'];
$tag->Prefix=$tmp['prefix'];
$tag->Special=$tmp['special'];
$tag->NamedParams = $this->NP;
$this->Logic = $tag->DoProcessTag();
// echo " this->Logic : ".$this->Logic."<br>";
}
else
{
$this->Logic = $function;
}
if($inverse) $this->Logic = !$this->Logic;
}
function Process()
{
switch ($this->Tag) {
case 'if':
case 'ifnot':
$this->GetLogic();
$this->SetStopTag('endif'); //This recursion level should end when 'endif' is found
$this->Parser->Recurve($this); //Saving current tag in parser recursion array
$this->StoreSkipMode(); //Storing initial SkipMode
if ($this->Logic) {
$this->SuggestSkipMode(parse); //suggest we parse it
}
else {
$this->SuggestSkipMode(skip); //suggest we don't parse it
}
break;
case 'elseif':
$if_logic = $this->Parser->Recursion[$this->Parser->RecursionIndex]->Logic;
if (!$if_logic) { //if IF or ELSEIF above have not worked
$this->GetLogic();
if ($this->Logic) { //ELSEIF should run
$this->Parser->Recursion[$this->Parser->RecursionIndex]->Logic = $this->Logic; //To escape running ELSE or ELSEIF below
$this->SuggestSkipMode(parse);
}
else { //ELSEIF should NOT run
$this->SuggestSkipMode(skip);
}
}
else //IF or ELSEIF above HAVE worked - this ELSEIF should NOT run
$this->SuggestSkipMode(skip);
break;
case 'else':
$if_logic = $this->Parser->Recursion[$this->Parser->RecursionIndex]->Logic;
$this->RestoreThisLevelSkipMode();
if (!$if_logic) { //IF was false - ELSE should run
$this->SuggestSkipMode(parse);
}
else { //IF was true - ELSE should not run
$this->SuggestSkipMode(skip);
}
break;
}
}
function CheckRecursion(&$tag)
{
if ($this->CheckEndRecursion($tag)) {
if (defined('EXPERIMENTAL_PRE_PARSE')) {
if ($tag->Tag == 'if' || $tag->Tag == 'endif') {
$this->Parser->AppendCompiledCode('}');
$this->Parser->ResetCode();
}
}
$this->RestoreSkipMode(); //Restoring original SkipMode
return true;
}
else {
if (defined('EXPERIMENTAL_PRE_PARSE')) {
// && ($tag->Tag != 'RenderElement' && isset($tag->NP['_short_closing_']))
if ($tag->Tag != 'block' && $tag->Tag != 'DefineElement' && $tag->Tag != 'Capture' && !($tag->Tag == 'RenderElement' && isset($tag->NP['_short_closing_']))) {
$this->Parser->AppendCode($tag->GetCode());
}
// $this->Parser->AppendCompiledCode( $tag->GetCode() );
}
}
return false;
}
function CheckEndRecursion(&$tag)
{
if ($tag->GetParam('_closing_tag_') == 1 && $tag->Tag == $this->Tag) {
return true;
}
return ($tag->Tag == $this->StopTag); //Tag matches StopTag we are waiting for to close current recursion
}
}
class BlockTag extends ConstructTag {
var $BlockName = '';
var $InsideBlock = 0;
function Process()
{
switch ($this->Tag) {
case 'block':
case 'DefineElement':
case 'RenderElement':
if ($this->Tag == 'DefineElement') {
$this->SetStopTag('end_define'); //This recursion level should end when 'blockend' is found
}
else {
$this->SetStopTag('blockend'); //This recursion level should end when 'blockend' is found
}
if ($this->Tag == 'RenderElement') {
$this->NP['name'] = '__lambda_element_'.abs(crc32($this->TemplateName)).'_'.$this->Application->LambdaElements++;
- $RenderTag =& new Tag($this->TagData.' name="'.$this->NP['name'].'"', $this->Parser);
+ $RenderTag = new Tag($this->TagData.' name="'.$this->NP['name'].'"', $this->Parser);
$this->Parser->AppendCode($RenderTag->GetCode());
}
$this->Parser->Recurve($this); //Saving current tag in parser recursion array
$this->Parser->SetBuffer('');
$this->BlockName = $this->NP['name']; //Stroing BlockName
if (isset($this->NP['args']) ) {
$this->Parser->Args = explode(',', $this->NP['args']);
}
$this->StoreSkipMode();
$this->SuggestSkipMode(skip_tags); //We need to skip tags from now
break;
}
}
function CheckRecursion(&$tag)
{
if (parent::CheckRecursion($tag)) { //if endtag matches (SkipMode would be restored then)
//Creating template from buffer
//if (defined('EXPERIMENTAL_PRE_PARSE') && isset($this->Application->PreParsedBlocks[$this->BlockName])) return true;
$template = new Template();
$template->SetBody($this->Parser->GetBuffer());
//Adding template to application' cache
$this->Application->TemplatesCache->SetTemplate($this->BlockName, $template, $this->Parser->TemplateName);
if (defined('EXPERIMENTAL_PRE_PARSE')) {
$code = $this->Parser->GetCode();
/*if ($this->Parser->UsedProcessors) {
array_unshift($code, '$application->CheckProcessors(array("'.implode('", "', $this->Parser->UsedProcessors).'"));');
}
$this->Parser->UsedProcessors = null;*/
array_unshift($code, '$o = \'\';');
array_unshift($code, '$application->Parser->SetParams($params, false);');
array_unshift($code, '$application =& kApplication::Instance();');
array_unshift($code, 'extract($params);');
$defaults = '$defaults = Array(';
foreach ($this->NP as $name => $val) {
if ($name == 'name') continue;
$defaults .= '"'.$name.'" => "'.str_replace('"', '\"', $val).'",';
}
$defaults .= ');';
array_unshift($code, '$params = array_merge_recursive2($defaults, $params);');
array_unshift($code, $defaults);
$code[] = 'return $o;';
global $debugger;
$dbg_functions = $this->Application->isDebugMode() && constOn('DBG_PRINT_PREPARSED');
$f_body = '';
//echo "<pre>";
$l = 0;
if ($dbg_functions) echo "<b>function ".$this->BlockName." {</b><br>";
foreach ($code as $line) {
$l++;
if ($dbg_functions) {
echo $l.' '.$debugger->highlightString(trim($line)."\n", true);
}
$f_body .= "\t\t".rtrim($line, "\n")."\n";
}
if ($dbg_functions) echo "<b>} // function ".$this->BlockName." end</b><br><br>";
//echo "</pre>";
//caching func body
$this->Application->PreParsedCache[$this->BlockName] = $f_body;
$compile_body = preg_replace('/\/\*COMPILE-ONLY\*\/.*/m', '', $f_body);
$func = create_function('$params', $compile_body);
$this->Application->PreParsedBlocks[$this->BlockName] = $func;
$this->Parser->Args = null;
$this->Parser->ResetCode();
$real_name = $this->Parser->AppendCompiledFunction($this->BlockName, $f_body);
if ($this->Tag == 'RenderElement') {
- $RenderTag =& new Tag($this->TagData.' name="'.$this->BlockName.'"', $this->Parser);
+ $RenderTag = new Tag($this->TagData.' name="'.$this->BlockName.'"', $this->Parser);
// $this->Parser->AppendCompiledCode($RenderTag->GetCode());
// for compilation run
$RenderTag->Process();
}
}
return true;
}
else {
// append the tag itself to the block - while in block, we check every tag to be 'blockend'
// if it is not - we need to append the tag to the buffer, which we'll parse later in 'parse_block'
//if ($tag->Tag != 'block') {
if (defined('EXPERIMENTAL_PRE_PARSE') && isset($this->Application->PreParsedBlocks[$this->BlockName])) {
return;
}
if (defined('EXPERIMENTAL_PRE_PARSE')) {
// $this->Parser->AppendCode($tag->GetCode());
}
else {
$this->Parser->AppendOutput($tag->GetFullTag());
}
//}
return false;
}
}
}
class CaptureTag extends ConstructTag {
var $VarName = null;
var $Mode = CM_LATE_PARSE;
function Process()
{
switch ($this->Tag) {
case 'Capture':
$this->Parser->Recurve($this); //Saving current tag in parser recursion array
$this->Parser->SetBuffer('');
$this->VarName = $this->NP['to_var']; //Stroing BlockName
$this->StoreSkipMode();
if (isset($this->NP['mode']) && $this->NP['mode'] == 'parse_now') {
$this->Mode = CM_PARSE;
}
$this->SuggestSkipMode(skip_tags);
break;
}
}
function RunCapture($f, $func, $cur_lambda)
{
$code = array();
$code[] = '/*COMPILE-ONLY*/ '.$f[2];
$code[] = '/*LAMBDA-ONLY*/ $application->PreParsedBlocks[\'capture_'.$this->VarName.'\'] = $application->PreParsedBlocks[\'capture_'.$this->VarName.$cur_lambda.'\'];';
$code[] = '$__f = $application->PreParsedBlocks[\'capture_'.$this->VarName.'\'];';
$code[] = '$application->Parser->SetParam(\''.$this->VarName.'\', $__f(array())'.');';
$code[] = '$'.$this->VarName.' = $application->Parser->GetParam(\''.$this->VarName.'\');';
$code[] = '$params[\''.$this->VarName.'\'] = $'.$this->VarName.';';
if ($this->Parser->RecursionIndex > 1) {
$this->Parser->AppendCode($code, -1);
}
else {
$this->Application->Parser->SetParam($this->VarName, $func(array()));
$this->Parser->AppendCompiledCode($code);
}
}
function CheckRecursion(&$tag)
{
if (parent::CheckRecursion($tag)) { //if endtag matches (SkipMode would be restored then)
$f_code = $this->Parser->GetCode();
array_unshift($f_code, '$o = \'\';');
array_unshift($f_code, '$application =& kApplication::Instance();');
$f_code[] = 'return $o;';
$f = $this->Parser->PrepareCompiledFunction('capture_'.$this->VarName, $f_code, false);
$f_code = trim(join("\n\t", $f_code));
$func = create_function('$params', $f_code);
$this->Application->PreParsedBlocks['capture_'.$this->VarName] = $func;
$cur_lambda = $this->Application->LambdaElements++;
$this->Application->PreParsedBlocks['capture_'.$this->VarName.$cur_lambda] = $func;
$this->Parser->AppendCompiledCode($f[1]);
if ($this->Mode == CM_PARSE) {
$this->RunCapture($f, $func, $cur_lambda);
}
elseif ($this->Mode == CM_LATE_PARSE) {
$code = array();
$code[] = '/*COMPILE-ONLY*/ '.$f[2];
$code[] = '/*LAMBDA-ONLY*/ $application->PreParsedBlocks[\'capture_'.$this->VarName.'\'] = $application->PreParsedBlocks[\'capture_'.$this->VarName.$cur_lambda.'\'];';
$code[] = '$application->LateParsed[\''.$this->VarName.'\'] = '.$cur_lambda.';';
if ($this->Parser->RecursionIndex > 1) {
$this->Parser->AppendCode($code, -1);
}
else {
$this->Parser->AppendCompiledCode($code);
}
$this->Application->LateParsed[$this->VarName] = $cur_lambda;
}
$this->Parser->ResetCode();
return true;
}
return ($tag->Tag == $this->StopTag); //Tag matches StopTag we are waiting for to close current recursion
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/parser/construct_tags.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.14
\ No newline at end of property
+1.14.2.1
\ No newline at end of property
Index: branches/RC/core/kernel/parser/template_parser.php
===================================================================
--- branches/RC/core/kernel/parser/template_parser.php (revision 9285)
+++ branches/RC/core/kernel/parser/template_parser.php (revision 9286)
@@ -1,744 +1,744 @@
<?php
k4_include_once(KERNEL_PATH.'/parser/tags.php');
k4_include_once(KERNEL_PATH.'/parser/construct_tags.php');
class TemplateParser extends kBase {
var $Template;
var $Output = '';
var $Position = 0;
var $LastPosition = 0;
var $Ses;
var $Recursion = Array();
var $RecursionIndex = 0;
var $SkipMode = 0;
var $Params = Array();
var $Pattern = Array();
var $ForSort = Array();
var $Values = Array();
var $Buffers = Array();
var $Args;
var $ParamsRecursionIndex = 0;
var $ParamsStack = Array();
var $CompiledBuffer;
var $DataExists = false;
var $FromPreParseCache = false;
function TemplateParser()
{
parent::kBase();
$this->Ses =& $this->Application->recallObject('Session');
}
function AddParam($pattern, $value, $dont_sort=0)
{
$this->ForSort[] = Array($pattern, $value);
if (!$dont_sort) //used when mass-adding params, to escape sorting after every new param
$this->SortParams(); //but do sort by default!
}
//We need to sort params by its name length desc, so that params starting with same word get parsed correctly
function SortParams()
{
uasort($this->ForSort, array ("TemplateParser", "CmpParams"));
// commented out by Kostja, otherwise when rednerElement is done into var (result_to_var) the other params are reset
// $this->Pattern = Array();
// $this->Values = Array();
foreach($this->ForSort as $pair)
{
$this->Pattern[] = $pair[0];
$this->Values[] = $pair[1];
}
}
function CmpParams($a, $b)
{
$a_len = strlen($a[0]);
$b_len = strlen($b[0]);
if ($a_len == $b_len) return 0;
return $a_len > $b_len ? -1 : 1;
}
function SetParams($params, $for_parsing=true)
{
if (!is_array($params)) $params = Array();
$this->ForSort = array();
$this->Params = $params;
$this->ParamsStack[$this->ParamsRecursionIndex] = $params;
if (!$for_parsing) return ;
foreach ($params as $key => $val) {
$this->AddParam('/[{]{0,1}\$'.$key.'[}]{0,1}/i', $val, 1); //Do not sort every time
}
$this->SortParams(); //Sort once after adding is done
}
/**
* Returns parser parameter value at specified deep level
*
* @param string $name
* @param int $deep_level if greather then 0 then use from ParamsStack
* @return mixed
*/
function GetParam($name, $deep_level = 0)
{
if ($deep_level > 0) {
return isset($this->ParamsStack[$deep_level][$name]) ? $this->ParamsStack[$deep_level][$name] : false;
}
return isset($this->Params[$name]) ? $this->Params[$name] : false;
}
/**
* Set's template parser parameter, that could be retrieved from template
*
* @param string $name
* @param mixed $value
*/
function SetParam($name, $value)
{
$this->Params[strtolower($name)] = $value;
$this->AddParam('/[{]{0,1}\$'.$name.'[}]{0,1}/i', $value, $this->FromPreParseCache);
$this->ParamsStack[$this->ParamsRecursionIndex][$name] = $value;
}
function SetBuffer($body)
{
$this->Buffers[$this->RecursionIndex] = $body;
}
function GetBuffer()
{
return $this->Buffers[$this->RecursionIndex];
}
function GetCode()
{
return $this->Code[$this->RecursionIndex];
}
function AppendBuffer($append)
{
$this->Buffers[$this->RecursionIndex] .= $append;
$this->AppendCode( $this->ConvertToCode($append) );
}
function AppendOutput($append, $append_code=false)
{
if ($this->SkipMode == parse) {
$this->Output .= $append; //append to Ouput only if we are parsing
if ($append_code) $this->AppendCompiledHTML($append);
}
elseif ($this->SkipMode == skip) {
if ($append_code) $this->AppendCompiledHTML($append);
}
elseif ($this->SkipMode == skip_tags) {
$this->AppendBuffer($append); //append to buffer if we are skipping tags
}
}
function ConvertToCode($data)
{
$data = str_replace("\\", "\\\\", $data); // escape any "\"
$data = str_replace("'", "\'", $data); // escape "'"
$code = '$o .= \''. $data .'\';';
$code = explode("\n", $code);
return $code;
}
function AppendCode($code, $level_offset=0)
{
if ($this->RecursionIndex+$level_offset <= 0 ) $level_offset = 0;
if (defined('EXPERIMENTAL_PRE_PARSE')) {
if (!isset($this->Code[$this->RecursionIndex+$level_offset])) {
$this->Code[$this->RecursionIndex+$level_offset] = Array();
}
if (is_array($code)) {
foreach ($code as $line) {
$this->Code[$this->RecursionIndex+$level_offset][] = rtrim($line, "\n")."\n";
}
}
else {
$this->Code[$this->RecursionIndex+$level_offset][] .= rtrim($code, "\n")."\n";
}
}
}
function PrepareCompiledFunction($f_name, $f_body, $add_reference=true)
{
$real_name = 'f_'.abs(crc32($this->TemplateName)).'_'.$f_name;
$real_code = '';
if (defined('EXPERIMENTAL_PRE_PARSE')) {
// if such function already compiled
if ( isset($this->Application->CompiledFunctions[$f_name]) ||
function_exists($real_name)
)
{
if (!isset($this->Application->CompiledFunctions[$f_name])) {
$real_name = $real_name.'_';
}
else {
$real_name = $this->Application->CompiledFunctions[$f_name].'_';
}
}
if (is_array($f_body)) {
$real_body = '';
foreach ($f_body as $line) {
if (preg_match('/^\/\*LAMBDA-ONLY\*\//', $line)) continue;
$real_body .= "\t\t".rtrim($line, "\n")."\n";
};
$f_body = $real_body;
}
else {
$f_body = preg_replace('/\/\*LAMBDA-ONLY\*\/.*/m', '', $f_body);
}
$ref = "\t".'$application->PreParsedBlocks[\''.$f_name.'\'] = \''.$real_name.'\';'."\n";
if ($add_reference) $real_code .= $ref;
$real_code .= 'if (!function_exists(\''.$real_name.'\')) {'."\n";
$real_code .= "\t".'function '.$real_name.'($params)'."\n\t{\n";
$real_code .= $f_body;
$real_code .= "\t}\n\n";
$real_code .= '}'."\n";
/*if (defined('DEBUG_MODE') && DEBUG_MODE && defined('DBG_PRE_PARSE') && DBG_PRE_PARSE) {
// this shows newly compiled functions (blocks)
global $debugger;
$f_body = "\t".'function '.$real_name.'($params)'."\n\t{\n".$f_body."\t}\n\n";
$debugger->appendHTML($debugger->highlightString($f_body));
}*/
$this->Application->CompiledFunctions[$f_name] = $real_name;
return array($real_name, $real_code, $ref);
}
}
function AppendCompiledFunction($f_name, $f_body)
{
$f = $this->PrepareCompiledFunction($f_name, $f_body);
$this->CompiledBuffer .= $f[1];
}
function AppendCompiledCode($code)
{
if (defined('EXPERIMENTAL_PRE_PARSE')) {
if (is_array($code)) {
foreach ($code as $line) {
if (preg_match('/^\/\*LAMBDA-ONLY\*\//', $line)) continue;
$this->CompiledBuffer .= "\t".rtrim($line, "\n")."\n";
}
}
else {
$this->CompiledBuffer .= $code;
}
$this->CompiledBuffer .= "\t".'echo $o;'."\n\t".'$o = \'\';'."\n";
}
}
function AppendCompiledHTML($append)
{
if (defined('EXPERIMENTAL_PRE_PARSE')) {
$this->CompiledBuffer .= '?'.'>'."\n";
$this->CompiledBuffer .= rtrim($append, "\t");
$this->CompiledBuffer .= '<'.'?php'."\n";
}
}
function ResetCode()
{
$this->Code[$this->RecursionIndex] = Array();
}
function FindTag2()
{
$openings = Array('<%' => '%>', '<inp2:' => Array('>', '/>'), '</inp2:' => '>', '</inp2>' => '', '<!--' => '-->');
$tag_open_pos = false;
foreach ($openings as $an_opening => $closings) {
$pos = strpos($this->Template, $an_opening, $this->Position);
if ($pos !== false && ($tag_open_pos === false || (int) $pos <= (int) $tag_open_pos)) {
$tag_open_pos = $pos;
$open_len = strlen($an_opening);
$opening_tag = $an_opening;
$tag_closings = $closings;
}
}
if ($tag_open_pos === false) { //If no tags left - adding all other data
$this->AppendOutput(substr($this->Template, $this->Position), true);
return false;
}
//Adding all data before tag open
$this->AppendOutput(substr($this->Template, $this->Position, $tag_open_pos - $this->Position), true);
if (is_array($tag_closings)) {
$tag_close_pos = false;
foreach ($tag_closings as $a_closing) {
$pos = strpos($this->Template, $a_closing, $tag_open_pos);
if ($pos !== false && ($tag_close_pos === false || (int) $pos <= (int) $tag_close_pos)) {
$tag_close_pos = $pos;
$closing_tag = $a_closing;
}
}
}
elseif ($opening_tag == '</inp2>') {
$closing_tag = '';
$tag_close_pos = $tag_open_pos + $open_len;
}
else {
$closing_tag = $tag_closings;
$tag_close_pos = strpos($this->Template, $closing_tag, $tag_open_pos);
}
$close_len = strlen($closing_tag);
// Cutting trailing line-breaks after tags (same way PHP does it)
if (substr($this->Template, $tag_close_pos+$close_len, 2) == "\r\n") {
$this->Template = substr_replace($this->Template, '', $tag_close_pos, 2);
}
elseif (substr($this->Template, $tag_close_pos+$close_len, 1) == "\n") {
$this->Template = substr_replace($this->Template, '', $tag_close_pos, 1);
}
//Cutting out the tag itself
$tag = substr($this->Template, $tag_open_pos + $open_len, $tag_close_pos - $tag_open_pos - $open_len);
if ($opening_tag == '<inp2:') {
//getting prefix_tag upto first space, tab or line break into regs[1]
preg_match("/^([^ \t\n]*)(.*)/", $tag, $regs);
$tag_part = $regs[1];
if (strpos($tag_part, '_') !== false) {
list($prefix, $the_tag) = explode('_', $tag, 2);
/*preg_match('/(.*)_(.*)/', $tag_part, $rets);
$prefix = $rets[1];
$the_tag = $rets[2].$regs[2];*/
$tag = $prefix.':'.$the_tag;
}
else {
$the_tag = $tag;
$tag = ':'.$tag;
}
}
if ($opening_tag == '</inp2>') { //empty closing means old style in-portal if <inp2:tag>....</inp2>
$tag = 'm:endif';
}
if ($opening_tag == '</inp2:') {
preg_match("/^([^ \t\n]*)(.*)/", $tag, $regs);
$tag_part = $regs[1];
if (strpos($tag_part, '_') !== false) {
list($prefix, $the_tag) = explode('_', $tag, 2);
$tag = $prefix.':'.$the_tag;
}
$tag .= ' _closing_tag_="1"';
}
// if there is no prefix for the tag
if (strpos($tag, ':') === 0) {
$prefix = getArrayValue($this->Params, 'PrefixSpecial');
$tag = $prefix.$tag.' _auto_prefix_="1"';
}
// temporary - for backward compatability with in-portal style if
$compat_tags = array('m_if', 'm_DefineElement', 'm_Capture', 'm_RenderElement');
if ($opening_tag == '<inp2:' && $closing_tag == '>' && !in_array($tag_part, $compat_tags)) {
if (strpos($the_tag, ' ') !== false) {
list($function, $params) = explode(' ', $the_tag, 2);
}
else {
$function = $the_tag;
$params = '';
}
$tag = 'm:if prefix="'.$prefix.'" function="'.$function.'" '.$params;
}
if ($opening_tag == '<!--') {
if ($this->Application->IsAdmin()) {
$this->AppendOutput('<!-- '.htmlspecialchars($tag). '-->');
}
else {
$this->AppendOutput('<!-- '.$tag. '-->');
$this->AppendCompiledHTML('<!-- '.$tag. '-->');
}
$tag = '__COMMENT__';
}
if ($closing_tag == '>') $tag .= ' _short_closing_="1"';
$this->Position = $tag_close_pos + $close_len;
return $tag;
}
function CurrentLineNumber()
{
return substr_count(substr($this->Template, 0, $this->Position), "\n")+1;
}
function SkipModeName()
{
switch ($this->SkipMode) {
case skip: return 'skip';
case skip_tags: return 'skip_tags';
case parse: return 'parse';
}
}
/**
* Recursive mkdir
*
* @param string $dir
* @param string $base_path base path to directory where folders should be created in
*/
function CheckDir($dir, $base_path = '')
{
if (file_exists($dir)) {
return;
}
else {
// remove $base_path from beggining because it is already created during install
$dir = preg_replace('/^'.preg_quote($base_path.'/', '/').'/', '', $dir, 1);
$segments = explode('/', $dir);
$cur_path = $base_path;
foreach ($segments as $segment) {
// do not add leading / for windows paths (c:\...)
$cur_path .= preg_match('/^[a-zA-Z]{1}:/', $segment) ? $segment : '/'.$segment;
if (!file_exists($cur_path)) {
mkdir($cur_path);
}
}
}
}
function ParseTemplate($name, $pre_parse = 1, $params=array(), $silent=0)
{
$this->FromPreParseCache = false;
if ($this->GetParam('from_inportal')) $pre_parse = 0;
if ($pre_parse) {
$pre_parsed = $this->Application->TemplatesCache->GetPreParsed($name);
if ($pre_parsed === false) {
// template not found -> don't compile
return '';
}
if ($pre_parsed && $pre_parsed['active']) { // active means good (not expired) pre-parsed cache
$this->FromPreParseCache = true;
$this->SetParams($params, 0); // 0 to disable params sorting and regexp generation - not needed when processing pre-parsed
ob_start();
if ($pre_parsed['mode'] == 'file') {
$this->TemplateName = str_replace(FULL_PATH, '', realpath($pre_parsed['fname']));
include($pre_parsed['fname']);
}
else {
eval('?'.'>'.$pre_parsed['content']);
}
$output = ob_get_contents();
ob_end_clean();
}
else {
$this->SetParams($params);
$this->CompiledBuffer .= '<'.'?php'."\n";
$this->CompiledBuffer .= 'global $application;'."\n";
$this->CompiledBuffer .= '$params =& $application->Parser->Params;'."\n";
$this->CompiledBuffer .= 'extract($params);'."\n";
$this->CompiledBuffer .= '$o = \'\';'."\n";
$body = $this->Application->TemplatesCache->GetTemplateBody($name, $silent);
$this->TemplateName = $name;
$output = $this->NewParse($body, $name);
$this->CompiledBuffer .= '?'.'>'."\n";
if (defined('SAFE_MODE') && SAFE_MODE) {
if (!isset($conn)) $conn =& $this->Application->GetADODBConnection();
$conn->Query('REPLACE INTO '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ('.$conn->qstr($pre_parsed['fname']).','.$conn->qstr($this->CompiledBuffer).','.adodb_mktime().')');
}
else {
$compiled = fopen($pre_parsed['fname'], 'w');
fwrite($compiled, $this->CompiledBuffer);
fclose($compiled);
}
}
if ( !$this->GetParam('from_inportal') && strpos($output, '<inp:') !== false) {
$inp1_parser =& $this->Application->recallObject('Inp1Parser');
// $name = $this->Application->TemplatesCache->GetTemplateFileName($name) . '-block:' . $name; // may be is needed (by Alex)
$output = $inp1_parser->Parse($name, $output);
}
return $output;
}
// pre-parse is OFF
$this->SetParams($params);
return $this->NewParse($this->Application->TemplatesCache->GetTemplateBody($name), $name, $pre_parse);
}
function NewParse($template, $name='unknown', $pre_parse = 1)
{
$this->Template = $template;
$this->TemplateName = $name;
$this->Position = 0;
$this->Output = '';
$this->TagHolder = new MyTagHolder();
$has_inp_tags = false;
if (!getArrayValue($this->Params, 'PrefixSpecial')) {
$this->Params['PrefixSpecial'] = '$PrefixSpecial';
}
//While we have more tags
while ($tag_data = $this->FindTag2())
{
if ($tag_data == '__COMMENT__') continue;
//Create tag object from passed tag data
if( $this->Application->isDebugMode() && constOn('DBG_SHOW_TAGS') )
{
global $debugger;
$debugger->appendHTML('mode: '.$this->SkipModeName().' tag '.$debugger->highlightString($tag_data).' in '.$debugger->getFileLink($debugger->getLocalFile(FULL_PATH.THEMES_PATH.'/'.$this->TemplateName).'.tpl', $this->CurrentLineNumber(), '', true));
}
$tag =& $this->TagHolder->GetTag($tag_data, $this);
if (!$this->CheckRecursion($tag)) //we do NOT process closing tags
{
$tag->Process();
}
}
return $this->Output;
}
function Parse($template, $name='unknown', $pre_parse = 1)
{
$this->Template = $template;
$this->TemplateName = $name;
$this->Position = 0;
$this->Output = '';
$this->TagHolder = new MyTagHolder();
$has_inp_tags = false;
if ($this->GetParam('from_inportal')) $pre_parse = 0;
if (defined('EXPERIMENTAL_PRE_PARSE') && $pre_parse) {
$fname = $this->Application->TemplatesCache->GetRealFilename($this->TemplateName).'.php';
$fname = str_replace(FULL_PATH, FULL_PATH.'/kernel/cache', $fname);
if (!defined('SAFE_MODE') || !SAFE_MODE) {
$this->CheckDir(dirname($fname), FULL_PATH.'/kernel/cache');
}
$tname = $this->Application->TemplatesCache->GetRealFilename($this->TemplateName).'.tpl';
$output = '';
$is_cached = false;
ob_start();
if (defined('SAFE_MODE') && SAFE_MODE) {
$conn =& $this->Application->GetADODBConnection();
$cached = $conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'Cache WHERE VarName = "'.$fname.'"');
if ($cached !== false && $cached['Cached'] > filemtime($tname)) {
eval('?'.'>'.$cached['Data']);
$is_cached = true;
}
}
else {
if (file_exists($fname) && file_exists($tname) && filemtime($fname) > filemtime($tname)) {
include($fname);
$is_cached = true;
}
}
$output = ob_get_contents();
ob_end_clean();
if ( $is_cached && !$this->GetParam('from_inportal') ) {
if ( strpos($output, '<inp:') !== false) {
$inp1_parser =& $this->Application->recallObject('Inp1Parser');
$output = $inp1_parser->Parse($name, $output);
}
return $output;
}
$this->CompiledBuffer .= '<'.'?php'."\n";
$this->CompiledBuffer .= 'global $application;'."\n";
$this->CompiledBuffer .= '$params =& $application->Parser->Params;'."\n";
$this->CompiledBuffer .= 'extract($params);'."\n";
$this->CompiledBuffer .= '$o = \'\';'."\n";
}
if (!getArrayValue($this->Params, 'PrefixSpecial')) {
$this->Params['PrefixSpecial'] = '$PrefixSpecial';
}
//While we have more tags
while ($tag_data = $this->FindTag2())
{
if ($tag_data == '__COMMENT__') continue;
//Create tag object from passed tag data
if( $this->Application->isDebugMode() && constOn('DBG_SHOW_TAGS') )
{
global $debugger;
$debugger->appendHTML('mode: '.$this->SkipModeName().' tag '.$debugger->highlightString($tag_data).' in '.$debugger->getFileLink($debugger->getLocalFile(FULL_PATH.THEMES_PATH.'/'.$this->TemplateName).'.tpl', $this->CurrentLineNumber(), '', true));
}
-// $tag =& new MyTag($tag_data, $this);
+// $tag = new MyTag($tag_data, $this);
$tag =& $this->TagHolder->GetTag($tag_data, $this);
if (!$this->CheckRecursion($tag)) //we do NOT process closing tags
{
$tag->Process();
}
}
if ( !$this->GetParam('from_inportal') ) {
if ( strpos($this->Output, '<inp:') !== false) {
$inp1_parser =& $this->Application->recallObject('Inp1Parser');
$this->Output = $inp1_parser->Parse($name, $this->Output);
$has_inp_tags = true;
}
}
if (defined('EXPERIMENTAL_PRE_PARSE') && $pre_parse && !$has_inp_tags) {
// $this->CompiledBuffer .= 'echo $o;'."\n";
$this->CompiledBuffer .= '?'.'>'."\n";
if (defined('SAFE_MODE') && SAFE_MODE) {
if (!isset($conn)) $conn =& $this->Application->GetADODBConnection();
$conn->Query('REPLACE INTO '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ('.$conn->qstr($fname).','.$conn->qstr($this->CompiledBuffer).','.adodb_mktime().')');
}
else {
$compiled = fopen($fname, 'w');
fwrite($compiled, $this->CompiledBuffer);
fclose($compiled);
}
}
return $this->Output;
}
function ParseBlock($params, $force_pass_params=0, $as_template=false)
{
if( $this->Application->isDebugMode() && constOn('DBG_SHOW_TAGS') )
{
global $debugger;
$debugger->appendHTML('ParseBlock '.$params['name'].' pass_params is '.$params['pass_params'].' force is '.$force_pass_params.' in '.$debugger->getFileLink($debugger->getLocalFile(FULL_PATH.THEMES_PATH.'/'.$this->TemplateName).'.tpl', $this->CurrentLineNumber(), '', true));
}
/*if ( $this->Application->isDebugMode() && constOn('DBG_PRE_PARSE') ) {
global $debugger;
$debugger->CurrentPreParsedBlock = $params['name'];
}*/
if (defined('EXPERIMENTAL_PRE_PARSE')) {
$this->MainParser = false;
if (isset($this->Application->PreParsedBlocks[$params['name']]) ) {
if ($this->ParamsRecursionIndex == 0) {
$this->ParamsStack[$this->ParamsRecursionIndex] = $this->Params;
}
if (isset($params['pass_params']) || $force_pass_params) {
$pass_params = array_merge($this->ParamsStack[$this->ParamsRecursionIndex], $params);
}
else {
$pass_params = $params;
}
$this->ParamsStack[++$this->ParamsRecursionIndex] = $pass_params;
$this->Params = $pass_params;
$f = $this->Application->PreParsedBlocks[$params['name']];
// $this->ParamsRecursionIndex--;
//$this->SetParams($params);
if( !isset($pass_params['PrefixSpecial']) && isset($pass_params['prefix']) ) $pass_params['PrefixSpecial'] = $pass_params['prefix'];
$ret = $f($pass_params);
if (isset($params['return_params']) && $params['return_params']) {
$this->ParamsStack[$this->ParamsRecursionIndex - 1] = array_merge($this->ParamsStack[$this->ParamsRecursionIndex - 1], $this->ParamsStack[$this->ParamsRecursionIndex]);
}
unset($this->ParamsStack[$this->ParamsRecursionIndex--]);
$this->Params = $this->ParamsStack[$this->ParamsRecursionIndex];
$this->MainParser = true;
return $ret;
}
}
$BlockParser =& $this->Application->makeClass('TemplateParser');
if (isset($params['pass_params']) || $force_pass_params) {
$BlockParser->SetParams(array_merge($this->Params, $params));
}
else
$BlockParser->SetParams($params);
$this->Application->Parser =& $BlockParser;
if (!isset($params['name'])) {
trigger_error('<b>***Error: Block name not passed to ParseBlock</b>', E_USER_ERROR);
}
$templates_cache =& $this->Application->recallObject('TemplatesCache');
$template_name = $as_template ? $params['name'] : $templates_cache->GetTemplateFileName($params['name']) . '-block:'.$params['name'];
$silent = getArrayValue($params, 'from_inportal') && !defined('DBG_TEMPLATE_FAILURE');
$o = $BlockParser->Parse(
$templates_cache->GetTemplateBody($params['name'], $silent),
$template_name
);
if (getArrayValue($params, 'BlockNoData') && !$BlockParser->DataExists) {
$template_name = $as_template ? $params['BlockNoData'] : $templates_cache->GetTemplateFileName($params['BlockNoData']) . '-block:'.$params['BlockNoData'];
$o = $BlockParser->Parse(
$templates_cache->GetTemplateBody($params['BlockNoData'], $silent),
$template_name
);
}
$this->Application->Parser =& $this;
$this->Application->Parser->DataExists = $this->Application->Parser->DataExists || $BlockParser->DataExists;
return $o;
}
function Recurve(&$tag)
{
$this->Recursion[++$this->RecursionIndex] =& $tag;
}
function CheckRecursion(&$tag)
{
if ($this->RecursionIndex > 0) { //If we are inside the recursion
if ($this->Recursion[$this->RecursionIndex]->CheckRecursion($tag)) { //If we can close this recursion
unset($this->Recursion[$this->RecursionIndex--]); //unsetting current recursion level and decreasing it at the same time
return true; //we should inform not to process closing tag
}
}
return false;
}
function SetSkipMode($mode)
{
$this->SkipMode = $mode;
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/parser/template_parser.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.31
\ No newline at end of property
+1.31.2.1
\ No newline at end of property
Index: branches/RC/core/units/categories/cache_updater.php
===================================================================
--- branches/RC/core/units/categories/cache_updater.php (revision 9285)
+++ branches/RC/core/units/categories/cache_updater.php (revision 9286)
@@ -1,489 +1,489 @@
<?php
class clsRecursionStack {
var $Stack;
function clsRecursionStack()
{
$this->Stack = Array();
}
function Push($values)
{
array_push($this->Stack, $values);
}
function Pop()
{
if ($this->Count() > 0) {
return array_pop($this->Stack);
}
else {
return false;
}
}
function Get()
{
if ($this->Count() > 0) {
// return end($this->Stack);
return $this->Stack[count($this->Stack)-1];
}
else {
return false;
}
}
function Update($values)
{
$this->Stack[count($this->Stack)-1] = $values;
}
function Count()
{
return count($this->Stack);
}
}
class clsCachedPermissions {
var $Allow = Array();
var $Deny = Array();
var $CatId;
/**
* Table name used for inserting permissions
*
* @var string
*/
var $table = '';
function clsCachedPermissions($CatId, $table_name)
{
$this->CatId = $CatId;
$this->table = $table_name;
}
function SetCatId($CatId)
{
$this->CatId = $CatId;
}
function CheckPermArray($Perm)
{
if (!isset($this->Allow[$Perm])) {
$this->Allow[$Perm] = array();
$this->Deny[$Perm] = array();
}
}
function AddAllow($Perm, $GroupId)
{
$this->CheckPermArray($Perm);
if (!in_array($GroupId, $this->Allow[$Perm])) {
array_push($this->Allow[$Perm], $GroupId);
$this->RemoveDeny($Perm, $GroupId);
}
}
function AddDeny($Perm, $GroupId)
{
$this->CheckPermArray($Perm);
if (!in_array($GroupId, $this->Deny[$Perm])) {
array_push($this->Deny[$Perm], $GroupId);
$this->RemoveAllow($Perm, $GroupId);
}
}
function RemoveDeny($Perm, $GroupId)
{
if (in_array($GroupId, $this->Deny[$Perm])) {
array_splice($this->Deny[$Perm], array_search($GroupId, $this->Deny[$Perm]), 1);
}
}
function RemoveAllow($Perm, $GroupId)
{
if (in_array($GroupId, $this->Allow[$Perm])) {
array_splice($this->Allow[$Perm], array_search($GroupId, $this->Allow[$Perm]), 1);
}
}
function GetInsertSQL()
{
$values = array();
foreach ($this->Allow as $perm => $groups) {
if (count($groups) > 0) {
$values[] = '(' .$this->CatId. ', ' .$perm. ', "' .join(',', $groups). '")';
}
}
if (!$values) return '';
$sql = 'INSERT INTO '.$this->table.' (CategoryId, PermId, ACL) VALUES '.join(',', $values);
return $sql;
}
}
class kPermCacheUpdater extends kHelper {
/**
* Holds Stack
*
* @var clsRecursionStack
*/
var $Stack;
/**
* Rebuild process iteration
*
* @var int
*/
var $iteration;
/**
* Categories count to process
*
* @var unknown_type
*/
var $totalCats = 0;
/**
* Processed categories count
*
* @var int
*/
var $doneCats = 0;
/**
* Temporary table name used for storing cache building progress
*
* @var string
*/
var $progressTable = '';
/**
* Temporary table name used for storing not fully built permissions cache
* 1. preserves previous cache while new cache is building
* 2. when rebuild process fails allows previous cache (in live table) is used
*
* @var string
*/
var $permCacheTable = '';
var $primaryLanguageId = 0;
var $languageCount = 0;
var $root_prefixes = Array();
/**
* Update cache only for requested categories and it's parent categories
*
* @var bool
*/
var $StrictPath = false;
function Init($prefix, $special, $event_params = null)
{
parent::Init($prefix, $special, $event_params);
$continuing = isset($event_params['continue']) ? $event_params['continue'] : 1;
$this->StrictPath = isset($event_params['strict_path']) ? $event_params['strict_path'] : false;
if ($this->StrictPath && !is_array($this->StrictPath)) {
$this->StrictPath = explode('|', trim($this->StrictPath, '|'));
}
// cache widely used values to speed up process: begin
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
$this->languageCount = $ml_helper->getLanguageCount();
$this->primaryLanguageId = $this->Application->GetDefaultLanguageId();
// cache widely used values to speed up process: end
foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
$this->root_prefixes[ $module_info['RootCat'] ] = $module_info['Var'];
}
$this->iteration = 0;
$this->progressTable = $this->Application->GetTempName('permCacheUpdate');
$this->permCacheTable = $this->Application->GetTempName(TABLE_PREFIX.'PermCache');
if ($continuing == 1) {
$this->InitUpdater();
}
elseif ($continuing == 2) {
$this->getData();
}
}
function InitUpdater()
{
- $this->Stack =& new clsRecursionStack();
+ $this->Stack = new clsRecursionStack();
$this->initData();
}
function getDonePercent()
{
if (!$this->totalCats) {
return 0;
}
return min(100, intval( floor( $this->doneCats / $this->totalCats * 100 ) ));
}
function getData()
{
$tmp = $this->Conn->GetOne('SELECT data FROM '.$this->progressTable);
if ($tmp) $tmp = unserialize($tmp);
$this->totalCats = isset($tmp['totalCats']) ? $tmp['totalCats'] : 0;
$this->doneCats = isset($tmp['doneCats']) ? $tmp['doneCats'] : 0;
if (isset($tmp['stack'])) {
$this->Stack = $tmp['stack'];
}
else {
- $this->Stack =& new clsRecursionStack();
+ $this->Stack = new clsRecursionStack();
}
}
function setData()
{
$tmp = Array (
'totalCats' => $this->totalCats,
'doneCats' => $this->doneCats,
'stack' => $this->Stack,
);
$this->Conn->Query('DELETE FROM '.$this->progressTable);
$fields_hash = Array('data' => serialize($tmp));
$this->Conn->doInsert($fields_hash, $this->progressTable);
}
function initData()
{
$this->clearData(); // drop table before starting anyway
// 1. create table for rebuilding permissions cache
$this->Conn->Query('CREATE TABLE '.$this->permCacheTable.' LIKE '.TABLE_PREFIX.'PermCache');
if ($this->StrictPath) {
// when using strict path leave all other cache intact
$sql = 'INSERT INTO '.$this->permCacheTable.'
SELECT *
FROM '.TABLE_PREFIX.'PermCache';
$this->Conn->Query($sql);
// delete only cache related to categories in path
$sql = 'DELETE FROM '.$this->permCacheTable.'
WHERE CategoryId IN ('.implode(',', $this->StrictPath).')';
$this->Conn->Query($sql);
}
$this->Conn->Query('CREATE TABLE '.$this->progressTable.'(data LONGTEXT)');
$this->totalCats = (int)$this->Conn->GetOne('SELECT COUNT(*) FROM '.TABLE_PREFIX.'Category');
$this->doneCats = 0;
}
function clearData()
{
$this->Conn->Query('DROP TABLE IF EXISTS '.$this->progressTable);
$this->Conn->Query('DROP TABLE IF EXISTS '.$this->permCacheTable);
$this->Conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = \'ForcePermCacheUpdate\'');
$this->Conn->Query('UPDATE '.TABLE_PREFIX.'ConfigurationValues SET VariableValue = VariableValue+1 WHERE VariableName = \'CategoriesRebuildSerial\'');
}
function SaveData()
{
// copy data from temp permission cache table back to live
$this->Conn->Query('TRUNCATE '.TABLE_PREFIX.'PermCache');
$sql = 'INSERT INTO '.TABLE_PREFIX.'PermCache
SELECT *
FROM '.$this->permCacheTable;
$this->Conn->Query($sql);
$this->clearData();
}
function DoTheJob()
{
$data = $this->Stack->Get();
if ($data === false) { //If Stack is empty
$data['current_id'] = 0;
$data['titles'] = Array();
$data['parent_path'] = Array();
$data['named_path'] = Array();
$data['category_template'] = '';
$data['item_template'] = '';
$data['children_count'] = 0;
$data['system'] = 0;
$data['left'] = 0;
$data['right'] = 2;
$data['debug_title'] = 'ROOT';
$this->Stack->Push($data);
}
if (!isset($data['queried'])) {
$this->QueryTitle($data);
$this->QueryChildren($data);
$data['children_count'] = count($data['children']);
$this->QueryPermissions($data);
$data['queried'] = 1;
$data['right'] = $data['left']+1;
if ($sql = $data['perms']->GetInsertSQL()) {
$this->Conn->Query($sql);
// $this->doneCats++; // moved to the place where it pops out of the stack by Kostja
}
$this->iteration++;
}
// start with first child if we haven't started yet
if (!isset($data['current_child'])) $data['current_child'] = 0;
// if we have more children on CURRENT LEVEL
if (isset($data['children'][$data['current_child']])) {
if ($this->StrictPath) {
while ( isset($data['children'][ $data['current_child'] ]) && !in_array($data['children'][ $data['current_child'] ], $this->StrictPath) ) {
$data['current_child']++;
continue;
}
if (!isset($data['children'][ $data['current_child'] ])) return false; //error
}
$next_data = Array();
$next_data['titles'] = $data['titles'];
$next_data['parent_path'] = $data['parent_path'];
$next_data['named_path'] = $data['named_path'];
$next_data['category_template'] = $data['category_template'];
$next_data['item_template'] = $data['item_template'];
$next_data['current_id'] = $data['children'][ $data['current_child'] ]; //next iteration should process child
$next_data['perms'] = $data['perms']; //we should copy our permissions to child - inheritance
$next_data['perms']->SetCatId($next_data['current_id']);
$next_data['left'] = $data['right'];
$data['current_child']++;
$this->Stack->Update($data); //we need to update ourself for the iteration after the next (or further) return to next child
$this->Stack->Push($next_data); //next iteration should process this child
return true;
}
else {
$this->Stack->Update($data);
$prev_data = $this->Stack->Pop(); //remove ourself from stack if we have finished all the childs (or there are none)
$data['right'] = $prev_data['right'];
$this->UpdateCachedPath($data);
// we are getting here if we finished with current level, so check if it's first level - then bail out.
$this->doneCats++; // moved by Kostja from above, seems to fix the prob
$has_more = $this->Stack->Count() > 0;
if ($has_more) {
$next_data = $this->Stack->Get();
$next_data['right'] = $data['right']+1;
$next_data['children_count'] += $data['children_count'];
$this->Stack->Update($next_data);
}
return $has_more;
}
}
function UpdateCachedPath(&$data)
{
$fields_hash = Array (
'ParentPath' => '|'.implode('|', $data['parent_path']).'|',
'NamedParentPath' => $data['system'] ? $data['file_name'] : implode('/', $data['named_path'] ),
'CachedCategoryTemplate' => $data['category_template'],
'CachedDescendantCatsQty' => $data['children_count'],
'TreeLeft' => $data['left'],
'TreeRight' => $data['right'],
);
$i = 1;
while ($i <= $this->languageCount) {
$fields_hash['l'.$i.'_CachedNavbar'] = implode('&|&', $data['titles'][$i]);
$i++;
}
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX.'Category', 'CategoryId = '.$data['current_id']);
}
function QueryTitle(&$data)
{
$category_id = $data['current_id'];
$sql = 'SELECT *
FROM '.TABLE_PREFIX.'Category
WHERE CategoryId = '.$category_id;
$record = $this->Conn->GetRow($sql);
if ($record) {
$i = 1;
while ($i <= $this->languageCount) {
$data['titles'][$i][] = $record['l'.$i.'_Name'] ? $record['l'.$i.'_Name'] : $record['l'.$this->primaryLanguageId.'_Name'];
$i++;
}
$data['debug_title'] = $record['l1_Name'];
$data['parent_path'][] = $category_id;
$data['named_path'][] = preg_replace('/^Content\\//', '', $record['Filename']);
$data['system'] = $record['IsSystem'];
$data['file_name'] = $record['Filename'];
// it is one of the modules root category
$root_prefix = isset($this->root_prefixes[$category_id]) ? $this->root_prefixes[$category_id] : false;
if ($root_prefix) {
$fields_hash = Array();
if (!$record['CategoryTemplate']) {
$record['CategoryTemplate'] = $this->Application->ConfigValue($root_prefix.'_CategoryTemplate');
$fields_hash['CategoryTemplate'] = $record['CategoryTemplate'];
}
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX.'Category', 'CategoryId = '.$category_id);
}
// if explicitly set, then use it; use parent template otherwise
if ($record['CategoryTemplate']) {
$data['category_template'] = $record['CategoryTemplate'];
}
}
}
function QueryChildren(&$data)
{
$sql = 'SELECT CategoryId
FROM '.TABLE_PREFIX.'Category
WHERE ParentId = '.$data['current_id'];
$data['children'] = $this->Conn->GetCol($sql);
}
function QueryPermissions(&$data)
{
// don't search for section "view" permissions here :)
$sql = 'SELECT ipc.PermissionConfigId, ip.GroupId, ip.PermissionValue
FROM '.TABLE_PREFIX.'Permissions AS ip
LEFT JOIN '.TABLE_PREFIX.'PermissionConfig AS ipc ON ipc.PermissionName = ip.Permission
WHERE (CatId = '.$data['current_id'].') AND (Permission LIKE "%.VIEW") AND (ip.Type = 0)';
$records = $this->Conn->Query($sql);
//create permissions array only if we don't have it yet (set by parent)
if (!isset($data['perms'])) {
$data['perms'] = new clsCachedPermissions($data['current_id'], $this->permCacheTable);
}
foreach ($records as $record) {
if ($record['PermissionValue'] == 1) {
$data['perms']->AddAllow($record['PermissionConfigId'], $record['GroupId']);
}
else {
$data['perms']->AddDeny($record['PermissionConfigId'], $record['GroupId']);
}
}
}
/**
* Rebuild all cache in one step
*
*/
function OneStepRun($path='')
{
$this->InitUpdater();
$needs_more = true;
while ($needs_more) {
// until proceeeded in this step category count exceeds category per step limit
$needs_more = $this->DoTheJob();
}
$this->SaveData();
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/categories/cache_updater.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.16
\ No newline at end of property
+1.16.2.1
\ No newline at end of property
Index: branches/RC/core/units/general/xml_helper.php
===================================================================
--- branches/RC/core/units/general/xml_helper.php (revision 9285)
+++ branches/RC/core/units/general/xml_helper.php (revision 9286)
@@ -1,203 +1,203 @@
<?php
class kXMLHelper extends kHelper {
var $RootElement = null;
/**
* Enter description here...
*
* @var kXMLNode
*/
var $CurrentElement = null;
/**
* Parses XML data specified and returns root node
*
* @param string $xml
* @return kXMLNode
*/
function &Parse($xml = null)
{
$this->Clear(); // in case if Parse method is called more then one time
$xml_parser = xml_parser_create();
xml_set_element_handler( $xml_parser, Array(&$this, 'startElement'), Array(&$this, 'endElement') );
xml_set_character_data_handler( $xml_parser, Array(&$this, 'characterData') );
if (!xml_parse($xml_parser, $xml, 1)) {
- $this->RootElement =& new kXMLNode('ERROR', array('code'=>xml_get_error_code($xml_parser),'message'=>xml_error_string(xml_get_error_code($xml_parser))));
+ $this->RootElement = new kXMLNode('ERROR', array('code'=>xml_get_error_code($xml_parser),'message'=>xml_error_string(xml_get_error_code($xml_parser))));
trigger_error(sprintf('XML error: %s at line %d',
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)), E_USER_WARNING);
}
xml_parser_free($xml_parser);
return $this->RootElement;
}
function startElement(&$Parser, &$Elem, $Attrs)
{
$parent =& $this->CurrentElement;
- $this->CurrentElement =& new kXMLNode($Elem, $Attrs);
+ $this->CurrentElement = new kXMLNode($Elem, $Attrs);
if (is_null($this->RootElement)) {
$this->RootElement =& $this->CurrentElement;
}
if (!is_null($parent)) {
$parent->AddChild($this->CurrentElement);
}
}
function characterData($Parser, $Line)
{
$this->CurrentElement->AppendData($Line);
}
function endElement($Parser, $Elem)
{
if ($this->CurrentElement->Parent != null) {
$this->CurrentElement =& $this->CurrentElement->Parent;
}
}
function Clear()
{
$this->RootElement = null;
$this->CurrentElement = null;
}
}
class kXMLNode {
var $Name = null;
var $Attributes = array();
var $Children = array();
var $Data = null;
var $firstChild = null;
var $lastChild = null;
/**
* Parent node
*
* @var kXMLNode
*/
var $Parent = null;
/**
* Node position relative to other nodes of it's parent
*
* @var int
*/
var $Position = 0;
function kXMLNode($name, $attrs = array())
{
$this->Name = $name;
$this->Attributes = $attrs;
}
function SetParent(&$elem)
{
$this->Parent =& $elem;
}
/**
* Adds new child to current node
*
* @param kXMLNode $a_child
*/
function AddChild(&$a_child)
{
$node_count = count($this->Children);
$a_child->Position = $node_count;
if ($node_count == 0) {
$this->firstChild =& $a_child;
$this->lastChild =& $a_child;
}
else {
$this->lastChild =& $a_child;
}
$this->Children[] =& $a_child;
$a_child->SetParent($this);
}
function AppendData($data)
{
$this->Data .= $data;
}
function &GetChild($path)
{
$entries = explode('/', strtoupper($path));
$cur = array_shift($entries);
if ($cur == $this->Name) $cur = array_shift($entries);
if (!$cur) return $this;
if (!isset($this->Children[$cur])) return false;
$left = implode('/', $entries);
if (!$left) return $this->Children[$cur];
return $this->Children[$cur]->GetChild($left);
}
function GetChildValue($path)
{
$child =& $this->GetChild($path);
if ($child !== false) {
return $child->Data;
}
}
function &GetChildByPosition($position)
{
if ($position < count($this->Children) ) {
return $this->Children[$position];
}
else {
$false = false;
return $false;
}
}
function &FindChild($name)
{
$name = strtoupper($name);
if ($this->Name == $name) return $this;
// if (isset($this->Children[$name])) return $this->Children[$name];
// $children = array_keys($this->Children);
foreach ($this->Children as $elem)
{
$child =& $elem->FindChild($name);
if ($child !== false)
{
return $child;
}
}
$false = false;
return $false;
}
function FindChildValue($name, $attr=null)
{
$child =& $this->FindChild($name);
if ($child !== false) {
if (isset($attr)) {
return $child->Attributes[strtoupper($attr)];
}
return $child->Data;
}
}
/**
* Returns next node to this, false in case of end list
*
* @return kXMLNode
*/
function &NextSibling()
{
if (!is_null($this->Parent)) {
$ret =& $this->Parent->GetChildByPosition($this->Position + 1);
return $ret;
}
else {
$false = false;
return $false;
}
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/general/xml_helper.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.8
\ No newline at end of property
+1.8.2.1
\ No newline at end of property

Event Timeline