Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sun, Feb 2, 12:50 PM

in-portal

Index: trunk/kernel/include/item.php
===================================================================
--- trunk/kernel/include/item.php (revision 1199)
+++ trunk/kernel/include/item.php (revision 1200)
@@ -1,1052 +1,1052 @@
<?php
require_once($pathtoroot."kernel/include/itemreview.php");
require_once($pathtoroot."kernel/include/itemrating.php");
class clsItem extends clsParsedItem
{
var $type;
var $Reviews;
var $Related;
var $Images;
var $PrimaryCat;
var $IsNew = FALSE;
var $IsHot = FALSE;
var $IsPop = FALSE;
var $Keywords;
var $OpenTagVar;
var $CloseTagVar;
var $AdminParser;
var $CustomFields;
var $FieldClass;
var $CustomLoaded=0;
var $ReviewSortOrder;
var $ReviewPerPageVar;
function clsItem($FullItem=FALSE)
{
$this->clsParsedItem();
if($FullItem==TRUE)
{
$this->Reviews = new clsItemReviewList();
$this->Related = new clsRelationshipList();
}
$this->Images = new clsImageList();
$this->CustomFields = array();
$this->FieldClass = new clsCustomFieldList();
}
function ClearCacheData()
{
DeleteModuleTagCache('kernel');
DeleteModuleTagCache('inlink');
DeleteModuleTagCache('innews');
DeleteModuleTagCache('inbulletin');
}
/* item reviews */
function &GetItemReviews($Page=1)
{
$res_id = $this->Get("ResourceId");
$this->Reviews->itemID=$res_id;
$this->Reviews->PerPageVar = $this->ReviewPerPageVar;
$this->Reviews->Page = $Page;
$this->Reviews->GetReviewList("Status=1",$this->ReviewSortOrder);
return $this->Reviews;
}
function ReviewCount($TodayOnly=FALSE)
{
if(is_numeric($this->Get("CachedReviewsQty")) && !$TodayOnly)
return (int)$this->Get("CachedReviewsQty");
$this->Reviews->itemID=$this->Get("ResourceId");
return (int)$this->Reviews->GetItemReviewCount($TodayOnly);
}
function ReviewsLoaded()
{
if($this->Reviews->itemID==$this->Get("ResourceId"))
{
return $this->Reviews->ItemCount();
}
else
return 0;
}
function &AddReview($createdBy,$reviewText,$isPending,$ip=NULL,$ForceIP=0, $Module="", $CreatedOn = 0)
{
$this->Reviews->itemID=$this->Get("ResourceId");
if($ip == NULL)
$ip = $_SERVER["REMOTE_ADDR"];
if(!$CreatedOn)
$CreatedOn = mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
$Status = 1;
if($isPending)
$Status = 2;
$AutoModule = GetModuleByAction(); // determine module name by action
if( $Module && ($AutoModule != $Module) ) $AutoModule = $Module;
$r = $this->Reviews->AddReview($CreatedOn,$reviewText,$Status,$ip,0,$this->Get("ResourceId"),$this->type,$createdBy,0,$AutoModule);
$this->Increment("CachedReviewsQty");
return $r;
}
function ReviewIPExists($ip)
{
return ip_exists($ip,$this->Get("ResourceId"),$this->Reviews->SourceTable);
}
function DeleteReview($reviewID)
{
$r = $this->Reviews->GetReview($reviewID);
if(is_object($r))
{
$r->Delete();
$this->Decrement("CachedReviewsQty");
}
}
function DeleteReviews()
{
$res_id = $this->Get("ResourceId");
if($res_id)
{
$sql = "DELETE FROM ".GetTablePrefix()."ItemReview WHERE ItemId=$res_id";
$this->adodbConnection->Execute($sql);
unset($this->Reviews);
$this->Reviews = new clsItemReviewList($res_id);
}
}
/* item custom fields */
function LoadCustomFields()
{
if(!$this->CustomLoaded && $this->Get("ResourceId")>0)
{
$this->FieldClass = new clsCustomFieldList();
$this->FieldClass->Type = $this->type;
$this->FieldClass->LoadFieldsAndValues($this->Get("ResourceId"));
foreach($this->FieldClass->Items as $f)
{
$this->CustomFields[$f->Get("FieldName")] = $f->HasField('Value') ? $f->Get('Value') : '';
}
$this->CustomLoaded = 1;
}
}
function SetCustomField($fieldname,$value)
{
// echo "Setting CF [<b>$fieldname</b>] = [$value]<br>";
if(!$this->CustomLoaded)
$this->LoadCustomFields();
$this->CustomFields[$fieldname] = $value;
}
function SaveCustomFields()
{
//echo "Saving CFs<br>";
if(!(int)$this->Get("ResourceId"))
return TRUE;
if(!$this->CustomLoaded)
return TRUE;
$data = new clsCustomDataList();
$data->LoadResource($this->Get("ResourceId"));
foreach($this->FieldClass->Items as $f)
{
$value = $this->CustomFields[$f->Get("FieldName")];
$data->SetFieldValue($f->Get("CustomFieldId"),$this->Get("ResourceId"),$value);
}
$data->SaveData();
unset($data);
}
function GetCustomFieldValue($fieldname,$default="")
{
if(!$this->CustomLoaded)
$this->LoadCustomFields();
$fieldname=strtolower($fieldname);
foreach($this->CustomFields as $k=>$v)
if(strtolower($k)==$fieldname)
return $v;
return $default;
if(isset($this->CustomFields[$fieldname]))
{
$ret = $this->CustomFields[$fieldname];
}
elseif(isset($this->CustomFields[$fieldname=strtolower($fieldname)]))
{
$ret = $this->CustomFields[$fieldname];
}
else
$ret = $default;
return $ret;
}
function DeleteCustomData()
{
$cdata = new clsCustomDataList();
$cdata->DeleteResource($this->Get("ResourceId"));
}
function Delete($RecordOnly=FALSE)
{
global $objFavorites;
if($RecordOnly==FALSE)
{
$this->DeleteReviews();
$this->DeleteRelations();
$this->DeleteCustomData();
if($this->NoResourceId==0)
{
if($this->UsingTempTable()==FALSE)
{
if(is_object($this->Images))
$this->Images->DeleteResource($this->Get("ResourceId"));
$objFavorites->DeleteItem($this->Get("ResourceId"));
}
}
}
parent::Delete();
}
/* item relationships */
function GetRelatedItems()
{
global $objConfig;
$where = "SourceId = ".$this->Get("ResourceId");
$where .= " OR (TargetId=".$this->Get("ResourceId")." AND Type=1)";
$orderBy = $objConfig->Get("Relation_Sortfield")." ".$objConfig->Get("Relation_Sortorder");
$orderBy = trim($orderBy);
$this->Related->Clear();
$res = $this->Related->LoadRelated($where,$orderBy);
return $res;
}
function &RelationObject()
{
return $this->Related;
}
function DeleteRelations()
{
$res_id = $this->Get("ResourceId");
if($res_id)
{
$sql = "DELETE FROM ".GetTablePrefix()."Relationship WHERE SourceId=$res_id OR TargetId=$res_id";
$this->adodbConnection->Execute($sql);
unset($this->Reviews);
$this->Related = new clsRelationshipList($res_id);
}
}
/* keyword highlighting for searches */
function HighlightField($field)
{
global $objConfig;
if(/*!strlen($OpenTag) || !strlen($CloseTag) ||*/ !is_array($this->Keywords))
{
//echo "Missing something<br>\n";
return $this->Get($field);
}
if(strlen($this->OpenTagVar))
$OpenTag = $objConfig->Get($this->OpenTagVar);
if(strlen($this->CloseTagVar))
$CloseTag = $objConfig->Get($this->CloseTagVar);
$k = array_merge($this->Keywords["required"],$this->Keywords["normal"]);
if(count($k))
{
$result = HighlightKeywords($k, $this->Get($field), $OpenTag, $CloseTag);
}
else
{
$result = $this->Get($field);
//echo "No Keywords<br>\n";
}
return $result;
}
function HighlightText($text)
{
global $objConfig;
if(strlen($this->OpenTagVar))
$OpenTag = $objConfig->Get($this->OpenTagVar);
if(strlen($this->CloseTagVar))
$CloseTag = $objConfig->Get($this->CloseTagVar);
if(!strlen($OpenTag) || !strlen($CloseTag) || !is_array($this->Keywords)) {
return $text;
}
$k = array_merge($this->Keywords["required"],$this->Keywords["normal"]);
if(count($k))
{
$result = HighlightKeywords($k,$text, $OpenTag, $CloseTag);
}
else
$result = $text;
return $result;
}
/* item status functions */
function Is($name)
{
$var = "m_" . $name;
return ( isset($this->$var) && $this->$var ) ? true : false;
}
function IsHotItem()
{
switch($this->Get("HotItem"))
{
case ALWAYS:
return TRUE;
break;
case NEVER:
return FALSE;
break;
case AUTO:
return $this->IsHot;
break;
}
}
function SetHotItem()
{
$this->IsHot = FALSE;
}
function IsNewItem()
{
switch($this->Get("NewItem"))
{
case ALWAYS:
return TRUE;
break;
case NEVER:
return FALSE;
break;
case AUTO:
return $this->IsNew;
break;
}
}
function SetNewItem()
{
$this->IsNew = FALSE;
}
function IsPopItem()
{
switch($this->Get("PopItem"))
{
case ALWAYS:
return TRUE;
break;
case NEVER:
return FALSE;
break;
case AUTO:
return $this->IsPop;
break;
}
}
function SetPopItem()
{
$this->IsPop = FALSE;
}
function SetFromArray($data, $dirty = false)
{
parent::SetFromArray($data, $dirty);
if(is_array($data))
{
if(array_key_exists("NewItem",$data))
{
$this->SetNewItem();
}
if(array_key_exists("HotItem",$data))
{
$this->SetHotItem();
}
if(array_key_exists("PopItem",$data))
{
$this->SetPopItem();
}
}
}
function Validate()
{
/* skeleton*/
return true;
}
function LoadFromDatabase($Id, $IdField = null) // custom IdField by Alex)
{
/* skeleton */
parent::LoadFromDatabase($Id, $IdField);
}
//Changes priority
function MoveDown()
{
$this->Decrement("Priority");
}
function MoveUp()
{
$this->Increment("Priority");
}
function CheckPermission($permissionName)
{
//Check permission and if needs approval set approval
global $objSession,$objCatList;
$perm = $this->BasePermission;
if(strlen($perm)>0)
$perm .= ".";
$perm .= $permissionName;
//get an instance of the forum category
$cat =& $objCatList->GetCategory($this->Get("CategoryId"));
if(!is_object($cat))
{
return FALSE;
}
else
{
return ($cat->HasPermission($perm,$objSession->Get("GroupId")));
}
}
function SubmitVote($voteRating, $voteNotes)
{
global $Errors;
global $REMOTE_ADDR;
//echo "Submitting vote<br>";
/* if($this->rating_ip_exists($REMOTE_ADDR))
{
// $Errors->AddError("error.already_voted","","","",get_class($this),"SubmitVote");
return false;
}*/
$vote = new clsItemRating(NULL);
$vote->Set("ItemId",$this->UniqueId());
$vote->Set("RatingValue",$voteRating);
if(!$vote->Create()) {
//echo "Submitting Failed<br>";
return false;
}
$NumVotes = (int)$this->Get("CachedVotesQty");
$CurrentRating = (int)$this->Get("CachedRating");
$Rating = (($NumVotes * $CurrentRating) + $voteRating)/($NumVotes+1);
$this->Set("CachedRating",$Rating);
$this->Update();
$this->Increment("CachedVotesQty");
//echo "Submitting Done<br>";
}
function rating_ip_exists($ip)
{
$count = 0;
$id = $this->Get("ResourceId");
$sql = "SELECT count(*) as DupCount FROM ".GetTablePrefix()."ItemRating WHERE IPAddress='$ip' and ItemId=$id";
$adodbConnection = &GetADODBConnection();
$rs = $adodbConnection->Execute($sql);
if($rs)
{
$count = $rs->fields["DupCount"];
}
return ($count>0);
//return FALSE;
}
function PurgeRatings()
{
global $objConfig;
$expired=time()-86400*$objConfig->Get("Timeout_Rating");
$query="DELETE FROM ".GetTablePrefix()."ItemRating WHERE CreatedOn<$expired";
$this->adodbConnection->Execute($query);
}
function GetThumbnailImage()
{
if($this->Images->NumItems()==0)
$this->Images->GetResourceImages($this->Get("ResourceId"));
return $this->Images->GetResourceThumbnail($this->Get("ResourceId"));
}
function GetImage($number)
{
return $this->Images->GetImageByResource($this->Get("ResourceId"),$number);
}
function GetImageByName($name)
{
if(!is_object($this->Images))
$this->Images = new clsImageList();
return $this->Images->GetImageByName($this->Get("ResourceId"),$name);
}
function &GetDefaultImage()
{
return $this->Images->GetDefaultImage($this->Get("ResourceId"));
}
function &GetAvatarImage()
{
return $this->Images->GetAvatarImage($this->Get("ResourceId"));
}
function CreatePendingCopy()
{
$OrgId = $this->IdField();
$this->Dirty();
$this->Set("OrgId",$OrgId);
$this->UnsetIdField();
$this->Set("ResourceId",0);
$this->Set("Status",-2);
$this->Create();
}
function AddFavorite($PortalUserId=NULL)
{
global $objSession, $objFavorites;
$res = FALSE;
- if($objSession->HasCatPermission("FAVORITES"))
+ if($objSession->HasCatPermission("FAVORITES",$this->GetPrimaryCategory() ))
{
if(!$PortalUserId)
$PortalUserId = $objSession->Get("PortalUserId");
if($PortalUserId==$objSession->Get("PortalUserId") || $objSession->HasSystemPermission("ADMIN"))
{
$objFavorites->AddFavorite($PortalUserId,$this->Get("ResourceId"), $this->type);
$res = TRUE;
}
}
return $res;
}
function DeleteFavorite($PortalUserId=NULL)
{
global $objSession, $objFavorites;
$res = FALSE;
if($objSession->HasCatPermission("FAVORITES"))
{
if(!$PortalUserId)
$PortalUserId = $objSession->Get("PortalUserId");
//echo $PortalUserId." ".$objSession->Get("PortalUserId");
if($PortalUserId==$objSession->Get("PortalUserId") || $objSession->HasSystemPermission("ADMIN"))
{
$objFavorites->DeleteFavorite($PortalUserId,$this->Get("ResourceId"));
$res = TRUE;
}
}
return $res;
}
function IsFavorite($PortalUserId=NULL)
{
global $objSession, $objFavorites;
$res = FALSE;
if($objSession->HasCatPermission("FAVORITES"))
{
if(!$PortalUserId)
$PortalUserId = $objSession->Get("PortalUserId");
if($PortalUserId==$objSession->Get("PortalUserId") || $objSession->HasSystemPermission("ADMIN"))
{
$i = $objFavorites->GetFavoriteObject($PortalUserId,$this->Get("ResourceId"));
if(is_object($i))
{
$res = TRUE;
}
else
$res = FALSE;
}
}
return $res;
}
function CheckBanned()
{
global $objBanList;
$objBanList->LoadItemRules($this->type);
$found = FALSE;
$MatchedRule = 0;
foreach($objBanList->Items as $b)
{
$field = $b->Get("ItemField");
if($this->FieldExists($field))
{
$ThisValue = strtolower($this->Get($field));
$TestValue = strtolower($b->Get("ItemValue"));
switch($b->Get("ItemVerb"))
{
case 0: /* any */
$found = TRUE;
break;
case 1: /* is */
if($ThisValue==$TestValue)
$found = TRUE;
break;
case 2: /* is not */
if($ThisValue != $TestValue)
$found = TRUE;
break;
case 3: /* contains */
if(strstr($ThisValue,$TestValue))
$found = TRUE;
break;
case 4: /* not contains */
if(!strstr($ThisValue,$TestValue))
$found = TRUE;
break;
case 5: /* Greater Than */
if($TestValue > $ThisValue)
$found = TRUE;
break;
case 6: /* Less Than */
if($TestValue < $ThisValue)
$found = TRUE;
break;
case 7: /* exists */
if(strlen($ThisValue)>0)
$found = TRUE;
break;
case 8: /* unique */
if($this->ValueExists($field,$ThisValue))
$found = TRUE;
break;
}
}
if($found)
{
if($b->Get("RuleType")==0)
{
$MatchedRule = $b->Get("RuleId");
}
else
{
$MatchedRule = 0;
}
break;
}
}
return $MatchedRule;
}
} /* clsItem */
class clsCatItem extends clsItem
{
function clsCatItem($FullItem=FALSE)
{
$this->clsItem($FullItem);
}
function Delete($RecordOnly=FALSE)
{
global $objFavorites;
parent::Delete($RecordOnly);
if($RecordOnly==FALSE)
{
$this->RemoveFromAllCategories();
}
}
/* category membership functions */
function AssignPrimaryCategory($SourceTable)
{
$catid = 0;
$sql = "SELECT * FROM $SourceTable WHERE ItemResourceId=".$this->Get("ResourceId")." LIMIT 1";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$catid = $rs->fields["CategoryId"];
$this->SetPrimaryCategory($catid,$SourceTable);
}
return $catid;
}
function GetPrimaryCategory($SourceTable = "")
{
if(is_numeric($this->PrimaryCat))
return $this->PrimaryCat;
$this->PrimaryCat="";
if( strlen($SourceTable) == 0 ) $SourceTable = GetTablePrefix()."CategoryItems";
$res_id = $this->HasField('ResourceId') ? $this->Get('ResourceId') : 0;
$sql = "SELECT * FROM $SourceTable WHERE ItemResourceId=".$res_id." AND PrimaryCat=1";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$this->PrimaryCat=$rs->fields["CategoryId"];
return $this->PrimaryCat;
}
else
{
$this->AssignPrimaryCategory($SourceTable);
return $this->PrimaryCat;
}
}
function SetPrimaryCategory($CategoryId,$SourceTable = "")
{
if(strlen($SourceTable)==0)
$SourceTable = GetTablePrefix()."CategoryItems";
$rs = $this->adodbConnection->Execute('SELECT * FROM '.$SourceTable.' WHERE CategoryId='.$CategoryId.' AND ItemResourceId='.$this->Get("ResourceId"));
$this->adodbConnection->Execute("UPDATE $SourceTable SET PrimaryCat=0 WHERE ItemResourceId=".$this->Get("ResourceId"));
$this->adodbConnection->Execute("UPDATE $SourceTable SET PrimaryCat=1 WHERE CategoryId=$CategoryId AND ItemResourceId=".$this->Get("ResourceId"));
$this->PrimaryCat=$CategoryId;
}
function CategoryMemberCount($SourceTable="")
{
if(strlen($SourceTable)==0)
$SourceTable = GetTablePrefix()."CategoryItems";
$sql = "SELECT count(*) as CatCount FROM $SourceTable WHERE ItemResourceId=".$this->Get("ResourceId");
if($this->debuglevel)
echo $sql."<br>\n";
$rs = $this->adodbConnection->Execute($sql);
$count = 0;
if($rs && !$rs->EOF)
$count = $rs->fields["CatCount"];
return $count;
}
/**
* Return comma separated CategoryId list,
* where this item is member (will be shown there)
*
* @param string $SourceTable
* @return string
*/
function CategoryMemberList($SourceTable="")
{
$cats = array();
if(strlen($SourceTable)==0)
$SourceTable = GetTablePrefix()."CategoryItems";
$sql = "SELECT * FROM $SourceTable WHERE ItemResourceId=".$this->Get("ResourceId");
if($this->debuglevel)
echo $sql."<br>\n";
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$cats[] = $rs->fields["CategoryId"];
$rs->MoveNext();
}
$catlist = implode(",",$cats);
return $catlist;
}
function AddToCategory($CatId,$SourceTable="",$PrimaryValue=NULL)
{
global $objSession, $objCatList;
if(!$SourceTable)
$SourceTable = GetTablePrefix()."CategoryItems";
if($this->type>0)
{
$Primary = 0;
if(is_numeric($PrimaryValue))
{
$Primary = $PrimaryValue;
if($Primary==1)
$this->PrimaryCat = $CatId;
}
else
{
if(!is_numeric($this->GetPrimaryCategory()))
{
$Primary =1;
$this->PrimaryCat = $CatId;
}
}
// check if not exists
$db =& $this->adodbConnection;
$sql = sprintf('SELECT * FROM %s WHERE CategoryId = %s AND ItemResourceId = %s', $SourceTable, (int)$CatId, $this->Get("ResourceId"));
$rs = $db->Execute($sql);
if (is_object($rs)) {
if($rs->RecordCount() == 0 )
{
$sql = "INSERT INTO $SourceTable (CategoryId,ItemResourceId, PrimaryCat) VALUES (".(int)$CatId.",'".$this->Get("ResourceId")."',$Primary)";
if($this->debuglevel)
echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
}
}
$c = $objCatList->GetCategory($CatId);
}
}
function RemoveFromCategory($CatId,$SourceTable="",$Force=0)
{
if(!is_numeric($CatId)) return;
global $objSession, $objCatList;
if(strlen($SourceTable)==0)
$SourceTable = GetTablePrefix()."CategoryItems";
if($this->type>0)
{
$primary = $this->GetPrimaryCategory();
if(($primary==$CatId && $this->CategoryMemberCount($SourceTable)>1) || ($primary != $CatId) || $Force)
{
$sql = "DELETE FROM $SourceTable WHERE CategoryId=$CatId AND ItemResourceId=".$this->Get("ResourceId");
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
$c = $objCatList->GetCategory($CatId);
$c->ClearCacheData();
}
}
}
function MoveToCategory($OldCatId,$NewCatId,$SourceTable="")
{
if(strlen($SourceTable)==0)
$SourceTable = GetTablePrefix()."CategoryItems";
$sql = "UPDATE $SourceTable SET CategoryId=$NewCatId WHERE CategoryId=$OldCatId AND ItemResourceId=".$this->Get("ResourceId");
if($this->debuglevel)
echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
}
function DeleteCategoryItems($CatId,$SourceTable = "")
{
if(strlen($SourceTable)==0)
$SourceTable = GetTablePrefix()."CategoryItems";
$CatCount = $this->CategoryMemberCount($SourceTable);
if($CatCount>1)
{
$this->RemoveFromCategory($CatId,$SourceTable);
$this->ClearCacheData();
}
else
{
$this->Delete();
$sql = "DELETE FROM $SourceTable WHERE CategoryId=$CatId AND ItemResourceId=".$this->Get("ResourceId");
if($this->debuglevel)
echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
}
}
function RemoveFromAllCategories($SourceTable = "")
{
if(strlen($SourceTable)==0)
$SourceTable = GetTablePrefix()."CategoryItems";
if($this->type>0)
{
$sql = "SELECT * FROM $SourceTable WHERE ItemResourceId=".$this->Get("ResourceId");
$rs = $this->adodbConnection->Execute($sql);
while ($rs && !$rs->EOF)
{
$CategoryId = $rs->fields["CategoryId"];
$rs->MoveNext();
}
$sql = "DELETE FROM $SourceTable WHERE ItemResourceId=".$this->Get("ResourceId");
if($this->debuglevel)
echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
}
}
function CopyToNewResource($TargetCat = NULL,$NameField="Name")
{
global $objSession;
$CatList = $this->CategoryMemberList();
$Cats = explode(",",$CatList);
//echo "Target: $TargetCat<br>";
$OldId = $this->Get("ResourceId");
$this->UnsetIdField();
$this->Dirty();
if(!is_numeric($this->Get("OrgId")))
$this->UnsetField("OrgId");
$this->UnsetField("ResourceId");
if(is_numeric($TargetCat) && strlen($NameField))
{
$OldName = $this->Get($NameField);
if(substr($OldName,0,5)=="Copy ")
{
$parts = explode(" ",$OldName,4);
if($parts[2]=="of" && is_numeric($parts[1]))
{
$Name = $parts[3];
}
else
if($parts[1]=="of")
{
$Name = $parts[2]." ".$parts[3];
}
else
$Name = $OldName;
}
else
$Name = $OldName;
$Names = CategoryItemNameCount($TargetCat,$this->tablename,$NameField,$Name);
if(count($Names)>0)
{
$NameCount = count($Names);
$found = FALSE;
$NewName = "Copy of $Name";
if(!in_array("Copy of $Name",$Names))
{
$found = TRUE;
}
else
{
for($x=2;$x<$NameCount+2;$x++)
{
$NewName = "Copy ".$x." of ".$Name;
if(!in_array($NewName,$Names))
{
$found = TRUE;
break;
}
}
}
if(!$found)
{
$NameCount++;
$NewName = "Copy $NameCount of $Name";
}
$this->Set($NameField,$NewName);
}
}
$this->Create();
// copy relationships
$NewId = $this->Get("ResourceId");
$reldata = new clsRelationshipList($TargetCat,$this->IdField());
$reldata->CopyToResource($OldId,$NewId);
// copy reviews
$rdata = new clsItemReviewList();
$rdata->CopyToItemId($OldId,$NewId);
unset($rdata);
// copy custom fields
$cdata = new clsCustomDataList();
$cdata->CopyResource($OldId,$NewId);
unset($cdata);
// copy images
if(is_object($this->Images))
$this->Images->CopyResource($OldId,$NewId);
$this->AddToCategory($TargetCat, '', 0); // insert (but with duplicate records check)
//echo "ok";
if(is_numeric($TargetCat))
{
if(is_array($Cats))
{
if(!in_array($TargetCat,$Cats))
{
$this->AddToCategory($TargetCat, 0); // insert
}
}
$this->SetPrimaryCategory($TargetCat); // 2 updates
}
}
function refreshLastUpdate($cat_id = null)
{
$db =& GetADODBConnection();
$prefix = GetTablePrefix();
// 1,2,3,4 - set lastupdate date to item's primary category as recent
// change date of all items in this category of same type as this item
// 1. get item category or use passed one
if(!isset($cat_id)) $cat_id = $this->GetPrimaryCategory();
if($cat_id == 0) return false;
// 2. get all item ResourceIds in that category
$sql = 'SELECT ItemResourceId FROM '.$prefix.'CategoryItems WHERE CategoryId = '.$cat_id;
$item_rids = $db->GetCol($sql);
if($item_rids)
{
$item_rids = implode(',',$item_rids);
// 2a. get LastUpdate date based on all item in $cat_id category
$sql = 'SELECT MAX(IF(Modified=0,CreatedOn,Modified)) FROM '.$this->tablename.' WHERE ResourceId IN ('.$item_rids.')';
$item_last_update = $db->GetOne($sql);
}
else
{
$item_last_update = 0;
}
// 3. get LastUpdate date based on all $cat_id subcategories
$sql = 'SELECT MAX(IF(Modified=0,CreatedOn,Modified)) FROM '.$prefix.'Category WHERE ParentId = '.$cat_id;
$cat_last_update = $db->GetOne($sql);
$last_update = max($item_last_update,$cat_last_update);
// 4. set $last_update date to $cat_id category
$sql = 'UPDATE '.$prefix.'Category SET Modified = '.$last_update.' WHERE CategoryId = '.$cat_id;
$db->Execute($sql);
// 5. get $cat_id parent CategoryId
$sql = 'SELECT ParentId FROM '.$prefix.'Category WHERE CategoryId = '.$cat_id;
if($cat_id > 0) $this->refreshLastUpdate( $db->GetOne($sql) );
}
}
?>
\ No newline at end of file
Property changes on: trunk/kernel/include/item.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.20
\ No newline at end of property
+1.21
\ No newline at end of property
Index: trunk/kernel/include/debugger.php
===================================================================
--- trunk/kernel/include/debugger.php (revision 1199)
+++ trunk/kernel/include/debugger.php (revision 1200)
@@ -1,798 +1,818 @@
<?php
- if(!defined('DBG_OPTIONS')) define('DBG_OPTIONS',0);
-
- if(!defined('DBG_USE_HIGHLIGHT')) define('DBG_USE_HIGHLIGHT',1);
+ // Detect fact, that this session beeing debugged by Zend Studio
+ foreach($_REQUEST as $rq_name=>$rq_value)
+ {
+ if( substr($rq_name,0,6)=='debug_' )
+ {
+ define('DBG_ZEND_PRESENT',1);
+ break;
+ }
+ }
- if(!defined('DBG_USE_SHUTDOWN_FUNC')) define('DBG_USE_SHUTDOWN_FUNC',1);
- if(!defined('DBG_HANDLE_ERRORS')) define('DBG_HANDLE_ERRORS', isset($_REQUEST['debug_port']) ? 0 : 1);
+ dbg_safeDefine('DBG_ZEND_PRESENT',0);
- if(!defined('DBG_RAISE_ON_WARNINGS')) define('DBG_RAISE_ON_WARNINGS',0);
- if(!defined('DBG_SHOW_MEMORY_USAGE')) define('DBG_SHOW_MEMORY_USAGE',1);
+ // set default values for debugger constants
+ $dbg_constMap=Array('DBG_OPTIONS'=>0,
+ 'DBG_USE_HIGHLIGHT'=>1,
+ 'DBG_USE_SHUTDOWN_FUNC'=>DBG_ZEND_PRESENT?0:1,
+ 'DBG_HANDLE_ERRORS'=>DBG_ZEND_PRESENT?0:1,
+ 'DBG_SHOW_MEMORY_USAGE'=>1,
+ 'DOC_ROOT'=>$_SERVER['DOCUMENT_ROOT'],
+ 'WINDOWS_ROOT'=>'w:');
- if(!defined('DOC_ROOT')) define('DOC_ROOT',$_SERVER['DOCUMENT_ROOT']);
- if(!defined('WINDOWS_ROOT')) define('WINDOWS_ROOT','w:');
+ foreach($dbg_constMap as $dbg_constName=>$dbg_constValue)
+ {
+ dbg_safeDefine($dbg_constName,$dbg_constValue);
+ }
if(!defined('WINDOWS_EDITOR'))
{
$dbg_editor = 0;
$dbg_editors[0] = Array('editor' => 'c:\Program Files\UltraEdit\uedit32.exe', 'params' => '%F/%L');
$dbg_editors[1] = Array('editor' => 'c:\Program Files\Zend\ZendStudio-4.0Beta\bin\ZDE.exe', 'params' => '%F');
define('WINDOWS_EDITOR',$dbg_editors[$dbg_editor]['editor'].' '.$dbg_editors[$dbg_editor]['params']);
unset($dbg_editors,$dbg_editor);
}
class Debugger
{
/**
* Debugger data for building report
*
* @var Array
*/
var $Data = Array();
var $ProfilerData = Array();
var $RecursionStack = Array(); // prevent recursion when processing debug_backtrace() function results
var $TraceNextError=false;
var $Options = 0;
var $OptionsMap = Array('shutdown_func' => 1, 'error_handler' => 2,
'output_buffer' => 4, 'highlight_output' => 8);
var $longErrors=Array();
/**
* Amount of memory used by debugger itself
*
* @var Array
* @access private
*/
var $memoryUsage=Array();
function Debugger()
{
+ ini_set('display_errors',dbg_ConstOn('DBG_ZEND_PRESENT')?0:1);
$this->memoryUsage['error_handling']=0; // memory amount used by error handler
$this->appendRequest();
}
function initOptions()
{
}
function mapLongError($msg)
{
$key=$this->generateID();
$this->longErrors[$key]=$msg;
return $key;
}
function setOption($name,$value)
{
if( !isset($this->OptionsMap[$name]) ) die('undefined debugger option: ['.$name.']<br>');
if($value)
{
$this->Options|=$this->OptionsMap[$name];
}
else
{
$this->Options=$this->Options&~$this->OptionsMap[$name];
}
}
function getOption($name)
{
if( !isset($this->OptionsMap[$name]) ) die('undefined debugger option: ['.$name.']<br>');
return ($this->Options & $this->OptionsMap[$name]) == $this->OptionsMap[$name];
}
/**
* Set's flag, that next error that occurs will
* be prepended by backtrace results
*
*/
function traceNext()
{
$this->TraceNextError=true;
}
function dumpVars()
{
$dumpVars = func_get_args();
foreach($dumpVars as $varValue)
{
$this->Data[] = Array('value' => $varValue, 'debug_type' => 'var_dump');
}
}
function prepareHTML($dataIndex)
{
$Data =& $this->Data[$dataIndex];
if($Data['debug_type'] == 'html') return $Data['html'];
switch($Data['debug_type'])
{
case 'error':
$fileLink = $this->getFileLink($Data['file'],$Data['line']);
$ret = '<b class="debug_error">'.$this->getErrorNameByCode($Data['no']).'</b>: '.$Data['str'];
$ret .= ' in <b>'.$fileLink.'</b> on line <b>'.$Data['line'].'</b>';
return $ret;
break;
case 'var_dump':
$ret = $this->highlightString( print_r($Data['value'], true) );
return addslashes($ret);
break;
case 'trace':
ini_set('memory_limit','500M');
$trace =& $Data['trace'];
//return 'sorry';
//return $this->highlightString(print_r($trace,true));
$i = 0; $traceCount = count($trace);
$ret = '';
while($i < $traceCount)
{
$traceRec =& $trace[$i];
$argsID = 'trace_args_'.$dataIndex.'_'.$i;
if(isset($traceRec['file']))
{
$func_name=isset($traceRec['class'])?$traceRec['class'].$traceRec['type'].$traceRec['function']:$traceRec['function'];
$ret .= '<a href="javascript:toggleTraceArgs(\''.$argsID.'\');" title="Show/Hide Function Arguments"><b>Function</b></a>: '.$this->getFileLink($traceRec['file'],$traceRec['line'],$func_name);
$ret .= ' in <b>'.basename($traceRec['file']).'</b> on line <b>'.$traceRec['line'].'</b><br>';
}
else
{
$ret .= 'no file information available';
}
// ensure parameter value is not longer then 200 symbols
$this->processTraceArguments($traceRec['args']);
$args = $this->highlightString(print_r($traceRec['args'], true));
$ret .= '<div id="'.$argsID.'" style="display: none;">'.$args.'</div>';
$i++;
}
return $ret;
break;
case 'profiler':
$profileKey = $Data['profile_key'];
$Data =& $this->ProfilerData[$profileKey];
$runtime = ($Data['ends'] - $Data['begins']); // in seconds
return '<b>Name</b>: '.$Data['description'].'<br><b>Runtime</b>: '.$runtime.'s';
break;
default:
return 'incorrect debug data';
break;
}
}
function processTraceArguments(&$traceArgs)
{
if(!$traceArgs) return '';
foreach ($traceArgs as $argID => $argValue)
{
if( is_array($argValue) || is_object($argValue) )
{
if(is_object($argValue) && !in_array(get_class($argValue),$this->RecursionStack) )
{
// object & not in stack - ok
array_push($this->RecursionStack, get_class($argValue));
settype($argValue,'array');
$this->processTraceArguments($argValue);
array_pop($this->RecursionStack);
}
elseif(is_object($argValue) && in_array(get_class($argValue),$this->RecursionStack) )
{
// object & in stack - recursion
$traceArgs[$argID] = '**** RECURSION ***';
}
else
{
// normal array here
$this->processTraceArguments($argValue);
}
}
else
{
$traceArgs[$argID] = $this->cutStringForHTML($traceArgs[$argID]);
}
}
}
function cutStringForHTML($string)
{
if( strlen($string) > 200 ) $string = substr($string,0,50).' ...';
return $string;
}
/**
* Format SQL Query using predefined formatting
* and highlighting techniques
*
* @param string $sql
* @return string
*/
function formatSQL($sql)
{
$sql = preg_replace('/(\n|\t| )+/is',' ',$sql);
$sql = preg_replace('/(CREATE TABLE|DROP TABLE|SELECT|UPDATE|SET|REPLACE|INSERT|DELETE|VALUES|FROM|LEFT JOIN|INNER JOIN|LIMIT|WHERE|HAVING|GROUP BY|ORDER BY) /is', "\n\t$1 ",$sql);
return $this->highlightString($sql);
}
function highlightString($string)
{
if( defined('DBG_USE_HIGHLIGHT')&&DBG_USE_HIGHLIGHT )
{
$string = highlight_string('<?php '.$string.'?>', true);
return preg_replace('/&lt;\?(.*)php (.*)\?&gt;/s','$2',$string);
}
else
{
return $string;
}
}
function getFileLink($file, $lineno = 1, $title = '')
{
if(!$title) $title = $file;
$is_mozilla=strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'firefox')!==false?true:false;
if($is_mozilla)
{
return '<a href="file://'.$this->getLocalFile($file).'">'.$title.'</a>';
}
else
{
return '<a href="javascript:editFile(\''.$this->getLocalFile($file).'\','.$lineno.');" title="'.$file.'">'.$title.'</a>';
}
}
function getLocalFile($remoteFile)
{
return str_replace(DOC_ROOT, WINDOWS_ROOT, $remoteFile);
}
function appendTrace()
{
$trace = debug_backtrace();
array_shift($trace);
$this->Data[] = Array('trace' => $trace, 'debug_type' => 'trace');
}
function appendHTML($html)
{
$this->Data[] = Array('html' => $html,'debug_type' => 'html');
}
/**
* Change debugger info that was already generated before.
* Returns true if html was set.
*
* @param int $index
* @param string $html
* @param string $type = {'append','prepend','replace'}
* @return bool
*/
function setHTMLByIndex($index,$html,$type='append')
{
if( !isset($this->Data[$index]) || $this->Data[$index]['debug_type'] != 'html' )
{
return false;
}
switch ($type)
{
case 'append':
$this->Data[$index]['html'] .= '<br>'.$html;
break;
case 'prepend':
$this->Data[$index]['html'] = $this->Data[$index]['html'].'<br>'.$html;
break;
case 'replace':
$this->Data[$index]['html'] = $html;
break;
}
return true;
}
/**
* Move $debugLineCount lines of input from debug output
* end to beginning.
*
* @param int $debugLineCount
*/
function moveToBegin($debugLineCount)
{
$lines = array_splice($this->Data,count($this->Data)-$debugLineCount,$debugLineCount);
$this->Data = array_merge($lines,$this->Data);
}
function appendRequest()
{
$script = $_SERVER['PATH_TRANSLATED'];
$this->appendHTML('ScriptName: <b>'.$this->getFileLink($script,1,basename($script)).'</b> (<b>'.dirname($script).'</b>)');
ob_start();
?>
<table width="100%" border="0" cellspacing="0" cellpadding="4" class="flat_table">
<thead style="font-weight: bold;">
<td width="20">Src</td><td>Name</td><td>Value</td>
</thead>
<?php
foreach($_REQUEST as $key => $value)
{
if( !is_array($value) && trim($value) == '' )
{
$value = '<b class="debug_error">no value</b>';
}
else
{
$value = htmlspecialchars(print_r($value, true));
}
$src = isset($_GET[$key]) ? 'GE' : (isset($_POST[$key]) ? 'PO' : (isset($_COOKIE[$key]) ? 'CO' : '?') );
echo '<tr><td>'.$src.'</td><td>'.$key.'</td><td>'.$value.'</td></tr>';
}
?>
</table>
<?php
$this->appendHTML( ob_get_contents() );
ob_end_clean();
}
function appendSession()
{
if( isset($_SESSION)&&$_SESSION )
{
$this->appendHTML('PHP Session: [<b>'.ini_get('session.name').'</b>]');
$this->dumpVars($_SESSION);
$this->moveToBegin(2);
}
}
function profileStart($key, $description)
{
$timeStamp = $this->getMoment();
$this->ProfilerData[$key] = Array('begins' => $timeStamp, 'ends' => 5000, 'debuggerRowID' => count($this->Data), 'description' => $description);
$this->Data[] = array('profile_key' => $key, 'debug_type' => 'profiler');
}
function profileFinish($key)
{
$this->ProfilerData[$key]['ends'] = $this->getMoment();
}
function getMoment()
{
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
function generateID()
{
list($usec, $sec) = explode(" ",microtime());
$id_part_1 = substr($usec, 4, 4);
$id_part_2 = mt_rand(1,9);
$id_part_3 = substr($sec, 6, 4);
$digit_one = substr($id_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$id_part_1 = ereg_replace("^0","",$id_part_1);
$id_part_1=$digit_one.$id_part_1;
}
return $id_part_1.$id_part_2.$id_part_3;
}
function getErrorNameByCode($errorCode)
{
switch($errorCode)
{
case E_USER_ERROR:
return 'Fatal Error';
break;
case E_WARNING:
case E_USER_WARNING:
return 'Warning';
break;
case E_NOTICE:
case E_USER_NOTICE:
return 'Notice';
break;
default:
return '';
break;
}
}
/**
* Generates report
*
*/
function printReport($returnResult = false)
{
+ if( dbg_ConstOn('DBG_ZEND_PRESENT') ) return;
+ dbg_safeDefine('DBG_RAISE_ON_WARNINGS',0);
$this->memoryUsage['debugger_start']=memory_get_usage();
// show php session if any
$this->appendSession();
// ensure, that 1st line of debug output always is this one:
$this->appendHTML('<a href="javascript:toggleDebugLayer(27);">Hide Debugger</a>');
$this->moveToBegin(1);
$i = 0; $lineCount = count($this->Data);
ob_start();
?>
<style type="text/css">
.flat_table TD {
border: 1px solid buttonface;
border-width: 1 1 0 0;
}
.debug_layer_table {
border-collapse: collapse;
width: 480px;
}
.debug_text, .debug_row_even TD, .debug_row_odd TD {
color: #000000;
font-family: Verdana;
font-size: 11px;
word-wrap: break-word;
}
.debug_cell {
border: 1px solid #FF0000;
padding: 2px;
word-wrap: break-word;
}
.debug_row_even {
background-color: #CCCCFF;
}
.debug_row_odd {
background-color: #FFFFCC;
}
.debug_layer_container {
left: 2px;
top: 1px;
width: 500px;
z-index: +1000;
position: absolute;
overflow: auto;
border: 2px solid;
padding: 3px;
border-top-color: threedlightshadow;
border-left-color: threedlightshadow;
border-right-color: threeddarkshadow;
border-bottom-color: threeddarkshadow;
background-color: buttonface;
}
.debug_layer {
padding: 0px;
width: 480px;
}
.debug_error {
color: #FF0000;
}
</style>
<div id="debug_layer" class="debug_layer_container" style="display: none;">
<div class="debug_layer">
<table width="100%" cellpadding="0" cellspacing="1" border="0" class="debug_layer_table">
<?php
while ($i < $lineCount)
{
echo '<tr class="debug_row_'.(($i % 2) ? 'odd' : 'even').'"><td class="debug_cell">'.$this->prepareHTML($i).'</td></tr>';
$i++;
}
?>
</table>
</div>
</div>
<script language="javascript">
function getEventKeyCode($e)
{
var $KeyCode = 0;
if($e.keyCode) $KeyCode = $e.keyCode;
else if($e.which) $KeyCode = $e.which;
return $KeyCode;
}
function keyProcessor($e)
{
if(!$e) $e = window.event;
var $KeyCode = getEventKeyCode($e);
if($KeyCode==123||$KeyCode==27) // F12 or ESC
{
toggleDebugLayer($KeyCode);
$e.cancelBubble = true;
if($e.stopPropagation) $e.stopPropagation();
}
}
function toggleDebugLayer($KeyCode)
{
var $isVisible=false;
var $DebugLayer = document.getElementById('debug_layer');
if( typeof($DebugLayer) != 'undefined' )
{
$isVisible = ($DebugLayer.style.display == 'none')?false:true;
if(!$isVisible&&$KeyCode==27) return false;
resizeDebugLayer(null);
$DebugLayer.style.display = $isVisible?'none':'block';
}
}
function prepareSizes($Prefix)
{
var $ret = '';
$ret = eval('document.body.'+$Prefix+'Top')+'; ';
$ret += eval('document.body.'+$Prefix+'Left')+'; ';
$ret += eval('document.body.'+$Prefix+'Height')+'; ';
$ret += eval('document.body.'+$Prefix+'Width')+'; ';
return $ret;
}
function resizeDebugLayer($e)
{
if(!$e) $e = window.event;
var $DebugLayer = document.getElementById('debug_layer');
var $TopMargin = 1;
if( typeof($DebugLayer) != 'undefined' )
{
$DebugLayer.style.top = parseInt(document.body.offsetTop + document.body.scrollTop) + $TopMargin;
$DebugLayer.style.height = document.body.clientHeight - $TopMargin - 5;
}
//window.parent.status = 'OFFSET: '+prepareSizes('offset')+' | SCROLL: '+prepareSizes('scroll')+' | CLIENT: '+prepareSizes('client');
//window.parent.status += 'DL Info: '+$DebugLayer.style.top+'; S.AH: '+screen.availHeight;
return true;
}
function SetClipboard(copyText)
{
if(window.clipboardData)
{
// IE send-to-clipboard method.
window.clipboardData.setData('Text', copyText);
}
else if (window.netscape)
{
// You have to sign the code to enable this or allow the action in about:config by changing user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
// Store support string in an object.
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
if (!str) return false;
str.data=copyText;
// Make transferable.
var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return false;
// Specify what datatypes we want to obtain, which is text in this case.
trans.addDataFlavor("text/unicode");
trans.setTransferData("text/unicode",str,copyText.length*2);
var clipid=Components.interfaces.nsIClipboard;
var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
function showProps($Obj, $Name)
{
var $ret = '';
for($Prop in $Obj)
{
$ret += $Name+'.'+$Prop+' = '+$Obj[$Prop]+"\n";
}
return $ret;
}
function editFile($fileName,$lineNo)
{
if(!document.all)
{
alert('Only works in IE');
return;
}
var $editorPath = '<?php echo defined('WINDOWS_EDITOR') ? addslashes(WINDOWS_EDITOR) : '' ?>';
if($editorPath)
{
var $obj = new ActiveXObject("LaunchinIE.Launch");
$editorPath = $editorPath.replace('%F',$fileName);
$editorPath = $editorPath.replace('%L',$lineNo);
$obj.LaunchApplication($editorPath);
}
else
{
alert('Editor path not defined!');
}
}
function toggleTraceArgs($ArgsLayerID)
{
var $ArgsLayer = document.getElementById($ArgsLayerID);
$ArgsLayer.style.display = ($ArgsLayer.style.display == 'none') ? 'block' : 'none';
}
document.onkeydown = keyProcessor;
window.onresize = resizeDebugLayer;
window.onscroll = resizeDebugLayer;
window.focus();
if( typeof($isFatalError) != 'undefined' && $isFatalError == 1 || <?php echo DBG_RAISE_ON_WARNINGS; ?> )
{
toggleDebugLayer();
}
if( typeof($isFatalError) != 'undefined' && $isFatalError == 1)
{
document.getElementById('debug_layer').scrollTop = 10000000;
}
</script>
<?php
$this->memoryUsage['debugger_finish']=memory_get_usage();
$this->memoryUsage['print_report']=$this->memoryUsage['debugger_finish']-$this->memoryUsage['debugger_start'];
$this->memoryUsage['total']=$this->memoryUsage['print_report']+$this->memoryUsage['error_handling'];
$this->memoryUsage['application']=memory_get_usage()-$this->memoryUsage['total'];
if($returnResult)
{
$ret = ob_get_contents();
ob_clean();
- if( ConstOn('DBG_SHOW_MEMORY_USAGE') ) $ret.=$this->getMemoryUsageReport();
+ if( dbg_ConstOn('DBG_SHOW_MEMORY_USAGE') ) $ret.=$this->getMemoryUsageReport();
return $ret;
}
else
{
ob_end_flush();
- if( ConstOn('DBG_SHOW_MEMORY_USAGE') ) echo $this->getMemoryUsageReport();
+ if( dbg_ConstOn('DBG_SHOW_MEMORY_USAGE') ) echo $this->getMemoryUsageReport();
}
}
/**
* Format's memory usage report by debugger
*
* @return string
* @access private
*/
function getMemoryUsageReport()
{
$info=Array('printReport'=>'print_report',
'saveError'=>'error_handling',
'Total'=>'total',
'<u>Application</u>'=>'application');
$ret=Array();
foreach($info as $title => $value_key)
{
$ret[]=$title.': <b>'.$this->formatSize($this->memoryUsage[$value_key]).'</b>';
}
return implode('<br>',$ret);
}
/**
* User-defined error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param array $errcontext
*/
function saveError($errno, $errstr, $errfile = '', $errline = '', $errcontext = '')
{
$memory_used=Array();
$memory_used['begin']=memory_get_usage();
$errorType = $this->getErrorNameByCode($errno);
if(!$errorType)
{
trigger_error('Unknown error type ['.$errno.']', E_USER_ERROR);
return false;
}
$long_id_pos=strrpos($errstr,'#');
if($long_id_pos!==false)
{
// replace short message with long one (due triger_error limitations on message size)
$long_id=substr($errstr,$long_id_pos+1,strlen($errstr));
$errstr=$this->longErrors[$long_id];
unset($this->longErrors[$long_id]);
}
if( strpos($errfile,'eval()\'d code') !== false )
{
$errstr = '[<b>EVAL</b>, line <b>'.$errline.'</b>]: '.$errstr;
$tmpStr = $errfile;
$pos = strpos($tmpStr,'(');
$errfile = substr($tmpStr,0,$pos);
$pos++;
$errline = substr($tmpStr,$pos,strpos($tmpStr,')',$pos)-$pos);
}
if($this->TraceNextError)
{
$this->appendTrace();
$this->TraceNextError=false;
}
$this->Data[] = Array('no' => $errno, 'str' => $errstr, 'file' => $errfile, 'line' => $errline, 'context' => $errcontext, 'debug_type' => 'error');
$memory_used['end']=memory_get_usage();
$this->memoryUsage['error_handling']+=$memory_used['end']-$memory_used['begin'];
if( substr($errorType,0,5) == 'Fatal')
{
echo '<script language="javascript">var $isFatalError = 1;</script>';
exit;
}
}
function saveToFile($msg)
{
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/vb_debug.txt', 'a');
fwrite($fp,$msg."\n");
fclose($fp);
}
/**
* Formats file/memory size in nice way
*
* @param int $bytes
* @return string
* @access public
*/
function formatSize($bytes)
{
if ($bytes >= 1099511627776) {
$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "TB";
} elseif ($bytes >= 1073741824) {
$return = round($bytes / 1024 / 1024 / 1024, 2);
$suffix = "GB";
} elseif ($bytes >= 1048576) {
$return = round($bytes / 1024 / 1024, 2);
$suffix = "MB";
} elseif ($bytes >= 1024) {
$return = round($bytes / 1024, 2);
$suffix = "KB";
} else {
$return = $bytes;
$suffix = "Byte";
}
$return .= ' '.$suffix;
return $return;
}
}
if( !function_exists('memory_get_usage') )
{
function memory_get_usage(){ return -1; }
}
- function ConstOn($const_name)
+ function dbg_ConstOn($const_name)
{
return defined($const_name)&&constant($const_name);
}
- $debugger = new Debugger();
- if(ConstOn('DBG_HANDLE_ERRORS')) set_error_handler( array(&$debugger,'saveError') );
- if(ConstOn('DBG_USE_SHUTDOWN_FUNC')) register_shutdown_function( array(&$debugger,'printReport') );
+ function dbg_safeDefine($const_name,$const_value)
+ {
+ if(!defined($const_name)) define($const_name,$const_value);
+ }
+ $debugger = new Debugger();
+ if(dbg_ConstOn('DBG_HANDLE_ERRORS')) set_error_handler( array(&$debugger,'saveError') );
+ if(dbg_ConstOn('DBG_USE_SHUTDOWN_FUNC')) register_shutdown_function( array(&$debugger,'printReport') );
?>
\ No newline at end of file
Property changes on: trunk/kernel/include/debugger.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.23
\ No newline at end of property
+1.24
\ No newline at end of property

Event Timeline