Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sun, Feb 2, 2:55 AM

in-portal

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: trunk/kernel/include/emailmessage.php
===================================================================
--- trunk/kernel/include/emailmessage.php (revision 700)
+++ trunk/kernel/include/emailmessage.php (revision 701)
@@ -1,962 +1,964 @@
<?php
class clsEmailMessage extends clsParsedItem
{
var $Event = "";
var $Item;
var $headers = array();
var $subject = "";
var $body = "";
var $TemplateParsed = FALSE;
var $recipient = NULL;
var $fromuser = NULL;
function clsEmailMessage($MessageId=NULL,$Item=NULL)
{
$this->clsParsedItem();
$this->tablename = GetTablePrefix()."EmailMessage";
$this->Item = $Item;
$this->BasePermission = "EMAIL";
$this->id_field = "EmailMessageId";
$this->TagPrefix = "email";
$this->NoResourceId=1;
if($MessageId)
$this->LoadFromDatabase($MessageId);
}
function LoadEvent($event,$language=NULL)
{
global $objConfig, $objLanguages;
if(!strlen($language))
$language = $objLanguages->GetPrimary();
$sql = "SELECT * FROM ".$this->tablename." WHERE EventId = $event AND LanguageId=$language";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$this->SetFromArray($data);
$this->Clean();
return TRUE;
}
else
return FALSE;
}
function LoadFromDatabase($MessageId)
{
global $Errors;
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$MessageId);
$result = $this->adodbConnection->Execute($sql);
if ($result === FALSE)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return FALSE;
}
$data = $result->fields;
$this->SetFromArray($data);
return TRUE;
}
function EditTemplate()
{
}
/* read the template, split into peices */
function ReadTemplate()
{
if(!$this->TemplateParsed)
{
$this->headers = array();
$lines = explode("\n",$this->Get("Template"));
$header_end = FALSE;
$i = 0;
while(!$header_end && $i<count($lines))
{
$h = $lines[$i];
if(strlen(trim($h))==0 || ($h=="."))
{
$header_end = TRUE;
}
else
{
$parts = explode(":",$h,2);
if(strtolower($parts[0])=="subject")
{
$this->subject = $h;
}
else
$this->headers[] = $h;
}
$i++;
}
while($i<count($lines))
{
$this->body .= $lines[$i++];
}
$this->TemplateParsed=TRUE;
}
}
function ParseSection($text, $parser=null)
{
global $objUsers, $objTemplate;
$res = $this->ParseTemplateText($text);
/* parse email class tags */
if(!is_object($this->fromuser))
{
$this->fromuser = $objUsers->GetItem($this->Get("FromUserId"));
$this->fromuser->TagPrefix = "fromuser";
}
/* parse from user object */
if(is_object($this->fromuser))
{
$res = $this->fromuser->ParseTemplateText($res);
}
/* parse recipient user object */
if(is_object($this->recipient))
{
$res = $this->recipient->ParseTemplateText($res);
}
//print_pre($this->Item);
if(is_object($this->Item))
{
$res = $this->Item->ParseTemplateText($res);
}
else
{
if(!is_object($objTemplate))
$objTemplate = new clsTemplateList(" ");
$res = $objTemplate->ParseTemplateText($res);
}
return $res;
}
function SendToGroup($GroupId)
{
global $objUsers;
$users = $objUsers->Query_GroupPortalUser("GroupId=$GroupId");
if(is_array($users))
{
foreach($users as $u)
{
$this->SendToUser($u->Get("PortalUserId"));
}
}
}
function SendToAddress($EmailAddress,$name="")
{
global $objUsers, $objEmailQueue,$objConfig;
$conn = &GetADODBConnection();
//$this->recipient = $objUsers->GetUser($UserId);
//$this->recipient->TagPrefix="touser";
if(strlen($EmailAddress))
{
$to_addr = $EmailAddress;
$this->ReadTemplate();
$subject = $this->ParseSection($this->subject);
$body = $this->ParseSection($this->body);
if(is_object($this->fromuser))
{
$FromAddr = $this->fromuser->Get("Email");
$FromName = trim($this->fromuser->Get("FirstName")." ".$this->fromuser->Get("LastName"));
}
if(!strlen($FromAddr))
{
$FromName = $objConfig->Get("Site_Name");
$FromAddr = $objConfig->Get("Smtp_AdminMailFrom");
}
$charset = "ascii-us";
if($this->Get("MessageType")=="html")
{
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,"",$body,$charset, $this->Get("Event"),NULL,$this->headers);
}
else
{
$body = nl2br($body);
$body = str_replace("<br />","\n",$body);
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,$body,"",$charset, $this->Get("Event"),NULL,$this->headers);
}
/*$time = time();
$sql = "INSERT INTO ".GetTablePrefix()."EmailLog VALUES ('', '$FromName', '$To', '$subject', $time, '')";
$conn->Execute($sql); */
return TRUE;
}
return FALSE;
}
function SendToUser($UserId)
{
global $objUsers, $objEmailQueue, $objConfig;
$conn = &GetADODBConnection();
//echo "Handling Event ".$this->Get("Event")." for user $UserId <br>\n";
$this->recipient = new clsPortalUser($UserId); // $objUsers->GetItem($UserId);
//echo "<PRE>";print_r($this->recipient); echo "</PRE>";
$this->recipient->TagPrefix="touser";
if($this->recipient->Get("PortalUserId")==$UserId)
{
$to_addr = $this->recipient->Get("Email");
$To = trim($this->recipient->Get("FirstName")." ".$this->recipient->Get("LastName"));
$this->ReadTemplate();
$subject = $this->ParseSection($this->subject, $this->recipient);
$body = $this->ParseSection($this->body);
if(!is_object($this->fromuser))
{
$this->fromuser = $objUsers->GetItem($this->Get("FromUserId"));
}
if(is_object($this->fromuser))
{
$FromAddr = $this->fromuser->Get("Email");
$FromName = trim($this->fromuser->Get("FirstName")." ".$this->fromuser->Get("LastName"));
$charset = "ascii-us";
}
if(!strlen($FromAddr))
{
$FromName = $objConfig->Get("Site_Name");
$FromAddr = $objConfig->Get("Smtp_AdminMailFrom");
}
echo $this->Event;
if($this->Get("MessageType")=="html")
{
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,"",$body,$charset, $this->Get("Event"),NULL,$this->headers);
}
else
{
$body = nl2br($body);
$body = str_replace("<br />","\n",$body);
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,$body,"",$charset, $this->Get("Event"),NULL,$this->headers);
}
/*$time = time();
$sql = "INSERT INTO ".GetTablePrefix()."EmailLog VALUES ('', '$FromName', '$To ($to_addr)', '$subject', $time, '')";
$conn->Execute($sql); */
return TRUE;
}
return FALSE;
}
function SendAdmin()
{
global $objUsers, $objConfig, $objEmailQueue;
$conn = &GetADODBConnection();
$this->recipient = $objUsers->GetUser($this->Get("FromUserId"));
$this->recipient->TagPrefix="touser";
if($this->recipient->Get("PortalUserId")==$this->Get("FromUserId"))
{
$to_addr = $this->recipient->Get("Email");
$To = trim($this->recipient->Get("FirstName")." ".$this->recipient->Get("LastName"));
$this->ReadTemplate();
$subject = $this->ParseSection($this->subject);
$body = $this->ParseSection($this->body);
$FromName = "System Event";
$FromAddr = $objConfig->Get("Smtp_AdminMailFrom");
if(strlen($FromAddr))
{
$charset = "ascii-us";
if($this->Get("MessageType")=="html")
{
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,"",$body,$charset,$this->Get("Event"),NULL,$this->headers);
}
else
{
$body=nl2br($body);
$body = str_replace("<br />","\n",$body);
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,$body,"",$charset, $this->Get("Event"),NULL,$this->headers);
}
/* $time = time();
$sql = "INSERT INTO ".GetTablePrefix()."EmailLog VALUES ('', '$FromName', '$To ($to_addr)', '$subject', $time, '')";
$conn->Execute($sql);
*/
return TRUE;
}
}
return FALSE;
}
function ParseTemplateText($text)
{
$html = $text;
$search = "<inp:";
//$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 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
{
if (is_object($this->Item)) {
$this->Item->TagPrefix = $tag->name;
$output = $this->Item->ParseObject($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 "";
}
}
class clsEmailMessageList extends clsItemCollection
{
function clsEmailMessageList()
{
$this->clsItemCollection();
$this->classname = "clsEmailMessage";
$this->SourceTable = GetTablePrefix()."EmailMessage";
$this->PerPageVar = "Perpage_EmailEvents";
$this->AdminSearchFields = array("Template","Description", "Module","Event");
}
function LoadLanguage($LangId=NULL)
{
global $objLanguages;
if(!$LangId)
$LangId = $objLanguages->GetPrimary();
$sql = "SELECT * FROM ".$this->SourceTable." WHERE LanguageId=$LangId";
$this->Clear();
return $this->Query_Item($sql);
}
function &AddEmailEvent($Template, $Type, $LangId, $EventId)
{
$e = new clsEmailMessage();
$e->tablename = $this->SourceTable;
$e->Set(array("Template","MessageType","LanguageId","EventId"),
array($Template,$Type,$LangId,$EventId));
$e->Dirty();
$e->Create();
return $e;
}
function DeleteLanguage($LangId)
{
$sql = "DELETE FROM ".$this->SourceTable." WHERE LanguageId=$LangId OR LanguageId = 0";
if( $GLOBALS['debuglevel'] ) echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
}
function &GetMessage($EventId,$LangId,$LoadFromDB=TRUE)
{
$found=FALSE;
if(is_array($this->Items))
{
for($x=0;$x<count($this->Items);$x++)
{
$i =& $this->GetItemRefByIndex($x);
if(is_object($i))
{
if($i->Get("EventId")==$EventId && $i->Get("LanguageId")==$LangId)
{
$found=TRUE;
break;
}
}
}
}
if(!$found)
{
if($LoadFromDB)
{
$n = NULL;
$n = new $this->classname();
$n->tablename = $this->SourceTable;
if($n->LoadEvent($EventId,$LangId))
{
array_push($this->Items, $n);
$i =& $this->Items[count($this->Items)-1];
}
else
$i = FALSE;
}
else
$i = FALSE;
}
return $i;
}
function CreateEmptyEditTable($IdList, $use_parent = false)
{
global $objSession;
if (!$use_parent) {
$edit_table = $objSession->GetEditTable($this->SourceTable);
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
- $query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield = -1";
+ $query = "SELECT * FROM ".$this->SourceTable." WHERE 0";
$insert = "CREATE TABLE ".$edit_table." ".$query;
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
$this->adodbConnection->Execute($insert);
$this->LoadLanguage();
$idvalue = -1;
for($i=0;$i<$this->NumItems();$i++)
{
$e =& $this->Items[$i];
$e->SourceTable = $edit_table;
if(is_array($IdList))
{
foreach($IdList as $id)
{
$e->UnsetIdField();
$e->Set("EmailMessageId",$idvalue--);
$e->Set("LanguageId",$id);
- $e->Set("Description",admin_language("la_desc_emailevent_".$e->Get("Event"),$id));
+// $e->Set("Description",admin_language("la_desc_emailevent_".$e->Get("Event"),$id));
$e->Create();
}
}
else
{
$e->UnsetIdField();
$e->Set("EmailMessageId",$idvalue--);
$e->Set("LanguageId",$IdList);
- $e->Set("Description",admin_language("la_desc_emailevent_".$e->Get("Event"),$LangId));
+// $e->Set("Description",admin_language("la_desc_emailevent_".$e->Get("Event"),$LangId));
$e->Create();
}
}
$this->Clear();
}
else {
parent::CreateEmptyEditTable($IdList);
}
}
function CopyFromEditTable()
{
global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
$idfield = "EmailMessageId";
$edit_table = $objSession->GetEditTable($this->SourceTable);
$sql = "SELECT * FROM $edit_table WHERE LanguageId <> 0";
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = new $this->classname;
$c->SetFromArray($data);
//$c->idfield = $idfield;
if($c->Get($idfield)<1)
{
$old_id = $c->Get($idfield);
$c->Dirty();
$c->UnsetIdField();
$c->Create();
}
else
{
$c->Dirty();
$c->Update();
}
$rs->MoveNext();
}
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
+ unset($GLOBALS['_CopyFromEditTable']);
}
function PurgeEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function &GetEmailEventObject($EventName,$Type=0,$LangId=NULL)
{
global $objLanguages;
if(!$LangId)
$LangId = $objLanguages->GetPrimary();
$EmailTable = $this->SourceTable;
$EventTable = GetTablePrefix()."Events";
$sql = "SELECT * FROM $EventTable INNER JOIN $EmailTable ON ($EventTable.EventId = $EmailTable.EventId) ";
$sql .="WHERE Event='$EventName' AND LanguageId=$LangId AND Type=$Type";
$result = $this->adodbConnection->Execute($sql);
if ($result === FALSE)
{
//$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"","clsEvent","GetEmailEventObject");
return FALSE;
}
$data = $result->fields;
$e = new clsEmailMessage();
$e->SetFromArray($data);
$e->Clean();
return $e;
}
function ReadImportTable($TableName,$Overwrite=FALSE, $MaxInserts=100,$Offset=0)
{
$eml = new clsEmailMessageList();
$this->Clear();
$Inserts = 0;
$sql = "SELECT * FROM $TableName LIMIT $Offset,$MaxInserts";
$this->Query_Item($sql);
if($this->NumItems()>0)
{
foreach($this->Items as $i)
{
$e = $eml->GetMessage($i->Get("EventId"),$i->Get("LanguageId"));
if(is_object($e))
{
if($Overwrite)
{
$e->Set("MessageType",$i->Get("MessageType"));
$e->Set("Template",$i->Get("Template"));
$e->Update();
}
}
else
{
$i->Create();
}
$Inserts++;
}
}
$Offset = $Offset + $Inserts;
return $Offset;
}
}
function EventEnabled($e)
{
global $objConfig;
$var = "Email_".$e."_Enabled";
return ($objConfig->Get($var)=="1");
}
class clsEmailQueue
{
var $SourceTable;
var $MessagesAtOnce;
var $MessagesSent=0;
var $LogLevel = 0;
function clsEmailQueue($SourceTable=NULL,$MessagesAtOnce=NULL)
{
global $objConfig;
if($SourceTable)
{
$this->SourceTable=$SourceTable;
}
else
$this->SourceTable = GetTablePrefix()."EmailQueue";
if(!$MessagesAtOnce)
$MessagesAtOnce = (int)$objConfig->Get("Email_MaxSend");
if($MessagesAtOnce<1)
$MessagesAtOnce=1;
$this->MessagesAtOnce = $MessagesAtOnce;
$this->LogLevel = (int)$objConfig->Get("Smtp_LogLevel");
}
function WriteToMailLog($text)
{
global $pathtoroot,$admin;
//echo htmlentities($text)."<br>\n";
if($this->LogLevel>0)
{
$Logfile = $pathtoroot.$admin."/email/log.txt";
if(is_writable($Logfile))
{
$fp = fopen($Logfile,"a");
if($fp)
{
fputs($fp,$text."\n");
fclose($fp);
}
}
}
}
function AllowSockets()
{
$minver = explode(".", "4.3.0");
$curver = explode(".", phpversion());
if (($curver[0] < $minver[0])
|| (($curver[0] == $minver[0])
&& ($curver[1] < $minver[1]))
|| (($curver[0] == $minver[0]) && ($curver[1] == $minver[1])
&& ($curver[2][0] < $minver[2][0])))
return false;
else
return true;
}
function DeliverMail($To,$From,$Subject,$Msg,$headers, $ForceSend=0)
{
global $MessagesSent,$objConfig;
if(($this->MessagesSent >$this->MessagesAtOnce) && !$ForceSend)
{
$this->EnqueueMail($To,$From,$Subject,$Msg,$headers);
return TRUE;
}
else
{
$this->MessagesSent++;
$time = time();
$conn = &GetADODBConnection();
/* $sql = "INSERT INTO ".GetTablePrefix()."EmailLog VALUES ('', '".htmlspecialchars($From)."', '".htmlspecialchars($To)."', '$Subject', $time, '')";
$conn->Execute($sql);*/
/* ensure headers are using \r\n instead of \n */
//$headers = str_replace("\r\n","\n",$headers);
//$headers = str_replace("\n","\r\n",$headers);
$headers = "Date: ".date("r")."\n".$headers;
$headers = "Return-Path: ".$objConfig->Get("Smtp_AdminMailFrom")."\n".$headers;
if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')) {
$Msg = str_replace("\r\n","\n",$Msg);
$Msg = str_replace("\n","\r\n",$Msg);
}
//echo "<PRE>"; print_r(htmlentities($headers)); echo "</PRE>";
//echo "<PRE>"; print_r(htmlentities($Msg)); echo "</PRE>";
$ver = phpversion();
if(substr($Subject,0,9)=="Subject: ")
$Subject = substr($Subject,9);
if(!strlen($objConfig->Get("Smtp_Server")) || !$this->AllowSockets())
{
return mail($To,trim($Subject),$Msg, $headers);
}
$headers = "Subject: ".trim($Subject)."\r\n".$headers;
$send_params['recipients'] = array($To); // The recipients (can be multiple)
$send_params['from'] = $From; // This is used as in the MAIL FROM: cmd
$send_params['headers'] = explode("\r\n",$headers);
// It should end up as the Return-Path: header
$send_params['body'] = $Msg; // The body of the email
$params['host'] = $objConfig->Get("Smtp_Server"); // The smtp server host/ip
$params['port'] = 25; // The smtp server port
$params['hello'] = 'INPORTAL'; // What to use when sending the helo command. Typically, your domain/hostname
if($objConfig->Get("Smtp_Authenticate")) // Whether to use basic authentication or not
{
$params['auth'] = TRUE;
$params['user'] = $objConfig->Get("Smtp_User");
$params['pass'] = $objConfig->get("Smtp_Pass");
}
else
$params['auth'] = FALSE;
$this->LogLevel=0;
$SmtpServer = new smtp($params);
if($this->LogLevel>0)
{
$SmtpServer->debug=1;
foreach($params as $key=>$value)
{
$this->WriteToMailLog($key."=".$value);
}
}
else
$SmtpServer->debug = 1;
$connected = $SmtpServer->connect();
if($connected)
{
if($this->LogLevel>1)
{
$this->WriteToMailLog("Connected to ".$params['host']);
}
$res = $SmtpServer->send($send_params);
}
$SmtpServer->disconnect();
if($this->LogLevel>1)
{
foreach($SmtpServer->buffer as $l)
{
$this->WriteToMailLog($l);
}
}
if($this->LogLevel>0)
{
if(count($SmtpServer->errors)>0)
{
foreach($SmtpServer->errors as $e)
{
$this->WriteToMailLog($e);
}
}
else
$this->WriteToMailLog("Message to $From Delivered Successfully");
}
unset($SmtpServer);
return $res;
}
}
function EnqueueMail($To,$From,$Subject,$Msg,$headers)
{
global $objSession;
$ado = &GetADODBConnection();
$To = mysql_escape_string($To);
$From = mysql_escape_string($From);
$Msg = mysql_escape_string($Msg);
$headers = mysql_escape_string($headers);
$Subject = mysql_escape_string($Subject);
$sql = "INSERT INTO ".$this->SourceTable." (toaddr,fromaddr,subject,message,headers) VALUES ('$To','$From','$Subject','$Msg','$headers')";
$ado->Execute($sql);
}
function SendMailQeue()
{
global $objConfig, $objSession, $TotalMessagesSent;
$ado = &GetADODBConnection();
$MaxAllowed = $this->MessagesAtOnce;
$del_sql = array();
$NumToSend = $MaxAllowed - $this->MessagesSent;
$sql = "SELECT * FROM ".$this->SourceTable." ORDER BY queued ASC LIMIT $NumToSend";
$rs = $ado->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$this->DeliverMail($data["toaddr"],$data["fromaddr"],$data["Subject"],$data["headers"],$data["message"],1);
$del_sql[] = "DELETE FROM ".$this->SourceTable." WHERE queued=".$data["queued"];
$rs->MoveNext();
}
$numdel = count($del_sql);
for($i=0;$i<$numdel;$i++)
{
$sql = $del_sql[$i];
if(strlen($sql))
$ado->Execute($sql);
if($objSession->HasSystemPermission("DEBUG.ITEM"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
}
}
function SendMail($From, $FromName, $ToAddr, $ToName, $Subject, $Text, $Html, $charset, $SendEvent,
$FileName="",$FileLoc="",$QueueOnly=0,$extra_headers = array())
{
$HasFile = FALSE;
$HasFile = (strlen($FileName)>0);
$OB="----=_OuterBoundary_000";
$boundary = "-----=".md5( uniqid (rand()));
$f = "\"$FromName\" <".$From.">";
$headers = "From: $f\n";
$headers .= "MIME-Version: 1.0\n";
$conn = &GetADODBConnection();
$time = time();
$sendTo = $ToName;
if (strlen($sendTo) > 0) {
$sendTo .= "($ToAddr)";
}
else {
$sendTo = $ToAddr;
}
$sql = "INSERT INTO ".GetTablePrefix()."EmailLog VALUES ('', '$FromName', '$sendTo', '".str_replace("Subject:", "", $Subject)."', $time, '$SendEvent')";
$conn->Execute($sql);
if($HasFile)
{
//Messages start with text/html alternatives in OB
$headers.="Content-Type: multipart/mixed;\n\tboundary=\"".$OB."\"\n\n";
$msg.="--".$OB."\n";
$msg.="Content-Type: multipart/alternative; boundary=\"$boundary\"\n\n";
}
else
$headers .= "Content-Type: multipart/alternative; boundary=\"$boundary\"";
if(is_array($extra_headers))
{
for($i=0;$i<count($extra_headers);$i++);
{
$headers .= $extra_headers[$i]."\n";
}
}
$msg .="This is a multi-part message in MIME format.\n\n";
$msg .= "--" . $boundary . "\n";
$msg .= "Content-Type: text/plain; charset=\"$charset\"\r\n";
$msg .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$msg .= stripslashes($Text);
$msg .= "\r\n\r\n";
if(strlen($Html)>0)
{
$msg .= "--" . $boundary . "\n";
$msg .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$msg .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$msg .= stripslashes($Html);
$msg .= "\r\n\r\n";
}
$msg .= "--" . $boundary . "--\n";
if($HasFile)
{
if(!strlen($FileLoc))
$FileLoc = $FileName;
$FileName = basename($FileName);
$msg .= "\n--".$OB."\n";
$msg.="Content-Type: application/octetstream;\n\tname=\"".$FileName."\"\r\n";
$msg.="Content-Transfer-Encoding: base64\n";
$msg.="Content-Disposition: attachment;\n\tfilename=\"".$FileName."\"\r\n\r\n";
//file goes here
$fd=fopen ($FileLoc, "r");
if($fd)
{
$FileContent=fread($fd,filesize($FileLoc));
fclose ($fd);
}
$FileContent=chunk_split(base64_encode($FileContent));
$msg.=$FileContent;
$msg .= "--".$OB."\n";
}
if(strlen($ToName)>0)
{
$To = "\"$ToName\" <$ToAddr>";
}
else {
$To = "<".$ToAddr.">";
}
//$headers.="To: $To\r\n";
if($this->MessagesSent>$this->MessagesAtOnce || $QueueOnly==1)
{
$this->EnqueueMail($ToAddr,$From,$Subject,$msg,$headers);
}
else
{
$this->DeliverMail($ToAddr,$From,$Subject,$msg,$headers);
}
}
}
?>
Property changes on: trunk/kernel/include/emailmessage.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.36
\ No newline at end of property
+1.37
\ No newline at end of property
Index: trunk/kernel/include/parseditem.php
===================================================================
--- trunk/kernel/include/parseditem.php (revision 700)
+++ trunk/kernel/include/parseditem.php (revision 701)
@@ -1,2959 +1,2961 @@
<?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())
{
if( isset($attribs["_tz"]) )
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = isset($attribs["_part"]) ? strtolower($attribs["_part"]) : '';
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if($d<=0)
{
$ret = "";
}
else
$ret = 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 "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 = $this->Get("CachedNavbar");
if(!strlen($ret))
{
if(is_numeric($this->Get("CategoryId")))
{
$c = $objCatList->GetItem($this->Get("CategoryId"));
if(is_object($c))
$ret = $c->Get("CachedNavbar");
}
else
{
if(method_exists($this,"GetPrimaryCategory"))
{
$cat = $this->GetPrimaryCategory();
$c = $objCatList->GetItem($cat);
if(is_object($c))
$ret = $c->Get("CachedNavbar");
}
}
}
// $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->attributes["_separator"];
}
}
break;
}
break;
case "reviews":
$today = FALSE;
if(method_exists($this,"ReviewCount"))
{
if($element->GetAttributeByName("_today"))
$today = TRUE;
$ret = $this->ReviewCount($today);
}
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->attributes["_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"];
$default = $element->attributes["_default"];
if (strlen($field))
$ret = $this->GetCustomFieldValue($field,$default);
}
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;
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;
}
function SendUserEventMail($EventName,$ToUserId,$LangId=NULL,$RecptName=NULL)
{
global $objMessageList,$FrontEnd;
$Event =& $objMessageList->GetEmailEventObject($EventName,0,$LangId);
if(is_object($Event))
{
if($Event->Get("Enabled")=="1" || ($Event->Get("Enabled")==2 && $FrontEnd))
{
$Event->Item = $this;
if(is_numeric($ToUserId))
{
return $Event->SendToUser($ToUserId);
}
else
return $Event->SendToAddress($ToUserId,$RecptName);
}
}
}
function SendAdminEventMail($EventName,$LangId=NULL)
{
global $objMessageList,$FrontEnd;
//echo "Firing Admin Event $EventName <br>\n";
$Event =& $objMessageList->GetEmailEventObject($EventName,1,$LangId);
if(is_object($Event))
{
if($Event->Get("Enabled")=="1" || ($Event->Get("Enabled")==2 && $FrontEnd))
{
$Event->Item = $this;
//echo "Admin Event $EventName Enabled <br>\n";
return $Event->SendAdmin($ToUserId);
}
}
}
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 = '';
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->tablename = $this->SourceTable;
return $this->Dummy;
}
function clsItemCollection()
{
$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)
{
$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);
$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)
{
$found=FALSE;
if(is_array($this->Items))
{
foreach($this->Items as $i)
{
if($i->Get($Field)==$Value)
{
$found = TRUE;
break;
}
}
}
if(!$found && $LoadFromDB==TRUE)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE $Field = '$Value'";
//echo $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;
//echo "Method QItem [<b>".get_class($this).'</b>], sql: ['.$sql.']<br>';
//if( get_class($this) == 'clsthemefilelist') trace();
$dummy =& $this->GetDummy();
if( !$dummy->TableExists() )
{
if($this->debuglevel) echo "ERROR: table <b>".$dummy->tablename."</b> missing.<br>";
$this->Clear();
return false;
}
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);
//echo "In Main <b>CopyFromEditTable</b> in class <b>".get_class($this).'</b><br>';
//echo $sql."<BR>";
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();
}
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"));
}
}
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);
}
}
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();
}
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']);
}
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 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)
{
global $objCatList;
$l =& $this->GetItem($Id);
$l->BasePermission=$this->BasePermission;
$l->DeleteCategoryItems($objCatList->CurrentCategoryID());
}
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 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, $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;
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()
{
// return category perpage
global $objConfig;
$PerPage = $objConfig->Get( $this->PerPageVar );
if( !is_numeric($PerPage) ) $PerPage = $this->DefaultPerPage ? $this->DefaultPerPage : 10;
return $PerPage;
}
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->Page > $NumPages)
{
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;
}
$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 = '')
{
global $objConfig, $var_list_update, $var_list;
$v= $this->PageEnvar;
global ${$v};
if(!strlen($page))
$page = GetIndexURL();
$PerPage = $objConfig->Get($this->PerPageVar);
if($PerPage<1)
$PerPage=20;
$NumPages = ceil($this->GetNumPages($PerPage));
if($NumPages==1 && $HideEmpty)
return "";
if(strlen($dest_template))
{
$var_list_update["t"] = $dest_template;
}
else
$var_list_update["t"] = $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 = $page."?env=".BuildEnv().$EnvSuffix;
$o .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
}
for($p=$StartPage;$p<=$EndPage;$p++)
{
if($p!=$this->Page)
{
${$v}[$this->PageEnvarIndex]=$p;
$href = $page."?env=".BuildEnv().$EnvSuffix;
$o .= " <A HREF=\"$href\">$p</A> ";
}
else
{
$o .= " <SPAN class=\"current-page\">$p</SPAN>";
}
}
if($EndPage<$NumPages && $EndPage>0)
{
${$v}[$this->PageEnvarIndex]=$this->Page+$PagesToList;
$next_url = $page."?env=".BuildEnv().$EnvSuffix;
$o .= "<A HREF=\"$next_url\"> &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
// 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>';
}
unset( $update[$this->PageEnvarIndex] );
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);
if(strlen($FieldVarData)>0)
{
$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ".
$objSession->GetPersistantVariable($OrderVar));
}
}
}
}
if(count($Orders)>0)
{
$OrderBy = "ORDER BY ".implode(", ",$Orders);
}
else
$OrderBy="";
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) ";
}
else
$sql .=") ";
}
else
$sql .="WHERE ($CatTable.CategoryId=".$cat." AND $t.Status=1) ";
if($attribs["_today"])
{
$today = mktime(0,0,0,date("m"),date("d"),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;
$p = $this->BasePermission.".VIEW";
$t = $this->SourceTable;
if($attribs["_today"])
{
$today = mktime(0,0,0,date("m"),date("d"),date("Y"));
$where = "($t.CreatedOn>=$today)";
}
if($attribs["_grouponly"])
{
$GroupList = $objSession->Get("GroupList");
}
else
$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)$attribs["_today"], 3600);
if(!is_numeric($cc))
{
$sql = $this->SqlGlobalCount($attribs);
$ret = QueryCount($sql);
$objCountCache->SetValue($this->CacheListType("_"),$this->ItemType,$this->CacheListExtraId("_"),(int)$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;
}
function CacheListType($ListType)
{
if(!strlen($ListType))
$ListType="_";
switch($ListType)
{
case "_":
$ListTypeId = 0;
break;
case "category":
$ListTypeId = 1;
break;
case "myitems":
$ListTypeId = 2;
break;
case "hot":
$ListTypeId = 3;
break;
case "pop":
$ListTypeId = 4;
break;
case "pick":
$ListTypeId = 5;
break;
case "favorites":
$ListTypeId = 6;
break;
case "new":
$ListTypeId = 8;
break;
}
return $ListTypeId;
}
function PerformItemCount($attribs=array())
{
global $objCountCache, $objSession;
$ret = "";
$ListType = $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(strlen($sql))
{
if(is_numeric($ListTypeId))
{
$cc = $objCountCache->GetValue($ListTypeId,$this->ItemType,$ExtraId,(int)$attribs["_today"], 3600);
if(!is_numeric($cc) || $attribs['_nocache'] == 1)
{
$ret = QueryCount($sql);
$objCountCache->SetValue($ListTypeId,$this->ItemType,$ExtraId,(int)$attribs["_today"],$ret);
}
else
$ret = $cc;
}
else
$ret = QueryCount($sql);
}
return $ret;
}
function GetJoinedSQL($PermName, $CatId=NULL, $AdditionalWhere="")
{
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) ";
$sql .="WHERE ($acl AND PermId=$VIEW AND PrimaryCat=1 AND $CategoryTable.Status=1) ";
if(is_numeric($CatId))
{
$sql .= " AND ($CategoryTable.CategoryId=$CatId) ";
}
if(strlen($AdditionalWhere)>0)
{
$sql .= "AND (".$AdditionalWhere.")";
}
return $sql;
}
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 = mktime(0,0,0,date("m"),date("d"),date("Y"));
$where = "PortalUserId=".$objSession->Get("PortalUserId")." AND $ltable.Status=1";
$where .= " AND $favtable.Modified >= $today AND ItemTypeId=".$this->ItemType;
$p = $this->BasePermission.".VIEW";
$sql = "SELECT $ltable.*,$CategoryTable.CategoryId,$CategoryTable.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 = mktime(0,0,0,date("m"),date("d"),date("Y"));
$where .= " AND $favtable.Modified >= $today AND ItemTypeId=".$this->ItemType;
}
$p = $this->BasePermission.".VIEW";
$sql = "SELECT $ltable.*,$CategoryTable.CategoryId,$CategoryTable.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;
$sql = $this->SqlFavorites($attribs);
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
if($attribs["_shortlist"])
{
$this->PerPageVar = $this->PerPageShortVar;
}
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)$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.".EditorsPick=1 AND ".$TableName.".Status=1";
}
else
{
$where = $TableName.".EditorsPick=1 AND ".$TableName.".Status=1 ";
$catid=NULL;
}
if($attribs["_today"])
{
$today = mktime(0,0,0,date("m"),date("d"),date("Y"));
$where .= " AND ($TableName.CreatedOn>=$today)";
}
$CategoryTable = GetTablePrefix()."Category";
$sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName ";
$p = $this->BasePermission.".VIEW";
$sql .= $this->GetJoinedSQL($p,$CatUd,$where);
$OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
$sql .= " ".$OrderBy;
return $sql;
}
function LoadPickItems($attribs)
{
global $objSession, $objCountCache;
$sql = $this->SqlPickItems($attribs);
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
if($attribs["_shortlist"])
{
$this->PerPageVar = $this->PerPageShortVar;
}
else
$this->PerPageVar = $this->PerPageVarLong;
$CachedCount = $objCountCache->GetValue($this->CacheListType("pick"),$this->ItemType,$this->CacheListExtraId("pick"),(int)$attribs["_today"],3600);
if(!is_numeric($CachedCount))
{
$this->QueryItemCount= QueryCount($sql);
$objCountCache->SetValue($this->CacheListType("pick"),$this->ItemType,$this->CacheListExtraId("pick"),(int)$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($attribs["_today"])
{
$today = mktime(0,0,0,date("m"),date("d"),date("Y"));
$where .= " AND ($TableName.CreatedOn>=$today)";
}
$CategoryTable = GetTablePrefix()."Category";
$sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName ";
$p = $this->BasePermission.".VIEW";
$sql .= $this->GetJoinedSQL($p,$CatUd,$where);
$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"])
{
$this->PerPageVar = $this->PerPageShortVar;
}
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)$attribs["_catid"];
$scope = (int)$attribs["_scope"];
//$JoinCats = (int)$attribs["_catinfo"] || $scope;
$TableName = $this->SourceTable;
if($attribs["_today"])
{
$cutoff = mktime(0,0,0,date("m"),date("d"),date("Y"));
}
else
{
if($scope)
{
if (!$catid)
{
$catid = $objCatList->CurrentCategoryID();
}
$cutoff = $this->GetNewValue($catid);
}
else
$cutoff = $this->GetNewValue();
}
if($scope)
{
if (!$catid)
{
$catid = $objCatList->CurrentCategoryID();
}
$where = "CategoryId =".$catid." AND ((".$TableName.".CreatedOn >=".$cutoff." AND ".$TableName.".NewItem != 0) OR ".$TableName.".NewItem=1 ) 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";
$sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName ";
$p = $this->BasePermission.".VIEW";
$sql .= $this->GetJoinedSQL($p,$CatUd,$where);
$OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
$sql .= " ".$OrderBy;
return $sql;
}
function LoadNewItems($attribs)
{
global $objSession,$objCountCache;
$sql = $this->SqlNewItems($attribs);
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
if($attribs["_shortlist"])
{
$this->PerPageVar = $this->PerPageShortVar;
}
else
$this->PerPageVar = $this->PerPageVarLong;
$CachedCount = $objCountCache->GetValue($this->CacheListType("new"),$this->ItemType,$this->CacheListExtraId("new"),(int)$attribs["_today"],3600);
if(!is_numeric($CachedCount))
{
$this->QueryItemCount= QueryCount($sql);
$objCountCache->SetValue($this->CacheListType("new"),$this->ItemType,$this->CacheListExtraId("new"),(int)$attribs["_today"],$this->QueryItemCount);
}
else
$this->QueryItemCount=$CachedCount;
return $this->Query_Item($sql);
}
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 = mktime(0,0,0,date("m"),date("d"),date("Y"));
$where .= " AND ($TableName.CreatedOn>=$today)";
}
$CategoryTable = GetTablePrefix()."Category";
$sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.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"])
{
$this->PerPageVar = $this->PerPageShortVar;
}
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 = mktime(0,0,0,date("m"),date("d"),date("Y"));
$where .= " AND ($TableName.CreatedOn>=$today)";
}
$CategoryTable = GetTablePrefix()."Category";
$sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.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"])
{
$this->PerPageVar = $this->PerPageShortVar;
}
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();
$sql = "SELECT $cattable.CategoryId,$cattable.CachedNavbar,$ltable.*, Relevance FROM $stable ";
$sql .= "INNER JOIN $ltable ON ($stable.ItemId=$ltable.".$i->id_field.") ";
$where = "ItemType=".$this->ItemType." AND $ltable.Status=1";
$sql .= $this->GetJoinedSQL($p,NULL,$where);
$sql .= " ORDER BY EdPick DESC,Relevance DESC ";
$tmp = $this->QueryOrderByClause(FALSE,TRUE,TRUE);
$tmp = substr($tmp,9);
if(strlen($tmp))
{
$sql .= ", ".$tmp." ";
}
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;
}
}
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);
}
}
}
}
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: trunk/kernel/include/parseditem.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.37
\ No newline at end of property
+1.38
\ No newline at end of property
Index: trunk/kernel/include/events.php
===================================================================
--- trunk/kernel/include/events.php (revision 700)
+++ trunk/kernel/include/events.php (revision 701)
@@ -1,99 +1,101 @@
<?php
class clsEvent extends clsItemDB
{
function clsEvent($EventId = NULL)
{
$this->clsItemDB();
$this->tablename = GetTablePrefix()."Events";
$this->id_field = "EventId";
$this->NoResourceId=1;
$this->debuglevel=0;
if($EventId)
{
$this->LoadFromDatabase($EventId);
}
}
function LoadFromDatabase($Id)
{
global $Errors;
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === FALSE)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return FALSE;
}
$data = $result->fields;
$this->SetFromArray($data);
$this->Clean();
return TRUE;
}
}
class clsEventList extends clsItemCollection
{
function clsEventList()
{
$this->clsItemCollection();
$this->classname="clsEvent";
$this->SourceTable = GetTablePrefix()."Events";
$this->PerPageVar = "Perpage_Events";
$this->AdminSearchFields = array("Description", "Module","Event","u.Login");
}
function CopyFromEditTable()
{
global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
$sql = "SELECT * FROM $edit_table";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
if($data["EventId"]>0)
{
$c->Update();
}
$rs->MoveNext();
}
+ unset($GLOBALS['_CopyFromEditTable']);
}
function PurgeEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function &GetEmailEventObject($EventName,$LangId=NULL)
{
global $objLanguages;
if(!$LangId)
$LangId = $objLanguages->GetPrimary();
$EmailTable = GetTablePrefix()."EmailMessage";
$EventTable = $this->SourceTable;
$sql = "SELECT * FROM $EventTable INNER JOIN $EmailTable ON ($EventTable.EventId = $EmailTable.EventId) ";
$sql .="WHERE Event='$EventName' AND LanguageId=$LangId";
$result = $this->adodbConnection->Execute($sql);
if ($result === FALSE)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"GetEmailEventObject");
return FALSE;
}
$data = $result->fields;
$e = new clsEmailMessage();
$e->SetFromArray($data);
$e->Clean();
return $e;
}
}
Property changes on: trunk/kernel/include/events.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.3
\ No newline at end of property
Index: trunk/kernel/include/custommetadata.php
===================================================================
--- trunk/kernel/include/custommetadata.php (revision 700)
+++ trunk/kernel/include/custommetadata.php (revision 701)
@@ -1,272 +1,274 @@
<?php
class clsCustomMetaData extends clsItem
{
// var $m_CustomDataId;
// var $m_ResourceId;
// var $m_CustomFieldId;
// var $m_Value;
var $FieldName;
function clsCustomMetaData($CustomDataId=-1,$table="CustomMetaData")
{
$this->clsItem();
$this->tablename=GetTablePrefix()."CustomMetaData";
$this->type=12;
$this->BasePermission="";
$this->id_field = "CustomDataId";
$this->NoResourceId=1; //set this to avoid using a resource ID
if(isset($CustomDataId))
$this->LoadFromDatabase($CustomDataId);
}
function Validate()
{
global $Errors;
$dataValid = true;
if(!strlen($this->Get("ResourceId")))
{
$Errors->AddError("error.fieldIsRequired",'ResourceId',"","",get_class($this),"Validate");
$dataValid = false;
}
return $dataValid;
}
function SetFieldName($name)
{
$this->FieldName = $name;
}
function GetFieldName()
{
return $this->FieldName;
}
function Save()
{
if(is_numeric($this->Get("CustomDataId")))
{
$this->Update();
}
else
$this->Create();
}
/*
function LoadFromDatabase($Id)
{
global $objSession, $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->SourceTable." WHERE CustomDataId = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
$this->SetFromArray($data);
$this->Clean();
return true;
}
*/
} /*clsCustomMetaData*/
class clsCustomDataList extends clsItemCollection
{
function clsCustomDataList($table="")
{
$this->clsItemCollection();
$this->classname = "clsCustomMetaData";
if(!strlen($table))
$table = GetTablePrefix()."CustomMetaData";
$this->SetTable('live', $table);
}
function LoadResource($ResourceId)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=".$ResourceId;
$this->Query_Item($sql);
return $this->Items;
}
function DeleteResource($ResourceId)
{
$sql = "DELETE FROM ".$this->SourceTable." WHERE ResourceID=".$ResourceId;
$this->adodbConnection->Execute($ResourceId);
}
function &SetFieldValue($FieldId,$ResourceId,$Value)
{
// so strange construction used, because in normal
// way it doesn't work at all (gets item copy not
// pointer)
$index = $this->GetDataItem($FieldId, true);
if($index !== false)
$d =& $this->Items[$index];
else
$d = null;
if(is_object($d))
{
$d->Set("Value",$Value);
if(!strlen($Value))
{
for($x=0;$x<count($this->Items);$x++)
{
if($this->Items[$x]->Get("CustomFieldId")==$FieldId &&
$this->Items[$x]->Get("ResourceId")==$ResourceId)
{
$this->Items[$x]->Set("CustomFieldId",0);
break;
}
}
$d->Delete();
}
}
else
{
if(strlen($Value)>0)
{
$d = new clsCustomMetaData();
$d->Set("CustomFieldId",$FieldId);
$d->Set("ResourceId",$ResourceId);
$d->Set("Value",$Value);
array_push($this->Items,$d);
}
}
return $d;
}
function &GetDataItem($id, $return_index = false)
{
// $id - custom field id to find
// $return_index - return index to items, not her.
$found = false;
$index = false;
for($i = 0; $i < $this->NumItems(); $i++)
{
$d =& $this->GetItemRefByIndex($i);
if($d->Get("CustomFieldId")==$id)
{
$found=TRUE;
break;
}
}
return $found ? ($return_index ? $i : $d) : false;
}
function SaveData()
{
foreach($this->Items as $f)
{
$FieldId = $f->Get("CustomFieldId");
$value = $f->Get("Value");
$ResId = $f->Get("ResourceId");
$DataId = $f->Get("CustomDataId");
if(is_numeric($DataId))
{
$sql = "UPDATE ".$this->SourceTable." SET Value='".$value."' WHERE CustomFieldId='$FieldId' AND ResourceId='$ResId'";
$this->adodbConnection->Execute($sql);
}
else
{
if($FieldId>0)
{
$sql = "INSERT INTO ".$this->SourceTable." (ResourceId,CustomFieldId,Value) VALUES ('".$ResId."','$FieldId','$value')";
$this->adodbConnection->Execute($sql);
}
}
}
$rs = $this->adodbConnection->Execute("SELECT * FROM ".$this->SourceTable." WHERE CustomDataId=0 ");
while($rs && !$rs->EOF)
{
$m = $this->adodbConnection->Execute("SELECT MIN(CustomDataId) as MinValue FROM ".$this->SourceTable);
$NewId = $m->fields["MinValue"]-1;
$sql = "UPDATE ".$this->SourceTable." SET CustomDataId=$NewId WHERE ResourceId=".$rs->fields["ResourceId"]." AND ";
$sql .= "CustomFieldId=".$rs->fields["CustomFieldId"];
$this->adodbConnection->Execute($sql);
$rs->MoveNext();
}
}
function CopyToEditTable($idfield, $idlist)
{
global $objSession;
$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((int)$GLOBALS["debuglevel"])
echo $insert;
$this->adodbConnection->Execute($insert);
$this->SourceTable = $edit_table;
$this->SaveData();
}
function CopyFromEditTable($ResourceId)
{
global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
//$this->adodbConnection->Execute($sql);
$sql = "SELECT * FROM $edit_table";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
if(strlen($data["Value"])>0)
{
$c->Dirty();
if($data["CustomDataId"]>0)
{
$c->Update();
}
else
{
$c->UnsetIdField();
$c->Create();
}
$idlist[] = $c->Get("CustomDataId");
}
else
{
$sql = "DELETE FROM ".$this->SourceTable." WHERE ResourceId=".$data["ResourceId"]." AND CustomFieldId=".$data["CustomFieldId"];
//echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
}
$rs->MoveNext();
}
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
+ unset($GLOBALS['_CopyFromEditTable']);
}
} /* clsCustomDataList */
?>
Property changes on: trunk/kernel/include/custommetadata.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.4
\ No newline at end of property
+1.5
\ No newline at end of property
Index: trunk/kernel/include/category.php
===================================================================
--- trunk/kernel/include/category.php (revision 700)
+++ trunk/kernel/include/category.php (revision 701)
@@ -1,2319 +1,2320 @@
<?php
define('TYPE_CATEGORY', 0);
$DownloadId=0;
RegisterPrefix("clsCategory","cat","kernel/include/category.php");
class clsCategory extends clsItem
{
var $Permissions;
function clsCategory($CategoryId=NULL)
{
global $objSession;
$this->clsItem(TRUE);
$this->tablename = GetTablePrefix()."Category";
$this->type=1;
$this->BasePermission ="CATEGORY";
$this->id_field = "CategoryId";
$this->TagPrefix = "cat";
$this->debuglevel=0;
/* keyword highlighting */
$this->OpenTagVar = "Category_Highlight_OpenTag";
$this->CloseTagVar = "Category_Highlight_CloseTag";
if($CategoryId!=NULL)
{
$this->LoadFromDatabase($CategoryId);
$this->Permissions = new clsPermList($CategoryId,$objSession->Get("GroupId"));
}
else
{
$this->Permissions = new clsPermList();
}
}
function ClearCacheData()
{
$env = "':m".$this->Get("CategoryId")."%'";
DeleteTagCache("m_itemcount","Category%");
DeleteTagCache("m_list_cats","",$env);
}
function Delete()
{
global $CatDeleteList;
if(!is_array($CatDeleteList))
$CatDeleteList = array();
if($this->UsingTempTable()==FALSE)
{
$this->Permissions->Delete_CatPerms($this->Get("CategoryId"));
$sql = "DELETE FROM ".GetTablePrefix()."CountCache WHERE CategoryId=".$this->Get("CategoryId");
$this->adodbConnection->Execute($sql);
$CatDeleteList[] = $this->Get("CategoryId");
if($this->Get("CreatedById")>0)
$this->SendUserEventMail("CATEGORY.DELETE",$this->Get("CreatedById"));
$this->SendAdminEventMail("CATEGORY.DELETE");
parent::Delete();
$this->ClearCacheData();
}
else
{
parent::Delete();
}
}
function Update($UpdatedBy=NULL)
{
parent::Update($UpdatedBy);
if($this->tablename==GetTablePrefix()."Category")
$this->ClearCacheData();
}
function Create()
{
if((int)$this->Get("CreatedOn")==0)
$this->Set("CreatedOn",date("U"));
parent::Create();
if($this->tablename==GetTablePrefix()."Category")
$this->ClearCacheData();
}
function SetParentId($value)
{
//Before we set a parent verify that propsed parent is not our child.
//Otherwise it will cause recursion.
$id = $this->Get("CategoryId");
$path = $this->Get("ParentPath");
$sql = sprintf("SELECT CategoryId From ".GetTablePrefix()."Category WHERE ParentPath LIKE '$path%' AND CategoryId = %d ORDER BY ParentPath",$value);
$rs = $this->adodbConnection->SelectLimit($sql,1,0);
if(!$rs->EOF)
{
return;
}
$this->Set("ParentId",$value);
}
function Approve()
{
global $objSession;
if($this->Get("CreatedById")>0)
$this->SendUserEventMail("CATEGORY.APPROVE",$this->Get("CreatedById"));
$this->SendAdminEventMail("CATEGORY.APPROVE");
$this->Set("Status", 1);
$this->Update();
}
function Deny()
{
global $objSession;
if($this->Get("CreatedById")>0)
$this->SendUserEventMail("CATEGORY.DENY",$this->Get("CreatedById"));
$this->SendAdminEventMail("CATEGORY.DENY");
$this->Set("Status", 0);
$this->Update();
}
function IsEditorsPick()
{
return $this->Is("EditorsPick");
}
function SetEditorsPick($value)
{
$this->Set("EditorsPick", $value);
}
function GetSubCats($limit=NULL, $target_template=NULL, $separator=NULL, $anchor=NULL, $ending=NULL, $class=NULL)
{
global $m_var_list, $m_var_list_update, $var_list, $var_list_update;
$sql = "SELECT CategoryId, Name from ".GetTablePrefix()."Category where ParentId=".$this->Get("CategoryId")." AND Status=1 ORDER BY Priority";
if(isset($limit))
{
$rs = $this->adodbConnection->SelectLimit($sql, $limit, 0);
}
else
{
$rs = $this->adodbConnection->Execute($sql);
}
$count=1;
$class_name = is_null($class)? "catsub" : $class;
while($rs && !$rs->EOF)
{
if(!is_null($target_template))
{
$var_list_update["t"] = $target_template;
}
$m_var_list_update["cat"] = $rs->fields["CategoryId"];
$m_var_list_update["p"] = "1";
$cat_name = $rs->fields['Name'];
if (!is_null($anchor))
$ret .= "<a class=\"$class_name\" href=\"".GetIndexURL()."?env=" . BuildEnv() . "\">$cat_name</a>";
else
$ret .= "<span=\"$class_name\">$cat_name</span>";
$rs->MoveNext();
if(!$rs->EOF)
{
$ret.= is_null($separator)? ", " : $separator;
}
}
if(strlen($ret))
$ret .= is_null($ending)? " ..." : $ending;
unset($var_list_update["t"], $m_var_list_update["cat"], $m_var_list_update["p"]);
return $ret;
}
function Validate()
{
global $objSession;
$dataValid = true;
if(!isset($this->m_Type))
{
$Errors->AddError("error.fieldIsRequired",'Type',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_Name))
{
$Errors->AddError("error.fieldIsRequired",'Name',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_Description))
{
$Errors->AddError("error.fieldIsRequired",'Description',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_Visible))
{
$Errors->AddError("error.fieldIsRequired",'Visible',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_CreatedById))
{
$Errors->AddError("error.fieldIsRequired",'CreatedBy',"","","clsCategory","Validate");
$dataValid = false;
}
return $dataValid;
}
function UpdateCachedPath()
{
if($this->UsingTempTable()==TRUE)
return;
$Id = $this->Get("CategoryId");
$Id2 = $Id;
$NavPath = "";
$path = array();
do
{
$rs = $this->adodbConnection->Execute("SELECT ParentId,Name from ".$this->tablename." where CategoryId='$Id2'");
$path[] = $Id2;
$nav[] = $rs->fields["Name"];
if ($rs && !$rs->EOF)
{
//echo $path;
$Id2 = $rs->fields["ParentId"];
}
else
$Id2="0"; //to prevent infinite loop
} while ($Id2 != "0");
$parentpath = "|".implode("|",array_reverse($path))."|";
$NavBar = implode(">",array_reverse($nav));
//echo "<BR>\n";
//$rs = $this->adodbConnection->Execute("update Category set ParentPath='$path' where CategoryId='$Id'");
if($this->Get("ParentPath")!=$parentpath || $this->Get("CachedNavbar")!=$NavBar)
{
$this->Set("ParentPath",$parentpath);
$this->Set("CachedNavbar",$NavBar);
$this->Update();
}
}
function GetCachedNavBar()
{
$res = $this->Get("CachedNavbar");
if(!strlen($res))
{
$this->UpdateCachedPath();
$res = $this->Get("CachedNavbar");
}
return $res;
}
function Increment_Count()
{
$this->Increment("CachedDescendantCatsQty");
}
function Decrement_Count()
{
$this->Decrement("CachedDescendantCatsQty");
$this->Update();
}
function LoadFromDatabase($Id)
{
global $objSession, $Errors, $objConfig;
if($Id==0)
return FALSE;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE CategoryId = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
if(is_array($data))
{
$this->SetFromArray($data);
$this->Clean();
}
else
return false;
return true;
}
function SetNewItem()
{
global $objConfig;
$value = $this->Get("CreatedOn");
$cutoff = adodb_date("U") - ($objConfig->Get("Category_DaysNew") * 86400);
$this->IsNew = FALSE;
if($value>$cutoff)
$this->IsNew = TRUE;
return $this->IsNew;
}
function LoadFromResourceId($Id)
{
global $objSession, $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromResourceId");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ResourceId = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromResourceId");
return false;
}
$data = $result->fields;
if(is_array($data))
$this->SetFromArray($data);
else
return false;
return true;
}
function GetParentField($fieldname,$skipvalue,$default)
{
/* this function moves up the category tree until a value for $field other than
$skipvalue is returned. if no matches are made, then $default is returned */
$path = $this->Get("ParentPath");
$path = substr($path,1,-1); //strip off the first & last tokens
$aPath = explode("|",$path);
$aPath = array_slice($aPath,0,-1);
$ParentPath = implode("|",$aPath);
$sql = "SELECT $fieldname FROM category WHERE $fieldname != '$skipvalue' AND ParentPath LIKE '$ParentPath' ORDER BY ParentPath DESC";
$rs = $this->adodbConnection->execute($sql);
if($rs && !$rs->EOF)
{
$ret = $rs->fields[$fieldname];
}
else
$ret = $default;
$update = "UPDATE ".$this->SourceTable." SET $fieldname='$ret' WHERE CategoryId=".$this->Get("CategoryId");
$this->adodbConnection->execute($update);
return $ret;
}
function GetCustomField($fieldName)
{
global $objSession, $Errors;
if(!isset($this->m_CategoryId))
{
$Errors->AddError("error.appError","Get field is required in order to set custom field values","","",get_class($this),"GetCustomField");
return false;
}
return GetCustomFieldValue($this->m_CategoryId,"category",$fieldName);
}
function SetCustomField($fieldName, $value)
{
global $objSession, $Errors;
if(!isset($this->m_CategoryId))
{
$Errors->AddError("error.appError","Set field is required in order to set custom field values","","",get_class($this),"SetCustomField");
return false;
}
return SetCustomFieldValue($this->m_CategoryId,"category",$fieldName,$value);
}
function LoadPermissions($first=1)
{
/* load all permissions for group on this category */
$this->Permissions->CatId=$this->Get("CategoryId");
if($this->Permissions->NumItems()==0)
{
$cats = explode("|",substr($this->Get("ParentPath"),1,-1));
if(is_array($cats))
{
$cats = array_reverse($cats);
$cats[] = 0;
foreach($cats as $catid)
{
$this->Permissions->LoadCategory($catid);
}
}
}
if($this->Permissions->NumItems()==0)
{
if($first==1)
{
$this->Permissions->GroupId=NULL;
$this->LoadPermissions(0);
}
}
}
function PermissionObject()
{
return $this->Permissions;
}
function PermissionItemObject($PermissionName)
{
$p = $this->Permissions->GetPermByName($PermissionName);
return $p;
}
function HasPermission($PermissionName,$GroupID)
{
global $objSession;
$perm = $this->PermissionValue($PermissionName,$GroupID);
// echo "Permission $PermissionName for $GroupID is $perm in ".$this->Get("CategoryId")."<br>\n";
if(!$perm)
{
$perm=$objSession->HasSystemPermission("ROOT");
}
return ($perm==1);
}
function PermissionValue($PermissionName,$GroupID)
{
//$this->LoadPermissions();
$ret=NULL;
//echo "Looping though ".count($this->Permissions)." permissions Looking for $PermissionName of $GroupID<br>\n";
if($this->Permissions->GroupId != $GroupID)
{
$this->Permissions->Clear();
$this->Permissions->GroupId = $GroupID;
}
$this->Permissions->CatId=$this->Get("CategoryId");
$ret = $this->Permissions->GetPermissionValue($PermissionName);
if($ret == NULL)
{
$cats = explode("|",substr($this->Get("ParentPath"),1,-1));
if(is_array($cats))
{
$cats = array_reverse($cats);
$cats[] = 0;
foreach($cats as $catid)
{
$this->Permissions->LoadCategory($catid);
$ret = $this->Permissions->GetPermissionValue($PermissionName);
if(is_numeric($ret))
break;
}
}
}
return $ret;
}
function SetPermission($PermName,$GroupID,$Value,$Type=0)
{
global $objSession, $objPermissions, $objGroups;
if($this->Permissions->GroupId != $GroupID)
{
$this->Permissions->Clear();
$this->Permissions->GroupId = $GroupID;
}
if($objSession->HasSystemPermission("GRANT"))
{
$current = $this->PermissionValue($PermName,$GroupID);
if($current == NULL)
{
$this->Permissions->Add_Permission($this->Get("CategoryId"),$GroupId,$PermName,$Value,$Type);
}
else
{
$p = $this->Permissions->GetPermByName($PermName);
if($p->Inherited==FALSE)
{
$p->Set("PermissionValue",$Value);
$p->Update();
}
else
$this->Permissions->Add_Permission($this->Get("CategoryId"),$GroupId,$PermName,$Value,$Type);
}
if($PermName == "CATEGORY.VIEW")
{
$Groups = $objGroups->GetAllGroupList();
$ViewList = $this->Permissions->GetGroupPermList($this,"CATEGORY.VIEW",$Groups);
$this->SetViewPerms("CATEGORY.VIEW",$ViewList,$Groups);
$this->Update();
}
}
}
function SetViewPerms($PermName,$acl,$allgroups)
{
global $objPermCache;
$dacl = array();
if(!is_array($allgroups))
{
global $objGroups;
$allgroups = $objGroups->GetAllGroupList();
}
for($i=0;$i<count($allgroups);$i++)
{
$g = $allgroups[$i];
if(!in_array($g,$acl))
$dacl[] = $g;
}
if(count($acl)<count($dacl))
{
$aval = implode(",",$acl);
$dval = "";
}
else
{
$dval = implode(",",$dacl);
$aval = "";
}
if(strlen($aval)==0 && strlen($dval)==0)
{
$aval = implode(",",$allgroups);
}
$PermId = $this->Permissions->GetPermId($PermName);
$pc = $objPermCache->GetPerm($this->Get("CategoryId"),$PermId);
if(is_object($pc))
{
$pc->Set("ACL",$aval);
$pc->Set("DACL",$dval);
$pc->Update();
}
else
$objPermCache->AddPermCache($this->Get("CategoryId"),$PermId,$aval,$dval);
//$this->Update();
}
function GetACL($PermName)
{
global $objPermCache;
$ret = "";
$PermId = $this->Permissions->GetPermId($PermName);
$pc = $objPermCache->GetPerm($this->Get("CategoryId"),$PermId);
if(is_object($pc))
{
$ret = $this->Get("ACL");
}
return $ret;
}
function UpdateACL()
{
global $objGroups, $objPermCache;
$glist = $objGroups->GetAllGroupList();
$ViewList = $this->Permissions->GetGroupPermList($this,"CATEGORY.VIEW",$glist);
$perms = $this->Permissions->GetAllViewPermGroups($this,$glist);
//echo "<PRE>";print_r($perms); echo "</PRE>";
foreach($perms as $PermName => $l)
{
$this->SetViewPerms($PermName,$l,$glist);
}
}
function Cat_Link()
{
global $m_var_list_update;
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = GetIndexURL()."?env=".BuildEnv();
unset($m_var_list_update["cat"]);
return $ret;
}
function Parent_Link()
{
global $m_var_list_update;
$m_var_list_update["cat"] = $this->Get("ParentId");
$ret = GetIndexURL()."?env=".BuildEnv();
unset($m_var_list_update["cat"]);
return $ret;
}
function Admin_Parent_Link($page=NULL)
{
global $m_var_list_update;
if(!strlen($page))
$page = $_SERVER["PHP_SELF"];
$m_var_list_update["cat"] = $this->Get("ParentId");
$ret = $page."?env=".BuildEnv();
unset($m_var_list_update["cat"]);
return $ret;
}
function StatusIcon()
{
global $imagesURL;
$ret = $imagesURL."/itemicons/";
switch($this->Get("Status"))
{
case STATUS_DISABLED:
$ret .= "icon16_cat_disabled.gif";
break;
case STATUS_PENDING:
$ret .= "icon16_cat_pending.gif";
break;
case STATUS_ACTIVE:
$img = "icon16_cat.gif";
if($this->IsPopItem())
$img = "icon16_cat_pop.gif";
if($this->IsHotItem())
$img = "icon16_cat_hot.gif";
if($this->IsNewItem())
$img = "icon16_cat_new.gif";
if($this->Is("EditorsPick"))
$img = "icon16_car_pick.gif";
$ret .= $img;
break;
}
return $ret;
}
function SubCatCount()
{
$ret = $this->Get("CachedDescendantCatsQty");
$sql = "SELECT COUNT(*) as SubCount FROM ".$this->tablename." WHERE ParentPath LIKE '".$this->Get("ParentPath")."%' AND CategoryId !=".$this->Get("CategoryId");
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$val = $rs->fields["SubCount"];
if($val != $this->Get("CachedDescendantCatsQty"))
{
$this->Set("CachedDescendantCatsQty",$val);
$this->Update();
}
$ret = $this->Get("CachedDescendantCatsQty");
}
return $ret;
}
function GetSubCatIds()
{
$sql = "SELECT CategoryId FROM ".$this->tablename." WHERE ParentPath LIKE '".$this->Get("ParentPath")."%' AND CategoryId !=".$this->Get("CategoryId");
$rs = $this->adodbConnection->Execute($sql);
$ret = array();
while($rs && !$rs->EOF)
{
$ret[] = $rs->fields["CategoryId"];
$rs->MoveNext();
}
return $ret;
}
function GetParentIds()
{
$Parents = array();
$ParentPath = $this->Get("ParentPath");
if(strlen($ParentPath))
{
$ParentPath = substr($ParentPath,1,-1);
$Parents = explode("|",$ParentPath);
}
return $Parents;
}
function ItemCount($ItemType="")
{
global $objItemTypes,$objCatList,$objCountCache;
if(!is_numeric($ItemType))
{
$TypeId = $objItemTypes->GetItemTypeValue($ItemType);
}
else
$TypeId = (int)$ItemType;
//$path = $this->Get("ParentPath");
//$path = substr($path,1,-1);
//$path = str_replace("|",",",$path);
$path = implode(",",$this->GetSubCatIds());
if(strlen($path))
{
$path = $this->Get("CategoryId").",".$path;
}
else
$path = $this->Get("CategoryId");
$res = TableCount(GetTablePrefix()."CategoryItems","CategoryId IN ($path)",FALSE);
return $res;
}
function ParseObject($element)
{
global $objConfig, $objCatList, $rootURL, $var_list, $var_list_update, $m_var_list_update, $objItemTypes,$objCountCache;
$extra_attribs = ExtraAttributes($element->attributes);
//print_r($element);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower( $element->GetAttributeByName('_field') );
switch($field)
{
case "name":
case "Name":
/*
@field:cat.name
@description:Category name
*/
$ret = $this->HighlightField("Name");
break;
case "description":
/*
@field:cat.description
@description:Category Description
*/
$ret = ($this->Get("Description"));
$ret = $this->HighlightText($ret);
break;
case "cachednavbar":
/*
@field:cat.cachednavbar
@description: Category cached navbar
*/
$ret = $this->HighlightField("CachedNavbar");
if(!strlen($ret))
{
$this->UpdateCachedPath();
$ret = $this->HighlightField("CachedNavbar");
}
break;
case "image":
/*
@field:cat.image
@description:Return an image associated with the category
@attrib:_default:bool:If true, will return the default image if the requested image does not exist
@attrib:_name::Return the image with this name
@attrib:_thumbnail:bool:If true, return the thumbnail version of the image
@attrib:_imagetag:bool:If true, returns a complete image tag. exta html attributes are passed to the image tag
*/
$default = $element->GetAttributeByName('_primary');
$name = $element->GetAttributeByName('_name');
if(strlen($name))
{
$img = $this->GetImageByName($name);
}
else
{
if($default)
$img = $this->GetDefaultImage();
}
if($img)
{
if( $element->GetAttributeByName('_thumbnail') )
{
$url = $img->parsetag("thumb_url");
}
else
$url = $img->parsetag("image_url");
}
else
{
$url = $element->GetAttributeByName('_defaulturl');
}
if( $element->GetAttributeByName('_imagetag') )
{
if(strlen($url))
{
$ret = "<IMG src=\"$url\" $extra_attribs >";
}
else
$ret = "";
}
else
$ret = $url;
break;
case "createdby":
/*
@field:cat.createdby
@description:parse a user field of the user that created the category
@attrib:_usertag::User field to return (defaults to login ID)
*/
$field = $element->GetAttributeByName('_usertag');
if(!strlen($field))
{
$field = "user_login";
}
$u = $objUsers->GetUser($this->Get("CreatedById"));
$ret = $u->parsetag($field);
break;
case "custom":
/*
@field:cat.custom
@description:Returns a custom field
@attrib:_customfield::field name to return
@attrib:_default::default value
*/
$field = $element->GetAttributeByName('_customfield');
$default = $element->GetAttributeByName('_default');
$ret = $this->GetCustomFieldValue($field,$default);
break;
case "catsubcats":
/*
@field:cat.catsubcats
@description:Returns a list of subcats of current category
@attrib:_limit:int:Number of categories to return
@attrib:_separator::Separator between categories
@attrib:_anchor:bool:Make an anchor (only if template is not specified)
@attrib:_TargetTemplate:tpl:Target template
@attrib:_Ending::Add special text at the end of subcategory list
@attrib:_Class::Specify stly sheet class for anchors (if used) or "span" object
*/
$limit = ((int)$element->attributes["_limit"]>0)? $element->attributes["_limit"] : NULL;
$separator = $element->attributes["_separator"];
$anchor = (int)($element->attributes["_anchor"])? 1 : NULL;
$template = strlen($element->attributes["_TargetTemplate"])? $element->attributes["_TargetTemplate"] : NULL;
$ending = strlen($element->attributes["_ending"])? $element->attributes["_ending"] : NULL;
$class = strlen($element->attributes["_class"])? $element->attributes["_class"] : NULL;
$ret = $this->GetSubCats($limit, $template, $separator, $anchor, $ending, $class);
break;
case "date":
/*
@field:cat.date
@description:Returns the date/time the category was created
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$d = $this->Get("CreatedOn");
if( $element->GetAttributeByName('_tz') )
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower( $element->GetAttributeByName('_part') );
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if(!is_numeric($d))
{
$ret = "";
}
else
$ret = LangDate($d);
}
break;
case "link":
/*
@field:cat.link
@description:Returns a URL setting the category to the current category
@attrib:_template:tpl:Template URL should point to
@attrib:_mod_template:tpl:Template INSIDE a module to which the category belongs URL should point to
*/
if ( strlen( $element->GetAttributeByName('_mod_template') ) ){
//will prefix the template with module template root path depending on category
$ids = $this->GetParentIds();
$tpath = GetModuleArray("template");
$roots = GetModuleArray("rootcat");
// get template path of module, by searching for moudle name
// in this categories first parent category
// and then using found moudle name as a key for module template paths array
$path = $tpath[array_search ($ids[0], $roots)];
$t = $path . $element->GetAttributeByName('_mod_template');
}
else
$t = $element->GetAttributeByName('_template');
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = GetIndexURL()."?env=" . BuildEnv();
unset($m_var_list_update["cat"], $var_list_update["t"]);
break;
case "adminlink":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$m_var_list_update["p"] = 1;
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
unset($m_var_list_update["cat"]);
unset($m_var_list_update["p"]);
return $ret;
break;
case "customlink":
$t = $this->GetCustomFieldValue("indextemplate","");
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = GetIndexURL()."?env=" . BuildEnv();
unset($m_var_list_update["cat"], $var_list_update["t"]);
break;
case "link_selector":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
// pass through selector
if( isset($_REQUEST['Selector']) ) $ret .= '&Selector='.$_REQUEST['Selector'];
// pass new status
if( isset($_REQUEST['new']) ) $ret .= '&new='.$_REQUEST['new'];
unset($m_var_list_update["cat"]);
return $ret;
break;
case "admin_icon":
if( $element->GetAttributeByName('fulltag') )
{
$ret = "<IMG $extra_attribs SRC=\"".$this->StatusIcon()."\">";
}
else
$ret = $this->StatusIcon();
break;
case "subcats":
/*
@field:cat.subcats
@description: Loads category's subcategories into a list and renders using the m_list_cats global tag
@attrib:_subcattemplate:tpl:Template used to render subcategory list elements
@attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
@attrib: _maxlistcount:int: Maximum number of categories to list
@attrib: _FirstItemTemplate:tpl: Template used for the first category listed
@attrib: _LastItemTemplate:tpl: Template used for the last category listed
@attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag
*/
$attr = array();
$attr["_catid"] = $this->Get("CategoryId");
$attr["_itemtemplate"] = $element->GetAttributeByName('_subcattemplate');
if( $element->GetAttributeByName('_notable') )
$attr["_notable"]=1;
$ret = m_list_cats($attr);
break;
case "subcatcount":
/*
@field:cat.subcatcount
@description:returns number of subcategories
*/
$GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0;
$txt = "<inp:m_itemcount _CatId=\"".$this->Get("CategoryId")."\" _SubCats=\"1\" ";
$txt .="_CategoryCount=\"1\" _ItemType=\"1\" _GroupOnly=\"$GroupOnly\" />";
$tag = new clsHtmlTag($txt);
$ret = $tag->Execute();
break;
case "itemcount":
/*
@field:cat.itemcount
@description:returns the number of items in the category
@attrib:_itemtype::name of item type to count, or all items if not set
*/
$typestr = $element->GetAttributeByName('_itemtype');
if(strlen($typestr))
{
$type = $objItemTypes->GetTypeByName($typestr);
if(is_object($type))
{
$TypeId = $type->Get("ItemType");
$GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0;
$txt = "<inp:m_itemcount _CatId=\"".$this->Get("CategoryId")."\" _SubCats=\"1\" ";
$txt .=" _ListType=\"category\" _CountCurrent=\"1\" _ItemType=\"$TypeId\" _GroupOnly=\"$GroupOnly\" />";
$tag = new clsHtmlTag($txt);
$ret = $tag->Execute();
}
else
$ret = "";
}
else
{
$ret = (int)$objCountCache->GetCatListTotal($this->Get("CategoryId"));
}
break;
case "totalitems":
/*
@field:cat.totalitems
@description:returns the number of items in the category and all subcategories
*/
$ret = $this->ItemCount();
break;
case 'modified':
$ret = '';
$date = $this->Get('Modified');
if(!$date) $date = $this->Get('CreatedOn');
if( $element->GetAttributeByName('_tz') )
{
$date = GetLocalTime($date,$objSession->Get("tz"));
}
$part = strtolower($element->GetAttributeByName('_part') );
if(strlen($part))
{
$ret = ExtractDatePart($part,$date);
}
else
{
$ret = ($date <= 0) ? '' : LangDate($date);
}
break;
case "itemdate":
/*
@field:cat.itemdate
@description:Returns the date the cache count was last updated
@attrib:_itemtype:Item name to check
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$typestr = $element->GetAttributeByName('_itemtype');
$type = $objItemTypes->GetTypeByName($typestr);
if(is_object($type))
{
$TypeId = $type->Get("ItemType");
$cc = $objCountCache->GetCountObject(1,$TypeId,$this->get("CategoryId"),0);
if(is_object($cc))
{
$date = $cc->Get("LastUpdate");
}
else
$date = "";
//$date = $this->GetCacheCountDate($TypeId);
if( $element->GetAttributeByName('_tz') )
{
$date = GetLocalTime($date,$objSession->Get("tz"));
}
$part = strtolower($element->GetAttributeByName('_part') );
if(strlen($part))
{
$ret = ExtractDatePart($part,$date);
}
else
{
if($date<=0)
{
$ret = "";
}
else
$ret = LangDate($date);
}
}
else
$ret = "";
break;
case "new":
/*
@field:cat.new
@description:returns text if category's status is "new"
@attrib:_label:lang: Text to return if status is new
*/
if($this->IsNewItem())
{
$ret = $element->GetAttributeByName('_label');
if(!strlen($ret))
$ret = "lu_new";
$ret = language($ret);
}
else
$ret = "";
break;
case "pick":
/*
@field:cat.pick
@description:returns text if article's status is "hot"
@attrib:_label:lang: Text to return if status is "hot"
*/
if($this->Get("EditorsPick")==1)
{
$ret = $element->GetAttributeByName('_label');
if(!strlen($ret))
$ret = "lu_pick";
$ret = language($ret);
}
else
$ret = "";
break;
case "parsetag":
/*
@field:cat.parsetag
@description:returns a tag output with this categoriy set as a current category
@attrib:_tag:: tag name
*/
$tag = new clsHtmlTag();
$tag->name = $element->GetAttributeByName('_tag');
$tag->attributes = $element->attributes;
$tag->attributes["_catid"] = $this->Get("CategoryId");
$ret = $tag->Execute();
break;
/*
@field:cat.relevance
@description:Displays the category relevance in search results
@attrib:_displaymode:: How the relevance should be displayed<br>
<UL>
<LI>"Numerical": Show the decimal value
<LI>"Bar": Show the HTML representing the relevance. Returns two HTML cells &lg;td&lt; with specified background colors
<LI>"Graphical":Show image representing the relevance
</UL>
@attrib:_onimage::Zero relevance image shown in graphical display mode. Also used as prefix to build other images (i.e. prefix+"_"+percentage+".file_extension"
@attrib:_OffBackGroundColor::Off background color of HTML cell in bar display mode
@attrib:_OnBackGroundColor::On background color of HTML cell in bar display mode
*/
}
if( !isset($ret) ) $ret = parent::ParseObject($element);
}
return $ret;
}
function parsetag($tag)
{
global $objConfig,$objUsers, $m_var_list, $m_var_list_update;
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "cat_id":
return $this->Get("CategoryId");
break;
case "cat_parent":
return $this->Get("ParentId");
break;
case "cat_fullpath":
return $this->Get("CachedNavbar");
break;
case "cat_name":
return $this->Get("Name");
break;
case "cat_desc":
return $this->Get("Description");
break;
case "cat_priority":
if($this->Get("Priority")!=0)
{
return (int)$this->Get("Priority");
}
else
return "";
break;
case "cat_pick":
if ($this->Get("EditorsPick"))
return "pick";
break;
case "cat_status":
return $this->Get("Status");
break;
case "cat_Pending":
return $this->Get("Name");
break;
case "cat_pop":
if($this->IsPopItem())
return "pop";
break;
case "cat_new":
if($this->IsNewItem())
return "new";
break;
case "cat_hot":
if($this->IsHotItem())
return "hot";
break;
case "cat_metakeywords":
return $this->Get("MetaKeywords");
break;
case "cat_metadesc":
return $this->Get("MetaDescription");
break;
case "cat_createdby":
return $objUsers->GetUserName($this->Get("CreatedById"));
break;
case "cat_resourceid":
return $this->Get("ResourceId");
break;
case "cat_sub_cats":
return $this->GetSubCats($objConfig->Get("SubCat_ListCount"));
break;
case "cat_link":
return $this->Cat_Link();
break;
case "subcat_count":
return $this->SubCatCount();
break;
case "cat_itemcount":
return (int)$this->GetTotalItemCount();
break;
case "cat_link_admin":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$m_var_list_update["p"] = 1;
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
unset($m_var_list_update["cat"]);
unset($m_var_list_update["p"]);
return $ret;
break;
case "cat_admin_icon":
$ret = $this->StatusIcon();
return $ret;
break;
case "cat_link_selector":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
unset($m_var_list_update["cat"]);
return $ret;
break;
case "cat_link_edit":
$m_var_list_update["id"] = $this->Get("CategoryId");
$ret = "addcategory.php?env=" . BuildEnv();
unset($m_var_list_update["id"]);
return $ret;
break;
case "cat_date":
return LangDate($this->Get("CreatedOn"));
break;
case "cat_num_cats":
return $this->Get("CachedDescendantCatsQty");
break;
case "cell_back":
if ($m_var_list_update["cat_cell"]=="#cccccc")
{
$m_var_list_update["cat_cell"]="#ffffff";
return "#ffffff";
}
else
{
$m_var_list_update["cat_cell"]="#cccccc";
return "#cccccc";
}
break;
default:
return "Undefined:$tagname";
}
}
function ParentNames()
{
global $objCatList;
if(strlen($this->Get("CachedNavbar"))==0)
{
$nav = "";
//echo "Rebuilding Navbar..<br>\n";
if(strlen($this->Get("ParentPath"))==0)
{
$this->UpdateCachedPath();
}
$cats = explode("|",substr($this->Get("ParentPath"),1,-1));
foreach($cats as $catid)
{
$cat =& $objCatList->GetCategory($catid);
if(is_object($cat))
{
if(strlen($cat->Get("Name")))
$names[] = $cat->Get("Name");
}
}
$nav = implode(">", $names);
$this->Set("CachedNavbar",$nav);
$this->Update();
}
$res = explode(">",$this->Get("CachedNavbar"));
return $res;
}
function UpdateCacheCounts()
{
global $objItemTypes;
$CatId = $this->Get("CategoryId");
if($CatId>0)
{
//echo "Updating count for ".$this->Get("CachedNavbar")."<br>\n";
UpdateCategoryCount(0,$CatId);
}
}
/**
* @return void
* @param int $date
* @desc Set Modified field for category & all it's parent categories
*/
function SetLastUpdate($date)
{
$parents = $this->Get('ParentPath');
$parents = substr($parents, 1, strlen($parents) - 2 );
$parents = explode('|', $parents);
$db =&GetADODBConnection();
$sql = 'UPDATE '.$this->tablename.' SET Modified = '.$date.' WHERE CategoryId IN ('.implode(',', $parents).')';
$db->Execute($sql);
}
}
class clsCatList extends clsItemList //clsItemCollection
{
//var $Page; // no need because clsItemList class used instead of clsItemCollection
//var $PerPageVar;
function clsCatList()
{
global $m_var_list;
$this->clsItemCollection();
$this->classname="clsCategory";
$this->AdminSearchFields = array("Name","Description");
$this->Page = (int)$m_var_list["p"];
$this->PerPageVar = "Perpage_Category";
$this->SourceTable = GetTablePrefix()."Category";
$this->BasePermission="CATEGORY";
$this->DefaultPerPage = 20;
}
function SaveNewPage()
{
global $m_var_list;
$m_var_list["p"] = $this->Page;
}
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 $ptable ON ($ltable.CategoryId=$ptable.CategoryId) ";
$sql .="WHERE ($acl AND PermId=$VIEW AND $ltable.Status=1) ";
if(strlen($AdditonalWhere)>0)
{
$sql .= "AND (".$AdditonalWhere.")";
}
return $sql;
}
function CountCategories($attribs)
{
global $objSession;
$cat = $attribs["_catid"];
if(!is_numeric($cat))
{
$cat = $this->CurrentCategoryID();
}
if((int)$cat>0)
$c = $this->GetCategory($cat);
if($attribs["_subcats"] && $cat>0)
{
$ParentWhere = "(ParentPath LIKE '".$c->Get("ParentPath")."%' AND ".$this->SourceTable.".CategoryId != $cat)";
}
if($attribs["_today"])
{
$today = mktime(0,0,0,date("m"),date("d"),date("Y"));
$TodayWhere = "(CreatedOn>=$today)";
}
if($attribs["_grouponly"])
{
$GroupList = $objSession->Get("GroupList");
}
else
$GroupList = NULL;
$where = "";
if(strlen($ParentWhere))
{
$where = $ParentWhere;
}
if(strlen($TodayWhere))
{
if(strlen($where))
$where .=" AND ";
$where .= $TodayWhere;
}
$sql = $this->GetCountSQL("CATEGORY.VIEW",$cat,$GroupList,$where);
// echo "SQL: ".$sql."<BR>";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$ret = $rs->fields["CacheVal"];
}
else
$ret = 0;
return $ret;
}
function CurrentCategoryID()
{
global $m_var_list;
return (int)$m_var_list["cat"];
}
function NumCategories()
{
return $this->NumItems();
}
function &CurrentCat()
{
//return $this->GetCategory($this->CurrentCategoryID());
return $this->GetItem($this->CurrentCategoryID());
}
function &GetCategory($CatID)
{
return $this->GetItem($CatID);
}
function GetByResource($ResId)
{
return $this->GetItemByField("ResourceId",$ResId);
}
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";
}
$FieldVar = "Category_Sortfield";
$OrderVar = "Category_Sortorder";
if(is_object($objSession))
{
if(strlen($objSession->GetPersistantVariable($FieldVar))>0)
{
$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ".
$objSession->GetPersistantVariable($OrderVar));
}
}
$FieldVar = "Category_Sortfield2";
$OrderVar = "Category_Sortorder2";
if(is_object($objSession))
{
if(strlen($objSession->GetPersistantVariable($FieldVar))>0)
{
$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ".
$objSession->GetPersistantVariable($OrderVar));
}
}
if(count($Orders)>0)
{
$OrderBy = "ORDER BY ".implode(", ",$Orders);
}
else
$OrderBy="";
return $OrderBy;
}
function LoadCategories($where="", $orderBy = "", $no_limit = true, $fix_method = 'set_first')
{
// load category list using $where clause
// apply ordering specified in $orderBy
// show all cats ($no_limit = true) or only from current page ($no_limit = false)
// in case if stored page is greather then page count issue page_fixing with
// method specified (see "FixInvalidPage" method for details)
$PerPage = $this->GetPerPage();
$this->QueryItemCount = TableCount($this->SourceTable,$where,0);
if($no_limit == false)
{
$this->FixInvalidPage($fix_method);
$Start = ($this->Page-1) * $PerPage;
$limit = "LIMIT ".$Start.",".$PerPage;
}
else
$limit = NULL;
return $this->Query_Category($where, $orderBy, $limit);
}
function Query_Category($whereClause="",$orderByClause="",$limit=NULL)
{
global $m_var_list, $objSession, $Errors, $objPermissions;
$GroupID = $objSession->Get("GroupID");
$resultset = array();
$table = $this->SourceTable;
$ptable = GetTablePrefix()."PermCache";
$CAT_VIEW = $objPermissions->GetPermId("CATEGORY.VIEW");
if(!$objSession->HasSystemPermission("ADMIN"))
{
$sql = "SELECT * FROM $table INNER JOIN $ptable ON ($ptable.CategoryId=$table.CategoryId)";
$acl_where = $objSession->GetACLClause();
if(strlen($whereClause))
{
$sql .= " WHERE ($acl_where) AND PermId=$CAT_VIEW AND ".$whereClause;
}
else
$sql .= " WHERE ($acl_where) AND PermId=$CAT_VIEW ";
}
else
{
$sql ="SELECT * FROM $table ".($whereClause ? "WHERE $whereClause" : '');
}
$sql .=" ".$orderByClause;
if(isset($limit) && strlen(trim($limit)))
$sql .= " ".$limit;
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql;
return $this->Query_item($sql);
}
function CountPending()
{
return TableCount($this->SourceTable,"Status=".STATUS_PENDING,0);
}
function GetPageLinkList($dest_template=NULL,$page="",$PagesToList=10,$HideEmpty=TRUE)
{
global $objConfig, $m_var_list_update, $var_list_update, $var_list;
if(!strlen($page))
$page = GetIndexURL();
$PerPage = $this->GetPerPage();
$NumPages = ceil( $this->GetNumPages($PerPage) );
if($NumPages == 1 && $HideEmpty) return '';
if(strlen($dest_template))
{
$var_list_update["t"] = $dest_template;
}
else
$var_list_update["t"] = $var_list["t"];
$o = "";
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)
{
$m_var_list_update["p"] = $this->Page-$PagesToList;
$prev_url = $page."?env=".BuildEnv();
$o .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
}
for($p=$StartPage;$p<=$EndPage;$p++)
{
if($p!=$this->Page)
{
$m_var_list_update["p"]=$p;
$href = $page."?env=".BuildEnv();
$o .= " <A HREF=\"$href\" >$p</A> ";
}
else
{
$o .= "$p";
}
}
if($EndPage<$NumPages && $EndPage>0)
{
$m_var_list_update["p"]=$this->Page+$PagesToList;
$next_url = $page."?env=".BuildEnv();
$o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
}
unset($m_var_list_update,$var_list_update["t"] );
return $o;
}
function GetAdminPageLinkList($url)
{
global $objConfig, $m_var_list_update, $var_list_update, $var_list;
$PerPage = $this->GetPerPage();
$NumPages = ceil($this->GetNumPages($PerPage));
$o = "";
if($this->Page>1)
{
$m_var_list_update["p"]=$this->Page-1;
$prev_url = $url."?env=".BuildEnv();
unset($m_var_list_update["p"]);
$o .= "<A HREF=\"$prev_url\" class=\"NAV_URL\"><<</A>";
}
if($this->Page<$NumPages)
{
$m_var_list_update["p"]=$this->Page+1;
$next_url = $url."?env=".BuildEnv();
unset($m_var_list_update["p"]);
}
for($p=1;$p<=$NumPages;$p++)
{
if($p != $this->Page)
{
$m_var_list_update["p"]=$p;
$href = $url."?env=".BuildEnv();
unset($m_var_list_update["p"]);
$o .= " <A HREF=\"$href\" class=\"NAV_URL\">$p</A> ";
}
else
$o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
}
if($this->Page < $NumPages)
$o .= "<A HREF=\"$next_url\" class=\"NAV_URL\">>></A>";
return $o;
}
function Search_Category($orderByClause)
{
global $objSession, $objConfig, $Errors;
$PerPage = $this->GetPerPage();
$Start = ($this->Page-1) * $PerPage;
$objResults = new clsSearchResults("Category","clsCategory");
$this->Clear();
$this->Categories = $objResults->LoadSearchResults($Start,$PerPage);
return $this->Categories;
}
function GetSubCats($ParentCat)
{
return $this->Query_Category("ParentId=".$ParentCat,"");
}
function AllSubCats($ParentCat)
{
$c =& $this->GetCategory($ParentCat);
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ParentPath LIKE '".$c->Get("ParentPath")."%'";
$rs = $this->adodbConnection->Execute($sql);
$subcats = array();
while($rs && !$rs->EOF)
{
if($rs->fields["CategoryId"]!=$ParentCat)
{
$subcats[] = $rs->fields["CategoryId"];
}
$rs->MoveNext();
}
if($ParentCat>0)
{
if($c->Get("CachedDescendantCatsQty")!=count($subcats))
{
$c->Set("CachedDescendantCatsQty",count($subcats));
}
}
return $subcats;
}
function cat_navbar($admin=0, $cat, $target_template, $separator = " > ", $LinkLeaf = FALSE,
$root = 0,$RootTemplate="",$modcat=0, $ModTemplate="", $LinkRoot = FALSE)
{
// draw category navigation bar (at top)
global $Errors, $var_list_update, $var_list, $m_var_list_update, $m_var_list, $objConfig;
$selector = isset($_REQUEST['Selector']) ? '&Selector='.$_REQUEST['Selector'] : '';
$new = isset($_REQUEST['new']) ? '&new='.$_REQUEST['new'] : '';
$nav = "";
$m_var_list_update["p"]=1;
if(strlen($target_template)==0)
$target_template = $var_list["t"];
if($cat == 0)
{
$cat_name = language($objConfig->Get("Root_Name"));
if ($LinkRoot)
{
$var_list_update["t"] = strlen($RootTemplate)? $RootTemplate : $target_template;
$nav = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">$cat_name</a>"; }
else
$nav = "<span class=\"NAV_CURRENT_ITEM\">$cat_name</span>";
}
else
{
$nav = array();
$c =& $this->GetCategory($cat);
$nav_unparsed = $c->Get("ParentPath");
if(strlen($nav_unparsed)==0)
{
$c->UpdateCachedPath();
$nav_unparsed = $c->Get("ParentPath");
}
//echo " Before $nav_unparsed ";
if($root)
{
$r =& $this->GetCategory($root);
$rpath = $r->Get("ParentPath");
$nav_unparsed = substr($nav_unparsed,strlen($rpath),-1);
$cat_name = $r->Get("Name");
$m_var_list_update["cat"] = $root;
if($cat == $catid && !$LinkLeaf)
{
$nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>"; //href=\"browse.php?env=". BuildEnv() ."\"
}
else
{
if ($admin == 1)
{
$nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
}
else
{
if(strlen($RootTemplate))
{
$var_list_update["t"] = $RootTemplate;
}
else
{
$var_list_update["t"] = $target_template;
}
$nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
}
}
}
else
{
$nav_unparsed = substr($nav_unparsed,1,-1);
$cat_name = language($objConfig->Get("Root_Name"));
$m_var_list_update["cat"] = 0;
if($cat == 0)
{
$nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>"; //href=\"browse.php?env=". BuildEnv() ."\"
}
else
{
if ($admin == 1)
{
$nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
}
else
{
if(strlen($RootTemplate))
{
$var_list_update["t"] = $RootTemplate;
}
else
$var_list_update["t"] = $target_template;
$nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
}
}
}
//echo " After $nav_unparsed <br>\n";
if(strlen($target_template)==0)
$target_template = $var_list["t"];
$cats = explode("|", $nav_unparsed);
foreach($cats as $catid)
{
if($catid)
{
$c =& $this->GetCategory($catid);
if(is_object($c))
{
$cat_name = $c->Get("Name");
$m_var_list_update["cat"] = $catid;
if($catid==$modcat && strlen($ModTemplate)>0)
{
$t = $ModTemplate;
}
else
$t = $target_template;
if($cat == $catid && !$LinkLeaf)
{
$nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>";
}
else
{
if ($admin == 1)
{
$nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
}
else
{
$var_list_update["t"] = $t;
$nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
unset($var_list_update["t"]);
}
}
unset($m_var_list_update["cat"]);
}
}
}
$nav = implode($separator, $nav);
}
return $nav;
}
function &Add($ParentId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $New, $Pop,
$Priority, $MetaKeywords,$MetaDesc)
{
global $objSession;
$UserId = $objSession->Get("UserId");
$d = new clsCategory(NULL);
$d->tablename = $this->SourceTable;
if($d->UsingTempTable())
$d->Set("CategoryId",-1);
$d->idfield = "CategoryId";
$d->Set(array("ParentId", "Name", "Description", "CreatedOn", "EditorsPick", "Status", "HotItem",
"NewItem","PopItem", "Priority", "MetaKeywords", "MetaDescription", "CreatedById"),
array($ParentId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $New,
$Pop, $Priority, $MetaKeywords,$MetaDesc, $UserId));
$d->Create();
if($Status==1)
{
$d->SendUserEventMail("CATEGORY.ADD",$objSession->Get("PortalUserId"));
$d->SendAdminEventMail("CATEGORY.ADD");
}
else
{
$d->SendUserEventMail("CATEGORY.ADD.PENDING",$objSession->Get("PortalUserId"));
$d->SendAdminEventMail("CATEGORY.ADD.PENDING");
}
$d->UpdateCachedPath();
//RunUp($ParentId, "Increment_Count");
return $d;
}
function &Edit_Category($CategoryId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot,
$NewItem, $Pop, $Priority, $MetaKeywords,$MetaDesc)
{
$d =& $this->GetCategory($CategoryId);
$d->Set(array("Name", "Description", "CreatedOn", "EditorsPick", "Status", "HotItem",
"NewItem", "PopItem", "Priority", "MetaKeywords","MetaDescription"),
array($Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $NewItem,
$Pop, $Priority, $MetaKeywords,$MetaDesc));
$d->Update();
$d->UpdateCachedPath();
return $d;
}
function Move_Category($Id, $ParentTo)
{
global $objCatList;
$d =& $this->GetCategory($Id);
$oldparent = $d->Get("ParentId");
$ChildList = $d->GetSubCatIds();
/*
echo "Target Parent Id: $ParentTo <br>\n";
echo "<PRE>";print_r($ChildList); echo "</PRE>";
echo "Old Parent: $oldparent <br>\n";
echo "ID: $Id <br>\n";
*/
/* sanity checks */
if(!in_array($ParentTo,$ChildList) && $oldparent != $ParentTo && $oldparent != $Id &&
$Id != $ParentTo)
{
$d->Set("ParentId", $ParentTo);
$d->Update();
$d->UpdateCachedPath();
RunUp($oldparent, "Decrement_Count");
RunUp($ParentTo, "Increment_Count");
RunDown($ParentTo, "UpdateCachedPath");
return TRUE;
}
else
{
global $Errors;
$Errors->AddAdminUserError("la_error_move_subcategory");
return FALSE;
}
die();
}
function Copy_CategoryTree($Id, $ParentTo)
{
global $PastedCatIds;
$new = $this->Copy_Category($Id, $ParentTo);
if($new)
{
$PastedCatIds[$Id] = $new;
$sql = "SELECT CategoryId from ".GetTablePrefix()."Category where ParentId=$Id";
$result = $this->adodbConnection->Execute($sql);
if ($result && !$result->EOF)
{
while(!$result->EOF)
{
$this->Copy_CategoryTree($result->fields["CategoryId"], $new);
$result->MoveNext();
}
}
}
return $new;
}
function Copy_Category($Id, $ParentTo)
{
global $objGroups;
$src = $this->GetCategory($Id);
$Children = $src->GetSubCatIds();
if($Id==$ParentTo || in_array($ParentTo,$Children))
{
/* sanity error here */
global $Errors;
$Errors->AddAdminUserError("la_error_copy_subcategory");
return 0;
}
$dest = $src;
$dest->Set("ParentId", $ParentTo);
if ($src->get("ParentId") == $ParentTo)
{
$OldName = $src->Get("Name");
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;
//echo "New Name: $Name<br>";
$dest->Set("Name", $Name);
$Names = CategoryNameCount($ParentTo,$Name);
//echo "Names Count: ".count($Names)."<br>";
if(count($Names)>0)
{
$NameCount = count($Names);
$found = FALSE;
$NewName = "Copy of $Name";
if(!in_array($NewName,$Names))
{
//echo "Matched on $NewName in:<br>\n";
$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";
}
//echo "New Name: $NewName<br>";
$dest->Set("Name",$NewName);
}
}
$dest->UnsetIdField();
$dest->Set("CachedDescendantCatsQty",0);
$dest->Set("ResourceId",NULL);
$dest->Create();
$dest->UpdateCachedPath();
$p = new clsPermList();
$p->Copy_Permissions($src->Get("CategoryId"),$dest->Get("CategoryId"));
$glist = $objGroups->GetAllGroupList();
$view = $p->GetGroupPermList($dest, "CATEGORY.VIEW", $glist);
$dest->SetViewPerms("CATEGORY.VIEW",$view,$glist);
RunUp($ParentTo, "Increment_Count");
return $dest->Get("CategoryId");
}
function Delete_Category($Id)
{
global $objSession;
$d =& $this->GetCategory($Id);
if(is_object($d))
{
if($d->Get("CategoryId")==$Id)
{
$d->SendUserEventMail("CATEGORY.DELETE",$objSession->Get("PortalUserId"));
$d->SendAdminEventMail("CATEGORY.DELETE");
$p =& $this->GetCategory($d->Get("ParentId"));
RunDown($d->Get("CategoryId"), "Delete");
RunUp($p->Get("CategoryId"), "Decrement_Count");
RunUp($d->Get("CategoryId"),"ClearCacheData");
}
}
}
function PasteFromClipboard($TargetCat)
{
global $objSession;
$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++)
{
$ItemId = $item_ids[$i];
$item = $this->GetItem($item_ids[$i]);
if(!$IsCopy)
{
$this->Move_Category($ItemId, $TargetCat);
$clip = str_replace("CUT","COPY",$clip);
$objSession->SetVariable("ClipBoard",$clip);
}
else
{
$this->Copy_CategoryTree($ItemId,$TargetCat);
}
}
}
}
function NumChildren($ParentID)
{
$cat_filter = "m_cat_filter";
global $$cat_filter;
$filter = $$cat_filter;
$adodbConnection = &GetADODBConnection();
$sql = "SELECT COUNT(Name) as children from ".$this->SourceTable." where ParentId=" . $ParentID . $filter;
$result = $adodbConnection->Execute($sql);
return $result->fields["children"];
}
function UpdateMissingCacheData()
{
$rs = $this->adodbConnection->Execute("SELECT * FROM ".$this->SourceTable." WHERE ParentPath IS NULL or ParentPath=''");
while($rs && !$rs->EOF)
{
$c = new clsCategory(NULL);
$data = $rs->fields;
$c->SetFromArray($data);
$c->UpdateCachedPath();
$rs->MoveNext();
}
$rs = $this->adodbConnection->Execute("SELECT * FROM ".$this->SourceTable." WHERE CachedNavbar IS NULL or CachedNavBar=''");
while($rs && !$rs->EOF)
{
$c = new clsCategory(NULL);
$data = $rs->fields;
$c->SetFromArray($data);
$c->UpdateCachedPath();
$rs->MoveNext();
}
}
function CopyFromEditTable($idfield)
{
global $objGroups, $objSession, $objPermList;
-
+ $GLOBALS['_CopyFromEditTable']=1;
$objPermList = new clsPermList();
$edit_table = $objSession->GetEditTable($this->SourceTable);
$sql = "SELECT * FROM $edit_table";
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = new $this->classname;
$c->SetFromArray($data);
$c->Dirty();
if($c->Get("CategoryId")>0)
{
$c->Update();
}
else
{
$c->UnsetIdField();
$c->Create();
$sql = "UPDATE ".GetTablePrefix()."Permissions SET CatId=".$c->Get("CategoryId")." WHERE CatId=-1";
$this->adodbConnection->Execute($sql);
}
$c->UpdateCachedPath();
$c->UpdateACL();
$c->SendUserEventMail("CATEGORY.MODIFY",$objSession->Get("PortalUserId"));
$c->SendAdminEventMail("CATEGORY.MODIFY");
$c->Related = new clsRelationshipList();
if(is_object($c->Related))
{
$r = $c->Related;
$r->CopyFromEditTable($c->Get("ResourceId"));
}
//RunDown($c->Get("CategoryId"),"UpdateCachedPath");
//RunDown($c->Get("CategoryId"),"UpdateACL");
unset($c);
unset($r);
$rs->MoveNext();
}
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
+ unset($GLOBALS['_CopyFromEditTable']);
//$this->UpdateMissingCacheData();
}
function PurgeEditTable($idfield)
{
parent::PurgeEditTable($idfield);
$sql = "DELETE FROM ".GetTablePrefix()."Permissions WHERE CatId=-1";
$this->adodbConnection->Execute($sql);
}
function GetExclusiveType($CatId)
{
global $objItemTypes, $objConfig;
$itemtype = NULL;
$c =& $this->GetItem($CatId);
$path = $c->Get("ParentPath");
foreach($objItemTypes->Items as $Type)
{
$RootVar = $Type->Get("ItemName")."_Root";
$RootId = $objConfig->Get($RootVar);
if((int)$RootId)
{
$rcat = $this->GetItem($RootId);
$rpath = $rcat->Get("ParentPath");
$p = substr($path,0,strlen($rpath));
//echo $rpath." vs. .$p [$path]<br>\n";
if($rpath==$p)
{
$itemtype = $Type;
break;
}
}
}
return $itemtype;
}
}
function RunUp($Id, $function, $Param=NULL)
{
global $objCatList;
$d = $objCatList->GetCategory($Id);
$ParentId = $d->Get("ParentId");
if ($ParentId == 0)
{
if($Param == NULL)
{
$d->$function();
}
else
{
$d->$function($Param);
}
}
else
{
RunUp($ParentId, $function, $Param);
if($Param == NULL)
{
$d->$function();
}
else
{
$d->$function($Param);
}
}
}
function RunDown($Id, $function, $Param=NULL)
{
global $objCatList;
$adodbConnection = &GetADODBConnection();
$sql = "select CategoryId from ".GetTablePrefix()."Category where ParentId='$Id'";
$rs = $adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
RunDown($rs->fields["CategoryId"], $function, $Param);
$rs->MoveNext();
}
$d = $objCatList->GetCategory($Id);
if($Param == NULL)
{
$d->$function();
}
else
$d->$function($Param);
}
?>
\ No newline at end of file
Property changes on: trunk/kernel/include/category.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.12
\ No newline at end of property
+1.13
\ No newline at end of property
Index: trunk/kernel/include/itemreview.php
===================================================================
--- trunk/kernel/include/itemreview.php (revision 700)
+++ trunk/kernel/include/itemreview.php (revision 701)
@@ -1,618 +1,620 @@
<?php
function ip_exists($ip,$id,$SourceTable)
{
$count = 0;
$sql = "SELECT count(*) as DupCount FROM $SourceTable WHERE IPAddress='$ip' and ItemId=$id";
$adodbConnection = &GetADODBConnection();
$rs = $adodbConnection->Execute($sql);
if($rs)
{
$count = $rs->fields["DupCount"];
}
return ($count>0);
}
RegisterPrefix("clsItemReview","review","kernel/include/itemreview.php");
class clsItemReview extends clsParsedItem
{
function clsItemReview($ReviewId=NULL,$table="ItemReview")
{
$this->clsParsedItem();
$this->tablename = $table;
$this->id_field = "ReviewId";
$this->type=-20;
$this->NoResourceId=1;
$this->TagPrefix = "review";
if($ReviewId!=NULL)
$this->LoadFromDatabase($ReviewId);
}
function Validate()
{
global $Errors;
$dataValid = true;
if(!isset($this->m_CreatedOn))
{
$Errors->AddError("error.fieldIsRequired",'CreatedOn',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_ReviewText))
{
$Errors->AddError("error.fieldIsRequired",'ReviewText',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_Pending))
{
$Error->AddError("error.fieldIsRequired",'Pending',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_IPAddress))
{
$Error->AddError("error.fieldIsRequired",'IPAddress',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_ItemId))
{
$Error->AddError("error.fieldIsRequired",'ItemId',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_CreatedById))
{
$Error->AddError("error.fieldIsRequired",'CreatedBy',"","",get_class($this),"Validate");
$dataValid = false;
}
return $dataValid;
}
function LoadFromDatabase($Id)
{
global $objSession, $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ReviewId = '%s'",$Id);
if( $GLOBALS['debuglevel'] ) echo $sql."<br>";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
if(is_array($data))
$this->SetFromArray($data);
$this->Clean();
return TRUE;
}
function MoveUp()
{
$this->Increment("Priority");
}
function MoveDown()
{
$this->Decrement("Priority");
}
function ParseObject($element)
{
global $objConfig, $objCatList, $rootURL, $objUsers;
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
switch($field)
{
case "id":
/*
@field:review.id
@description: review id
*/
$ret = $this->Get("ReviewId");
break;
case "item_id":
/*
@field:review.item_id
@description: ID of the item being reviewed
*/
$ret = $this->Get("ItemId");
break;
case "text":
/*
@field:review.text
@description:Review text
*/
if($this->Get("TextFormat")==0 || $element->attribues["_textonly"])
{
$ret = inp_htmlize($this->Get("ReviewText"));
}
else
{
$ret = $this->Get("ReviewText");
}
break;
case "ip":
/*
@field:review.ip
@description:IP address of remote host submitting the review
*/
$ret = $this->Get("IPAddress");
break;
case "pending":
/*
@field:review.pending
@description: Returns the review pening status
*/
$ret = $this->Get("Pending");
break;
case "item_type":
/*
@field:review.item_type
@description:Returns the name of the reviewed item type
*/
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
if(is_object($type))
$ret = $type->Get("ItemName");
break;
case "date":
/*
@field:review.date
@description:Returns the date/time the review was created
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$d = $this->Get("CreatedOn");
if($element->attributes["_tz"])
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower($element->attributes["_part"]);
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if($d<=0)
{
$ret = "";
}
else
$ret = LangDate($d);
}
break;
case "reviewer":
/*
@field:revier.reviewer
@description:Parse a user tag for the user submitting the review
@attrib:_usertag::User tag to parse, defaults to the users login name
*/
$userfield = $element->attributes["_usertag"];
if(!strlen($userfield))
{
$userfield = "login";
}
if($this->Get("CreatedById")>0)
{
$u =& $objUsers->GetItem($this->Get("CreatedById"));
$e = new clsHtmlTag();
$e->name = $u->TagPrefix;
$e->attributes = $element->attributes;
$e->attributes["_field"] = $userfield;
$ret = $u->ParseObject($e);
}
else
if($userfield=="login")
$ret = "root";
break;
default:
$tag = $this->TagPrefix."_".$field;
$ret = "Undefined: ".$tag->name;
break;
}
}
else
{
$ret = $element->Execute();
}
return $ret;
}
function parsetag($tag)
{
global $objConfig, $objUsers, $objItemTypes;
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "review_id":
return $this->Get("ReviewId");
break;
case "review_item_id":
return $this->Get("ItemId");
break;
case "review_text":
return $this->Get("ReviewText");
break;
case "review_ip_address":
return $this->Get("IPAddress");
break;
case "review_pending":
return $this->Get("Pending");
break;
case "review_item_type":
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
$res = $type->Get("ItemName");
return $res;
break;
case "review_created_date":
return LangDate($this->Get("CreatedOn"));
break;
case "review_created_time":
if($this->Get("CreatedOn")<=0)
return "";
return adodb_date($objConfig->TimeFormat(), $this->Get("CreatedOn"));
break;
case "review_created_date_month":
return adodb_date("m", $this->Get("CreatedOn"));
break;
case "review_created_date_day":
return adodb_date("d", $this->Get("CreatedOn"));
break;
case "review_created_date_year":
return adodb_date("Y", $this->Get("CreatedOn"));
break;
default:
if (substr($tagname, 0, 16) == "review_createdby")
{
/* parse the created by user */
$u = $objUsers->GetUser($this->Get("CreatedById"));
$usertag = substr($tag,17);
return $u->parsetag($usertag);
}
else
return "Undefined:$tagname";
break;
}
}
function SendUserEventMail($Suffix,$ToUserId,$LangId=NULL)
{
global $objItemTypes, $objMessageList;
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
$res = $type->Get("ItemName");
$EventName = $res.$Suffix;
$Event =& $objMessageList->GetEmailEventObject($EventName,0,$LangId);
if(is_object($Event))
{
if($Event->Get("Enabled")=="1")
{
$Event->Item = $this;
return $Event->SendToUser($ToUserId);
}
}
}
function SendAdminEventMail($EventName,$LangId=NULL)
{
global $objItemTypes, $objMessageList;
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
$res = $type->Get("ItemName");
$EventName = $res; //.$Suffix;
$Event =& $objMessageList->GetEmailEventObject($EventName,1,$LangId);
if(is_object($Event))
{
if($Event->Get("Enabled")=="1")
{
$Event->Item = $this;
return $Event->SendAdmin($ToUserId);
}
}
}
} /*clsIItemReview*/
class clsItemReviewList extends clsItemCollection
{
var $itemID;
var $Page;
var $PerPageVar;
function clsItemReviewList($id=NULL)
{
$this->clsItemCollection();
$this->classname = "clsItemReview";
$this->SourceTable = GetTablePrefix()."ItemReview";
$this->Page = 1;
$this->PerPageVar = "Perpage_Review";
if(isset($id))
$this->itemID=$id;
$this->AdminSearchFields = array("ReviewText");
}
function ItemCount()
{
return $this->NumItems();
}
function GetReview($ID)
{
return $this->GetItem($ID);
}
function GetReviewList($StatusWhere = "Status=1", $OrderBy=NULL)
{
$this->Clear();
$where = "ItemId=".$this->itemID;
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ";
if(strlen($StatusWhere))
$where .= " AND ".$StatusWhere;
$sql .= $where;
if(strlen($OrderBy))
$sql .= " ORDER BY ".$OrderBy;
$Limit = $this->GetLimitSQL();
if(strlen($Limit))
$sql .= " ".$Limit;
$this->QueryItemCount=TableCount($this->SourceTable,$where,0);
return $this->Query_item($sql);
}
function GetItemReviewCount($TodayOnly = FALSE)
{
$sql = "SELECT count(*) as ItemCount FROM ".$this->SourceTable." WHERE ItemId=".$this->itemID." AND Status=1";
if($TodayOnly)
{
$today = mktime(0,0,0,date("m"),date("d"),date("Y"));
$where .= " AND CreatedOn>=$today";
}
$rs = $this->adodbConnection->execute($sql);
$count=0;
if($rs)
$count = $rs->fields["ItemCount"];
return (int)$count;
}
function ip_exists($ip,$id)
{
return ip_exists($ip,id,$this->SourceTable);
}
function GetLimitSQL()
{
global $objConfig;
if($this->Page<1)
$this->Page=1;
$PerPage = $objConfig->Get($this->PerPageVar);
if(is_numeric($PerPage))
{
$Start = ($this->Page-1)*$PerPage;
$limit = "LIMIT ".$Start.",".$PerPage;
}
else
$limit = NULL;
return $limit;
}
function Query_Review($whereClause=NULL,$orderByClause=NULL)
{
global $Errors;
$this->Clear();
$sql = "SELECT * FROM ".$this->SourceTable." ";
if(isset($whereClause) && strlen(trim($whereClause))>0)
$sql = sprintf("%s WHERE %s",$sql,$whereClause);
if(isset($orderByClause) && strlen(trim($orderByClause))>0)
$sql = sprintf("%s ORDER BY %s",$sql,$orderByClause);
return $this->Query_Item($sql);
}
function &AddReview($CreatedOn,$ReviewText, $Status, $IPAddress,
$Priority, $ItemId,$ItemType,$CreatedById,$TextFormat=0,$Module)
{
global $objSession;
$r = new clsItemReview(NULL,$this->SourceTable);
$ReviewText = str_replace("env=".$objSession->GetSessionKey(), "env=",$ReviewText);
//$r->debuglevel = 1;
$r->Set(array("CreatedOn","ReviewText","Status", "IPAddress",
"Priority","ItemId","ItemType","CreatedById","TextFormat","Module"),
array($CreatedOn,$ReviewText,$Status, $IPAddress,
$Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module));
$r->Create();
array_push($this->Items,$r);
if($Status==1)
{
$r->SendUserEventMail("REVIEW.ADD",$CreatedById);
$r->SendAdminEventMail("REVIEW.ADD");
}
else
{
$r->SendUserEventMail("REVIEW.ADD.PENDING",$CreatedById);
$r->SendAdminEventMail("REVIEW.ADD.PENDING");
}
return $r;
}
function EditReview($ReviewId,$CreatedOn,$ReviewText, $Status,
$IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module)
{
global $objSession;
$r = $this->GetItem($ReviewId);
if($CreatedById==0)
$CreatedById = $r->Get("CreatedById");
$r->Set(array("ReviewId","CreatedOn","ReviewText","Status",
"IPAddress", "Priority", "ItemId","ItemType","CreatedById","TextFormat","Module"),
array($ReviewId,$CreatedOn,$ReviewText,$Status,
$IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module));
$r->Update();
//$r->SendUserEventMail("REVIEW.MODIFY",$objSession->Get("PortalUserId"));
$r->SendAdminEventMail("REVIEW.MODIFY");
return $r;
}
function DeleteReview($ReviewId)
{
$r = $this->GetItem($ReviewId);
$r->Delete();
}
function CopyToItemId($OldId,$NewId)
{
$this->Clear();
$this->Query_Review("ItemId=$OldId","");
if($this->NumItems()>0)
{
foreach($this->Items as $i)
{
$i->Set("ItemId",$NewId);
$i->UnsetIdField();
$i->Create();
}
}
}
function CopyFromEditTable($ResourceId)
{
global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
//echo "ToLive [Reviews]<br>";
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
$sql = "SELECT * FROM $edit_table";
$this->Clear();
// get all items in edit-table
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data =& $rs->fields;
$c = $this->AddItemFromArray($data);
$c->Dirty();
if($data["ReviewId"]>0)
{
$c->Update();
}
else
{
$c->UnsetIdField();
$c->Create();
}
$idlist[] = $c->Get("ReviewId");
$rs->MoveNext();
}
//print_pre($idlist);
$sql = "DELETE FROM ".$this->SourceTable." WHERE ItemId=$ResourceId ".(count($idlist) > 0 ? "AND ReviewId NOT IN (".implode(",",$idlist).")" : "");
//echo "DEL REVIEW SQL: $sql<br>";
$this->adodbConnection->Execute($sql);
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$edit_table);
+ unset($GLOBALS['_CopyFromEditTable']);
}
function GetPageLinkList(&$UpdateVar,$dest_template=NULL,$page = NULL,$PagesToList=10,$HideEmpty=TRUE)
{
global $objConfig, $var_list_update, $var_list;
if(!strlen($page))
$page = GetIndexURL();
$PerPage = $objConfig->Get($this->PerPageVar);
if($PerPage<1)
$PerPage=20;
$NumPages = ceil($this->GetNumPages($PerPage));
if($NumPages==1 && $HideEmpty)
return "";
if(strlen($dest_template))
{
$var_list_update["t"] = $dest_template;
}
else
$var_list_update["t"] = $var_list["t"];
$o = "";
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)
{
$UpdateVar["rp"] = $this->Page-$PagesToList;
$prev_url = $page."?env=".BuildEnv();
$o .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
}
for($p=$StartPage;$p<=$EndPage;$p++)
{
if($p!=$this->Page)
{
$UpdateVar["rp"]=$p;
$href = $page."?env=".BuildEnv();
$o .= " <A HREF=\"$href\" >$p</A> ";
}
else
{
$o .= "$p";
}
}
if($EndPage<$NumPages && $EndPage>0)
{
$UpdateVar["rp"]=$this->Page+$PagesToList;
$next_url = $page."?env=".BuildEnv();
$o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
}
unset($UpdateVar,$var_list_update["t"] );
return $o;
}
} /*clsItemReviewList*/
?>
\ No newline at end of file
Property changes on: trunk/kernel/include/itemreview.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.11
\ No newline at end of property
+1.12
\ No newline at end of property
Index: trunk/kernel/include/portaluser.php
===================================================================
--- trunk/kernel/include/portaluser.php (revision 700)
+++ trunk/kernel/include/portaluser.php (revision 701)
@@ -1,1020 +1,1022 @@
<?php
RegisterPrefix("clsPortalUser","user","kernel/include/portaluser.php");
class clsPortalUser extends clsItem
{
var $Vars; //contains the PersistantSessionData for the user
var $VarsLoaded;
var $PrimeGroup;
function clsPortalUser($UserId=NULL)
{
$this->clsParsedItem();
$this->tablename=GetTablePrefix()."PortalUser";
$this->type=6;
$this->BasePermission="USER";
$this->id_field = "PortalUserId";
$this->TagPrefix="user";
$this->Vars = array();
$VarsLoaded = FALSE;
$this->debuglevel = 0;
if(isset($UserId))
$this->LoadFromDatabase($UserId);
}
function Delete()
{
global $objGroups, $objFavorites;
$g = $objGroups->GetPersonalGroup($this->Get("Login"));
if(is_object($g))
$g->Delete();
$objFavorites->DeleteUser($this->Get("PortalUserId")); //delete favorites
parent::Delete();
}
function RemoveFromAllGroups()
{
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortaluserId=".$this->Get("PortalUserId");
$this->adodbConnection->Execute($sql);
}
function RemoveFromGroup($GroupId)
{
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortaluserId=".$this->Get("PortalUserId");
$sql .= " AND GroupId=$GroupId";
$this->adodbConnection->Execute($sql);
}
function PrimaryGroup($ReturnField = "GroupId")
{
global $objGroups;
$ret = "";
if(!is_object($this->PrimeGroup))
{
if((int)$this->Get("GroupId")>0)
{
$this->PrimeGroup =& $objGroups->GetItem($this->Get("GroupId"));
}
else
{
$this->PrimeGroup = new clsPortalGroup();
$sql = "SELECT * FROM ".GetTablePrefix()."UserGroup INNER JOIN ".GetTablePrefix()."PortalGroup ON (".GetTablePrefix()."UserGroup.GroupId=".GetTablePrefix()."PortalGroup.GroupId) WHERE PrimaryGroup = 1 AND PortalUserId=".$this->Get("PortalUserId");
//echo $sql;
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
$this->PrimeGroup->SetFromArray($rs->fields);
}
}
$ret = $this->PrimeGroup->Get($ReturnField);
return $ret;
}
function SetPrimaryGroup($GroupId)
{
if($this->IsInGroup($GroupId))
{
$sql = "UPDATE ".GetTablePrefix()."UserGroup SET PrimaryGroup=0 WHERE PortalUserId=".$this->Get("PortalUserId");
$this->adodbConnection->Execute($sql);
$sql = "UPDATE ".GetTablePrefix()."UserGroup SET PrimaryGroup=1 WHERE GroupId=$GroupId AND PortalUserId=".$this->Get("PortalUserId");
$this->adodbConnection->Execute($sql);
}
}
function GetGroupList()
{
$ret = array();
$sql = "SELECT GroupId FROM %sUserGroup WHERE PortalUserId = %s ORDER BY PrimaryGroup";
$sql = sprintf($sql, GetTablePrefix(), $this->Get("PortalUserId"));
$ret = $this->adodbConnection->GetCol($sql);
return $ret;
}
function IsInGroup($GroupId)
{
$groups = $this->GetGroupList();
if( $groups === false ) return false;
return in_array($GroupId, $groups) ? true : false;
}
function GetPersonalGroup($CreateIfMissing = FALSE)
{
global $objGroups;
$n = "_".$this->Get("Login");
$g = $objGroups->GetItemByField("Name",$n);
if(!is_object($g) && $CreateIfMissing)
$g = $this->CreatePersonalGroup();
return $g;
}
function CreatePersonalGroup()
{
global $objGroups;
$Description = $this->Get("FirstName")." ".$this->Get("LastName");
$CreatedOn=time();
$n = "_".$this->Get("Login");
$g = $objGroups->Add_Group($n, $Description, $CreatedOn, 1, 0);
$g->Set("Personal",1);
$g->Set("System",0);
$g->Set("Enabled",1);
$g->Update();
if(is_object($g))
$g->AddUser($this->Get("PortalUserId"));
return $g;
}
function Validate()
{
global $Errors;
$dataValid = true;
if(!strlen($this->Get("Login")))
{
$Errors->AddError("error.fieldIsRequired",'Login',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!strlen($this->Get("Email")))
{
$Errors->AddError("error.fieldIsRequired",'Email',"","",get_class($this),"Validate");
$dataValid = false;
}
return $dataValid;
}
function Approve()
{
$this->Set("Status", 1);
$this->Update();
$this->SendUserEventMail("USER.APPROVE",$this->Get("PortalUserId"));
$this->SendAdminEventMail("USER.APPROVE");
}
function Deny($IsBanned = 0)
{
$this->Set( Array('Status','IsBanned'), Array(0,$IsBanned) );
$this->Update();
$this->SendUserEventMail("USER.DENY",$this->Get("PortalUserId"));
$this->SendAdminEventMail("USER.DENY");
}
function HasSystemPermission($PermissionName)
{
global $objGroups;
$GroupList = $this->GetGroupList();
for($i=0;$i<count($GroupList);$i++)
{
$g = $objGroups->GetItem($GroupList[$i]);
$value = $g->HasSystemPermission($PermissionName);
if($value != -1)
break;
}
return $value;
}
function LoadPersistantVars()
{
global $objConfig;
unset($this->Vars);
$this->Vars = array();
$user_id = $this->HasField('PortalUserId') ? $this->Get('PortalUserId') : 0;
$sql = "SELECT VariableName, VariableValue FROM ".GetTablePrefix()."PersistantSessionData WHERE PortalUserId = 0 OR PortalUserId = ".$user_id." ORDER BY PortalUserId ASC";
$result = $this->adodbConnection->Execute($sql);
while ($result && !$result->EOF)
{
$data = $result->fields;
$this->Vars[$data["VariableName"]] = $data["VariableValue"];
$objConfig->Set($data["VariableName"], $data["VariableValue"], 1, 1);
$result->MoveNext();
}
$this->VarsLoaded=TRUE;
}
function SetPersistantVariable($variableName, $variableValue)
{
global $objConfig;
if(!$this->VarsLoaded)
$this->LoadPersistantVars();
$userid = $this->Get("PortalUserId");
$objConfig->Set($variableName,$variableValue,1);
$fields = array_keys($this->Vars);
if(strlen($variableValue)>0)
{
if(in_array($variableName,$fields))
{
$sql = "UPDATE ".GetTablePrefix()."PersistantSessionData SET VariableValue='$variableValue' WHERE VariableName='$variableName' AND PortalUserId=$userid";
}
else
$sql = "INSERT INTO ".GetTablePrefix()."PersistantSessionData (VariableName,VariableValue,PortalUserId) VALUES ('$variableName','$variableValue',$userid)";
}
else
$sql = "DELETE FROM ".GetTablePrefix()."PersistantSessionData WHERE VariableName='$variableName' AND PortalUserId=$userid";
$this->Vars[$variableName] = $variableValue;
// echo "<BR>SQL: $sql<BR>";
$this->adodbConnection->Execute($sql);
}
function GetPersistantVariable($variableName)
{
global $objConfig, $objSession;
if(!$this->VarsLoaded)
$this->LoadPersistantVars();
$fields = array_keys($this->Vars);
if(in_array($variableName,$fields))
{
$val = $this->Vars[$variableName];
}
else
{
if( $this->UniqueId() == $objSession->Get('PortalUserId') )
{
$val = $objConfig->Get($variableName);
}
else
{
$val = '';
}
}
return $val;
}
function GetAllPersistantVars()
{
if(!$this->VarsLoaded)
$this->LoadPersistantVars();
return $this->Vars;
}
function GetIcon()
{
}
function StatusIcon()
{
global $imagesURL;
$url = $imagesURL."/itemicons/icon16_user";
if($this->Get("Status")==0)
{
$url .= "_disabled";
}
else
if($this->Get("Status")==2)
{
$url .= "_pending";
}
$url .= ".gif";
return $url;
}
function IsFriend($UserId)
{
$ftable = GetTablePrefix()."Favorites";
$sql = "SELECT count(*) as FriendCount FROM $ftable WHERE PortalUserId=$UserId AND ResourceId=";
$sql .=$this->Get("ResourceId")." AND ItemTypeId=6";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
return ($rs->fields["FriendCount"]>0);
return FALSE;
}
function GetUserTime($timestamp)
{
if(is_numeric($this->Get("tz")))
{
return GetLocalTime($timestamp,$this->Get("tz"));
}
else
return GetLocalTime($timestamp);
}
function ParseObject($element)
{
global $objConfig, $objUsers, $objCatList,$objSession, $var_list_update, $var_list, $m_var_list_update;
//echo "<PRE>"; print_r($element); echo "</pre>";
//echo "Tag Prefix: ".$this->TagPrefix." Element: ".$element->name."<br>";
if (strtolower($element->name) == 'touser') {
$this->TagPrefix = "touser";
}
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
if(substr($field,0,3)=="pp_")
{
$perm = $objSession->GetPersistantVariable($field);
if($perm)
{
$field = substr($field,3);
}
else
$field = "";
}
switch($field)
{
/*
@field:user.login
@description:User's login name
*/
case "username":
case "login":
$ret = $this->Get("Login");
break;
case "firstname":
$ret = $this->Get("FirstName");
break;
case "lastname":
$ret = $this->Get("LastName");
break;
case "password":
/*
@field:user.password
@description:User password
*/
$ret = $objSession->Get("password");
$objSession->Set("password", '');
break;
case "email":
$ret = $this->Get("Email");
break;
case "street":
$ret = $this->Get("Street");
break;
case "city":
$ret = $this->Get("City");
break;
case "state":
$ret = $this->Get("State");
break;
case "zip":
$ret = $this->Get("Zip");
break;
case "phone":
$ret = $this->Get("Phone");
break;
case "country":
$ret = $this->Get("Country");
break;
case "primarygroup":
/*
@field:user.primarygroup
@description:Parses a field from the user's primary group
@attrib:_groupfield::group field name to parse, defaults to group name
*/
$groupfield = $element->attributes["_groupfield"];
if(!strlen($groupfield))
$groupfield="Name";
$ret = $this->PrimaryGroup($groupfield);
break;
case "date":
/*
@field:user.date
@description:Returns the date/time the user was created
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$d = $this->Get("CreatedOn");
if($element->attributes["_tz"])
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower($element->attributes["_part"]);
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if($d<=0)
{
$ret = "";
}
else
$ret = LangDate($d);
}
break;
case "dob":
/*
@field:user.dob
@description:Returns the date/time of the users date of birth
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$d = $this->Get("dob");
if($element->attributes["_tz"])
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower($element->attributes["_part"]);
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
// if($d<=0)
// {
// $ret = "";
// }
// else
$ret = LangDate($d);
}
break;
case "modified":
/*
@field:user.modified
@description:Returns the date/time the user was last modified
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$d = $this->Get("Modified");
if($d<=0)
$d = $this->Get("CreatedOn");
if($element->attributes["_tz"])
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower($element->attributes["_part"]);
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if($d<=0)
{
$ret = "";
}
else
$ret = LangDate($d);
}
break;
case 'send_pm_link':
$var_list_update['t'] = $element->GetAttributeByName('_Template');
$ret = GetIndexURL()."?env=".BuildEnv()."&ToUser=".$this->Get('Login');
break;
case "profile_link":
/*
@field:user.profile_link
@description:Create a link to the user's profile
@attrib:_template:tpl:template the link should point to
*/
$t = $element->attributes["_template"];
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$ret = GetIndexURL()."?env=" . BuildEnv()."&UserId=".$this->Get("PortalUserId");
break;
case "add_friend_link":
/*
@field:user.add_friend_link
@description:link to add a user to the friends list
@attrib:_template:tpl:Template link shoukd point to
*/
if($element->attributes["_force"] || !$this->IsFriend($objSession->Get("PortalUserId")) &&
$this->Get("PortalUserId") != $objSession->Get("PortalUserId"))
{
$t = $element->attributes["_template"];
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$action = "m_add_friend";
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=".$action."&UserId=".$this->Get("PortalUserId");
}
else
$ret = "";
break;
case "del_friend_link":
/*
@field:user.del_friend_link
@description:link to remove a user from the friends list
@attrib:_template:tpl:Template link shoukd point to
*/
if($element->attributes["_force"] || $this->IsFriend($objSession->Get("PortalUserId")) &&
$this->Get("PortalUserId") != $objSession->Get("PortalUserId"))
{
$t = $element->attributes["_template"];
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$action = "m_del_friend";
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=".$action."&UserId=".$this->Get("PortalUserId");
}
else
$ret = "";
break;
case "icon":
$ret = $this->GetIcon();
break;
case "image":
/*
@field:user.image
@description:Return an image associated with the user
@attrib:_default:bool:If true, will return the default image if the requested image does not exist
@attrib:_name::Return the image with this name
@attrib:_thumbnail:bool:If true, return the thumbnail version of the image
@attrib:_imagetag:bool:If true, returns a complete image tag. exta html attributes are passed to the image tag
*/
$default = $element->attributes["_primary"];
$name = $element->attributes["_name"];
if(strlen($name))
{
$img = $this->GetImageByName($name);
// echo "<PRE>";print_r($img); echo "</PRE>";
}
else
{
if($default)
$img = $this->GetDefaultImage();
}
if($img)
{
if($element->attributes["_thumbnail"])
{
$url = $img->parsetag("thumb_url");
}
else
$url = $img->parsetag("image_url");
}
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 "custom":
/*
@field:cat.custom
@description:Returns a custom field
@attrib:_customfield::field name to return
@attrib:_default::default value
*/
$field = $element->attributes["_customfield"];
$default = $element->attributes["
"];
$ret = $this->GetPersistantVariable($field);
if(!strlen($ret))
$ret = $this->GetCustomFieldValue($field,$default);
break;
default:
$ret = "Undefined:".$element->name;
break;
}
}
else
{
$ret = $this->parsetag($element->name);
}
return $ret;
}
function parsetag($tag)
{
global $m_var_list_update, $var_list_update, $var_list, $objConfig;
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "user_id":
return $this->Get("ResourceId");
break;
case "user_login":
return $this->Get("Login");
break;
case "user_group":
return $this->Get("PrimaryGroupName");
break;
case "user_firstname":
return $this->Get("FirstName");
break;
case "user_lastname":
return $this->Get("LastName");
break;
case "user_email":
return $this->Get("Email");
break;
case "user_date":
return LangDate($this->Get("CreatedOn"));
break;
case "user_time":
return LangTime($this->Get("CreatedOn"));
break;
case "user_dob":
return LangDate($this->Get("dob"));
break;
case "user_password":
return $this->Get("Password");
break;
case "user_phone":
return $this->Get("Phone");
break;
case "user_street":
return $this->Get("Street");
break;
case "user_city":
return $this->Get("City");
break;
case "user_state":
return $this->Get("State");
break;
case "user_zip":
return $this->Get("Zip");
break;
case "user_country":
return $this->Get("Country");
break;
case "user_resourceid":
return $this->Get("ResourceId");
break;
case "user_icon":
return $this->GetIcon();
break;
case "user_profile_link":
$var_list_update["t"] = "user_profile";
$m_var_list_update["action"] = $this->Get("UserId");
$ret = GetIndexURL()."?env=" . BuildEnv();
unset($m_var_list_update["action"], $var_list_update["t"]);
return $ret;
break;
case "user_messages":
return $this->NewMessages();
break;
case "user_messages_link":
$var_list_update["t"] = "inbulletin/bb_private_msg_list";
return GetIndexURL()."?env=" . BuildEnv();
unset($var_list_update);
break;
default:
return "Undefined:$tagname";
break;
}
}
} /* class clsPortalUser*/
class clsUserManager extends clsItemList //clsItemCollection
{
/*this class wraps common user-related functions */
// var $Page;
function clsUserManager()
{
$this->clsItemCollection(); // clsItemList() // need to use this, but double limit clause being created (normal+default 0,100)
$this->classname = "clsPortalUser";
$this->SetTable('live', GetTablePrefix().'PortalUser');
$this->Page = isset($_GET['lpn']) ? $_GET['lpn'] : 1;
$this->EnablePaging = true;
$this->PerPageVar = "Perpage_User";
$this->AdminSearchFields = array("Login","FirstName","LastName","Email","Street","City", "State","Zip","Country","Phone");
}
function GetPageLinkList($dest_template=NULL,$link_template=NULL,$page = "")
{
global $objConfig, $m_var_list_update, $var_list_update, $var_list;
if(!strlen($page))
$page = GetIndexURL();
$NumPages = $this->GetNumPages($objConfig->Get("Perpage_Topics"));
if(strlen($dest_template)>0)
{
$var_list_update["t"]=$dest_template;
}
else
{
$var_list_update["t"] = $var_list["t"];
}
$o = "";
if($this->Page>1)
{
$m_var_list_update["p"]=$this->Page-1;
$prev_url = $page."?env=".BuildEnv();
}
if($this->Page<$NumPages)
{
$m_var_list_update["p"]=$this->Page+1;
$next_url = $page."?env=".BuildEnv();
}
for($p=1;$p<=$NumPages;$p++)
{
$t = template($link_template);
if($p!=$this->Page)
{
$m_var_list_update["p"]=$p;
$href = $page."?env=".BuildEnv();
$t = str_replace("<%page_link%>", $href, $t);
$t = str_replace("<%page_number%>",$p,$t);
$t = str_replace("<%prev_url%>",$prev_url,$t);
$t = str_replace("<%next_url%>",$next_url,$t);
$o .= $t;
}
else
{
$o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
}
}
return $o;
}
function GetUser($ID)
{
$u = $this->GetItem($ID);
return $u;
}
function GetUserName($Id)
{
$rs = $this->adodbConnection->Execute("SELECT Login from ".$this->SourceTable." where PortalUserId=$Id");
return $rs->fields["Login"];
}
function GetUserId($Login)
{
$rs = $this->adodbConnection->Execute("SELECT PortalUserId from ".$this->SourceTable." where Login LIKE '$Login'");
return $rs->fields["PortalUserId"];
}
function GetTotalUsers()
{
return $this->UserCount("1");
}
function GetLatestUser()
{
global $Errors;
$sql = "SELECT max(CreatedOn) as LastDate FROM ".$this->SourceTable;
$result = $this->adodbConnection->Execute($sql);
if ($result === false || !is_object($result))
{
$Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"GetLatestUser");
return false;
}
$sql = "SELECT PortalUserId FROM ".$this->SourceTable." WHERE CreatedOn >= ".$result->fields["LastDate"];
$result = $this->adodbConnection->Execute($sql);
if (!rs || $rs->EOF)
{
$Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"GetLatestUser");
return false;
}
$u = $this->GetUser($result->fields["PortalUserId"]);
return $u;
}
function &Add_User($Login, $Password, $Email, $CreatedOn, $FirstName="", $LastName="", $Status=2,
$Phone="", $Street="", $City="", $State="", $Zip="", $Country="", $dob=0, $ip="", $CheckBanned=FALSE)
{
$u = new clsPortalUser(NULL);
$u->tablename = $this->SourceTable;
//echo "Creating User..<br>\n";
$u->Set(array("Login", "Password", "FirstName", "LastName", "Email", "Status",
"Phone","Street", "City", "State", "Zip", "Country", "CreatedOn","dob"),
array($Login, $Password, $FirstName, $LastName, $Email, $Status,
$Phone, $Street, $City, $State, $Zip, $Country, $CreatedOn, $dob));
$BrokenRule = $CheckBanned ? $u->CheckBanned() : false;
if(!$BrokenRule)
{
$u->Create();
return $u;
}
return $BrokenRule;
/*md5($Password)*/
}
function &Edit_User($UserId, $Login, $Password, $Email, $CreatedOn, $FirstName="", $LastName="",
$Status=2, $Phone="", $Street="", $City="", $State="", $Zip="", $Country="", $dob=0)
{
//echo "<font color=\"red\">Editing User: [$UserId]</font><br>";
$u =& $this->GetItem($UserId);
if(!$CreatedOn)
$CreatedOn = $u->Get("CreatedOn");
// $u->debuglevel=1;
if (is_object($u))
{
$IsBanned = $u->Get('IsBanned');
if($Status == 1) $IsBanned = 0;
$u->Set(array("Login", "FirstName", "LastName", "Email", "Status",
"Phone", "Street", "City", "State", "Zip", "Country", "CreatedOn","dob","IsBanned"),
array($Login, $FirstName, $LastName, $Email, $Status,
$Phone, $Street, $City, $State, $Zip, $Country, $CreatedOn,$dob,$IsBanned));
if(strlen($Password))
$u->Set("Password",$Password);
$u->Update();
}
return $u;
}
function Delete_User($UserId)
{
$u = $this->GetItemByField("ResourceId",$UserId);
if(is_object($u))
{
$u->RemoveFromAllGroups();
$u->Delete();
}
}
function LoadUsers($where = "",$orderBy = "")
{
global $objConfig;
$this->Clear();
if($this->Page<1)
$this->Page=1;
if(is_numeric($objConfig->Get("Perpage_Users")))
{
$Start = ($this->Page-1)*$objConfig->Get("Perpage_Users");
$limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Users");
}
else
$limit = NULL;
$where = trim($where);
$orderBy = trim($orderBy);
if(!strlen($where))
$where = "1";
$this->QueryItemCount=TableCount($this->SourceTable,$where,0);
if($this->QueryItemCount>0)
{
if ($orderBy!="")
{
$this->Query_PortalUser($where,$orderBy,$limit);
}
else
{
$this->Query_PortalUser($where,"Login DESC",$limit);
}
}
}
function Query_PortalUser($whereClause,$orderByClause="", $limitClause="")
{
global $m_var_list,$Errors, $objSession;
$resultSet = array();
$utable = $this->SourceTable;
$gtable = GetTablePrefix()."UserGroup";
$sql = "SELECT * FROM $utable LEFT JOIN $gtable ON ($utable.PortalUserId=$gtable.PortalUserId)";
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause))
if(strlen(trim($orderByClause))>0)
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
if(isset($limitClause))
$sql = sprintf('%s %s',$sql,$limitClause);
return $this->Query_Item($sql);
}
function Query_GroupPortalUser($whereClause,$orderByClause)
{
global $m_var_list,$objSession,$Errors;
$resultSet = array();
$table = $this->SourceTable;
$sql = "SELECT * FROM $table LEFT JOIN ".GetTablePrefix()."UserGroup USING (PortalUserId) ";
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause))
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
return $this->query_item($sql);
}
function UserCount($whereClause)
{
$count = TableCount($this->SourceTable,$whereClause,0);
return $count;
}
function CountActive()
{
return $this->UserCount("Status=1");
}
function CountPending()
{
return $this->UserCount("Status=2");
}
function CountDisabled()
{
return $this->UserCount("Status=0");
}
function CopyFromEditTable($idfield)
{
global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$sql = "SELECT * FROM $edit_table";
$rs = $this->adodbConnection->Execute($sql);
// echo $sql."<BR>";
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();
$c->Create();
$sql = "UPDATE ".GetTablePrefix()."UserGroup SET PortalUserId=".$c->Get("PortalUserId");
$sql .=" WHERE PortalUserId=0";
$this->adodbConnection->Execute($sql);
}
else
$c->Update();
unset($c);
$rs->MoveNext();
}
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
+ unset($GLOBALS['_CopyFromEditTable']);
}
function PurgeEditTable()
{
parent::PurgeEditTable();
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortalUserId=0";
$this->adodbConnection->Execute($sql);
}
} /*clsUserManager*/
?>
Property changes on: trunk/kernel/include/portaluser.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.17
\ No newline at end of property
+1.18
\ No newline at end of property
Index: trunk/kernel/include/relationship.php
===================================================================
--- trunk/kernel/include/relationship.php (revision 700)
+++ trunk/kernel/include/relationship.php (revision 701)
@@ -1,434 +1,436 @@
<?php
class clsRelationship extends clsItemDB
{
var $expanded;
function clsRelationship($id=NULL,$expanded=FALSE)
{
$this->clsItemDB();
$this->tablename = GetTablePrefix()."Relationship";
$this->id_field = "RelationshipId";
$this->NoResourceId = 1;
$this->expanded=FALSE;
GetModuleArray();
if($id)
{
if(!$expanded)
{
$this->LoadFromDatabase($id);
}
else
$this->LoadExpanded($id);
}
}
function LoadExpanded($id)
{
global $objModules;
$pre = GetTablePrefix();
$reltable = $this->tablename;
// ==== build sql depending on modules installed: begin ====
$prefix = GetTablePrefix();
$modules = $objModules->GetModuleList();
$sql_source = $objModules->ExecuteFunction('GetModuleInfo', 'rel_list');
$sql_templates['ItemName'] = 'IFNULL('.$prefix."%s.%s,' ')";
$sql_templates['TableJoin'] = 'LEFT JOIN '.$prefix."%1\$s ON ".$prefix."%1\$s.ResourceId = rel.TargetId";
$sql_templates['TargetName'] = "IF(rel.TargetType = %s, '%s', %s)";
$sql = "SELECT TRIM(CONCAT(%s)) AS ItemName, %s AS ItemType,".
GetELT('rel.Type+1', Array('la_Text_OneWay','la_Text_Reciprocal')).' AS RelationType,'.
"RelationshipId, rel.Priority AS Priority, rel.Type as Type, rel.Enabled as Enabled,".
"rel.TargetId, rel.TargetType, rel.SourceId, rel.SourceType,".
GetELT('rel.Enabled+1', Array('la_Text_Disabled','la_Text_Enabled')).' AS Status '.
'FROM '.$reltable.' AS rel %s WHERE rel.RelationshipId = '.$id;
$sql_parts = Array();
$sql_parts['TargetName'] = "''";
foreach($modules as $module)
{
$sql_parts['ItemName'][] = sprintf($sql_templates['ItemName'], $sql_source[$module]['MainTable'], $sql_source[$module]['ItemNameField']);
$sql_parts['TableJoin'][] = sprintf($sql_templates['TableJoin'], $sql_source[$module]['MainTable']);
$sql_parts['TargetName'] = sprintf( $sql_templates['TargetName'],
$sql_source[$module]['TargetType'],
admin_language($sql_source[$module]['ItemNamePhrase']),
$sql_parts['TargetName']);
}
$sql = sprintf($sql, implode(', ',$sql_parts['ItemName']), $sql_parts['TargetName'], implode(' ',$sql_parts['TableJoin']));
// ==== build sql depending on modules installed: end ====
//echo "SQL: ".$sql.'<br>';
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$this->SetFromArray($data);
$this->Clean();
$this->expanded=TRUE;
return TRUE;
}
else
return FALSE;
}
function LoadFromDatabase($id)
{
$table = $this->tablename;
$sql = "SELECT * FROM $table";
$sql .= " WHERE ".$this->id_field."=".$id;
$rs=$this->adodbConnection->execute($sql);
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$this->SetFromArray($data);
$this->Clean();
$this->expanded=FALSE;
return TRUE;
}
else
return FALSE;
}
function GetTargetItemData()
{
global $objItemTypes;
/*returns the table row in an array for the item this relationship points to */
$type = $this->Get("TargetType");
$Item = $objItemTypes->GetItem($type);
$table = $Item->Get("SourceTable");
$titlefield = $Item->Get("TitleField");
if(strlen($table))
{
$sql = "SELECT * FROM ".GetTablePrefix().$table." WHERE ResourceId=".$this->Get("TargetId");
$rs = $this->adodbConnection->execute($sql);
if($rs)
{
$res = $rs->fields;
$res["SourceTable"]=$table;
$res["TitleField"]=$titlefield;
return $res;
}
else
return FALSE;
}
else
return FALSE;
}
function Admin_Icon()
{
global $imagesURL;
$type = "reciprocal";
if($this->Get("Type")==0)
{
$type = "one-way";
}
$icon = $imagesURL."/itemicons/icon16_relation_".$type;
if($this->Get("Enabled")!=1)
{
$icon .= "_disabled";
}
$icon .= ".gif";
return $icon;
}
function parse_template()
{
$item = $this->GetTargetItemData();
$type=$this->Get("TargetType");
switch($type)
{
case 1:
$c = new clsCategory();
$t = "cat_relate_element";
break;
case 2:
$c = new clsNews();
$t = "innews/news_relate_element";
break;
case 3:
$c = new clsTopic();
$t="inbulletin/bb_relate_element";
break;
case 4:
$c = new clsLink();
$t="inlink/link_relate_element";
break;
case 5:
$c = new clsSurvey();
$t="insurvey/s_relate_element";
break;
default:
$c=NULL;
}
if(is_object($c))
{
foreach($item as $key=>$value)
{
$c->Set($key,$value);
}
$o = $c->parse_template(parse($t));
}
return $o;
}
function &GetTargetItemClass()
{
global $objItemTypes;
$objType = $objItemTypes->GetItem($this->Get("TargetType"));
$classname = $objType->Get("ClassName");
if(strlen($classname))
{
$c = new $classname;
}
else
$c = NULL;
if(is_object($c))
{
$c->LoadFromResourceId($this->Get("TargetId"));
}
return $c;
}
function &GetSourceItemClass()
{
global $objItemTypes;
$objType = $objItemTypes->GetItem($this->Get("SourceType"));
$classname = $objType->Get("ClassName");
if(strlen($classname))
{
$c = new $classname;
}
else
$c = NULL;
if(is_object($c))
{
$c->LoadFromResourceId($this->Get("SourceId"));
}
return $c;
}
//Changes priority
function MoveUp()
{
$this->Increment("Priority");
}
function MoveDown()
{
$this->Decrement("Priority");
}
} /*clsRelationship*/
class clsRelationshipList extends clsItemCollection
{
var $Page;
var $PerPage;
function clsRelationshipList($CategoryId=-1,$ItemId=-1)
{
$this->clsItemCollection();
$this->classname="clsRelationship";
$this->SourceTable = GetTablePrefix()."Relationship";
$this->Page=1;
$this->PerPage=20;
$this->AdminSearchFields = array("ItemName","ItemType","RelationType","Status");
$this->TargetItems = new clsItemCollection();
$this->TargetItems->classname="clsItemDB";
}
function GetNumPages()
{
global $objConfig;
return ceil($this->NumItems()/$this->PerPage);
}
function GetAdminPageLinkList($link_template,$url)
{
global $objConfig, $bb_var_list_update, $var_list_update, $var_list;
$NumPages = $this->GetNumPages();
$o = "";
if($this->Page>1)
{
$prev_url = $url."?env=".BuildEnv()."&lpn=".$this->Page-1;
$o = "<A HREF=\"$prev_url\"><<</A>";
}
for($p=1;$p<=$NumPages;$p++)
{
$t = admintemplate($link_template);
if($p!=$this->Page)
{
$href = $url."?env=".BuildEnv()."&lpn=".$p;
$o = "-<A HREF=\"$href\">$p</A>-";
}
else
{
$o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
}
}
if($this->Page<$NumPages)
{
$next_url = $url."?env=".BuildEnv()."&lpn=".$this->Page+1;
}
return $o;
}
function GetLimitSQL()
{
if($this->Page<1)
$this->Page=1;
if(is_numeric($this->PerPage))
{
$Start = ($this->Page-1)*$this->PerPage;
$limit = "LIMIT ".$Start.",".$this->PerPage;
}
else
$limit = NULL;
return $limit;
}
function LoadRelated($where,$orderBy,$custom_sql = null)
{
global $objSession;
$sql = isset($custom_sql) ? sprintf($custom_sql,$this->SourceTable) : "SELECT * FROM ".$this->SourceTable;
if(strlen(trim($orderBy))>0)
{
$orderBy = "Priority, ".$orderBy;
}
else
$orderBy = "Priority ";
if(strlen($where))
$sql = sprintf('%s WHERE %s',$sql,$where);
$sql = sprintf('%s ORDER BY %s',$sql,$orderBy);
$sql .= " ".$this->GetLimitSQL();
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
return $this->Query_Item($sql);
}
function CountRelated($where)
{
$res = 0;
$sql = "SELECT count(*) as mycount from ".$this->SourceTable." WHERE $where ";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
$res = $rs->fields["mycount"];
return $res;
}
function Add($SourceId,$SourceType,$TargetId,$TargetType,
$Priority=0,$Enabled=1,$Type=0, $RelationId = -999)
{
$r = new clsRelationship();
$r->Set(array("SourceId","SourceType","TargetId","TargetType","Priority","Type","Enabled"),
array($SourceId,$SourceType,$TargetId,$TargetType,$Priority,$Type,$Enabled));
if ($RelationId != -999)
{
$r->Set("RelationshipId", $RelationId);
}
$r->tablename = $this->SourceTable;
$r->Create();
return $r;
}
function CopyToResource($OldSource,$NewSource)
{
$this->Clear();
$sql = "SELECT * FROM ".$this->SourceTable." WHERE SourceId=$OldSource";
$this->Query_Item($sql);
if($this->NumItems()>0)
{
foreach($this->Items as $i)
{
$i->UnsetIdField();
$i->Set("SourceId",$NewSource);
$i->Create();
}
}
}
function PurgeEditTable($idfield = "")
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
$sql = "DROP TABLE IF EXISTS $edit_table";
$this->adodbConnection->Execute($sql);
}
function CopyFromEditTable($ResourceId)
{
global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
$sql = "SELECT * FROM $edit_table WHERE SourceId='$ResourceId'";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
$c->Dirty();
if($data["RelationshipId"]>0)
{
$c->Update();
}
else
{
$c->UnsetIdField();
$c->Create();
}
$idlist[] = $c->Get("RelationshipId");
$rs->MoveNext();
}
if(count($idlist)>0)
{
$sql = "DELETE FROM ".GetTablePrefix()."Relationship WHERE SourceId=$ResourceId AND RelationshipId NOT IN (".implode(",",$idlist).")";
}
else
{
$sql = "DELETE FROM ".GetTablePrefix()."Relationship WHERE SourceId=$ResourceId";
}
if((int)$GLOBALS["debuglevel"])
echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
// $this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
+ unset($GLOBALS['_CopyFromEditTable']);
}
}
?>
Property changes on: trunk/kernel/include/relationship.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.3
\ No newline at end of property
Index: trunk/kernel/include/theme.php
===================================================================
--- trunk/kernel/include/theme.php (revision 700)
+++ trunk/kernel/include/theme.php (revision 701)
@@ -1,728 +1,730 @@
<?php
define('THEME_ERROR_1', 'Theme folder not writable');
define('THEME_ERROR_2', 'Template File Not Found');
class clsThemeFile extends clsItem
{
var $Contents;
var $Root;
var $Errors = Array(); // global template error messages (not db related)
function clsThemeFile($id=NULL)
{
$this->clsItem();
$this->tablename = GetTablePrefix()."ThemeFiles";
$this->id_field = "FileId";
$this->NoResourceId=1;
$this->Root = "";
$this->Contents = '';
if($id) $this->LoadFromDatabase($id);
}
function ThemeRoot()
{
if( !$this->Root )
{
$t = new clsTheme( $this->Get("ThemeId") );
$this->Root = $t->Get("Name");
}
return $this->Root;
}
function FullPath()
{
// need to rewrite (by Alex)
global $objConfig, $pathchar,$pathtoroot;
$path = $pathtoroot."themes".$pathchar.$this->ThemeRoot();
if(strlen(trim($this->Get("FilePath"))))
$path .= $pathchar.$this->Get("FilePath");
$path .= $pathchar.$this->Get("FileName");
//echo "Full Path is $path <br>\n";
return str_replace('//','/',$path);
}
function Get($name)
{
if($name == 'Contents')
return $this->Contents;
else
return parent::Get($name);
}
function Set($name, $value)
{
if( !is_array($name) )
{
$name = Array($name);
$value = Array($value);
}
$i = 0; $field_count = count($name);
while($i < $field_count)
{
if($name[$i] == 'Contents')
$this->Contents = $value[$i];
else
parent::Set($name[$i], $value[$i]);
$i++;
}
}
/*
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
$this->SetFromArray($data);
$this->Clean();
return true;
}
*/
function Delete()
{
$path = $this->FullPath();
if($this->debuglevel) echo "Trying to delete file [$path]<br>";
if( file_exists($path) ) @unlink($path);
parent::Delete();
}
function LoadFileContents($want_return = true)
{
global $objConfig,$pathchar;
$this->Contents = '';
$path = $this->FullPath();
if( file_exists($path) )
$this->Contents = file_get_contents($path);
else
$this->SetError(THEME_ERROR_2, 2); // template not found
if($want_return) return $this->Contents;
}
function SetError($msg, $code, $field = 'global_error')
{
$this->Errors[$field]['msg'] = $msg;
$this->Errors[$field]['code'] = $code;
}
function HasError()
{
return count($this->Errors) ? 1 : 0;
}
function ErrorMsg()
{
return $this->Errors['global_error']['msg'];
}
function SaveFileContents($filecontents, $new_file = false)
{
$path = $this->FullPath();
if( is_array($filecontents) ) $filecontents = implode("\n",$filecontents);
if( $this->IsWriteablePath($new_file) )
{
$fp = fopen($path,"w");
if($fp)
{
fwrite($fp,$filecontents);
fclose($fp);
return true;
}
}
return false;
}
function IsWriteablePath($new_file = false)
{
$path = $this->FullPath();
$path = str_replace('//','/',$path);
$ret = $new_file ? is_writable(dirname($path)): is_writable($path);
if(!$ret)
{
$this->SetError(THEME_ERROR_1, 1);
return false;
}
return $ret;
}
}
class clsThemeFileList extends clsItemCollection
{
var $Page;
var $PerPageVar;
var $ThemeId;
function clsThemeFileList($theme_id=NULL)
{
global $m_var_list;
$this->clsItemCollection();
$this->classname = "clsThemeFile";
$this->Page=(int)$m_var_list["p"];
$this->PerPageVar = "Perpage_ThemeFiles";
$this->SourceTable = GetTablePrefix()."ThemeFiles";
$this->AdminSearchFields = array("FileName","FilePath","Description");
$this->ThemeId=$theme_id;
//if($theme_id)
// $this->LoadFiles($theme_id);
}
function LoadFiles($id,$where="",$orderBy="",$limit="")
{
global $objConfig;
$this->Clear();
$this->ThemeId=$id;
$sql = "SELECT * FROM ".$this->SourceTable. " WHERE ThemeId=$id ";
if(strlen(trim($where))) $sql .= ' AND '.$where." ";
if(strlen(trim($orderBy))) $sql .= "ORDER BY $orderBy";
if(strlen(trim($limit))) $sql .= $limit;
if(strlen($this->PerPageVar))
{
$sql .= GetLimitSQL($this->Page,$objConfig->Get($this->PerPageVar));
}
//echo $sql;
return $this->Query_Item($sql);
}
function GetFileByName($path,$name,$LoadFromDB=TRUE)
{
$found = FALSE;
$f = FALSE;
//echo "Looking through ".$this->NumItems()." Files <br>\n";
if($this->NumItems()>0)
{
foreach($this->Items as $f)
{
if(($f->Get("FilePath")== $path) && ($f->Get("FileName")==$name))
{
$found = TRUE;
break;
}
}
}
if(!$found && $LoadFromDB)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ThemeId=".$this->ThemeId." AND FileName LIKE '$name' AND FilePath LIKE '$path'";
$rs = $this->adodbConnection->Execute($sql);
//echo $sql."<br>\n";
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$f =& $this->AddItemFromArray($data);
}
else
$f = FALSE;
}
return $f;
}
function AddFile($Path,$Name,$ThemeId,$Type,$Description,$contents=NULL)
{
$f = new clsThemeFile();
$f->Set(array("FilePath","FileName","ThemeId","FileType","Description"),
array($Path,$Name,$ThemeId,$Type,$Description));
$f->Create();
if($contents!=NULL)
$f->SaveFileContents($contents);
//echo $f->Get("FilePath")."/".$f->Get("FileName")."<br>\n";
return $f;
}
function EditFile($FileId,$Path,$Name,$ThemeId,$Type,$Description,$contents=NULL)
{
$f = $this->GetItem($FileId);
$f->Set(array("FilePath","FileName","ThemeId","FileType","Description"),
array($Path,$Name,$ThemeId,$Type,$Description));
$f->Update();
if($Contents!=NULL)
$f->SaveFileContents($Contents);
return $f;
}
function DeleteFile($FileId)
{
$f = $this->GetItem($FileId);
$f->Delete();
}
function DeleteAll()
{
$this->Clear();
$this->LoadFiles($this->ThemeId);
foreach($this->Items as $f)
$f->Delete();
$this->Clear();
}
function SetFileContents($FileId,$Contents)
{
$f = $this->GetItem($FileId);
$f->SaveFileContents($Contents);
}
function GetFileContents($FileId)
{
$f = $this->GetItem($FileId);
return $f->LoadFileContents();
}
function FindMissingFiles($path, $where = null, $OrderBy = null, $limit = null)
{
global $pathtoroot;
$this->Clear();
$fullpath = $pathtoroot.'themes/'.$path;
// get all templates from database
$sql = 'SELECT FileId AS i,CONCAT(FilePath,"/",FileName) AS f FROM '.$this->SourceTable. ' WHERE ThemeId='.$this->ThemeId;
$DBfiles=Array();
if($rs = $this->adodbConnection->Execute($sql))
{
while(!$rs->EOF)
{
$DBfiles[$rs->fields['i']] = $fullpath.$rs->fields['f'];
$rs->MoveNext();
}
$rs->Free();
}
// get all templates file from disk
$HDDfiles = filelist($fullpath, NULL, "tpl");
$missingFiles=array_diff($HDDfiles,$DBfiles);
$orphanFiles=array_diff($DBfiles,$HDDfiles);
$sql = 'DELETE FROM '.$this->SourceTable.' WHERE FileId IN('.join(',',array_keys($orphanFiles)).')';
$this->adodbConnection->Execute($sql);
$l=strlen($fullpath);
foreach($missingFiles as $file)
$this->AddFile(substr(dirname($file),$l),basename($file),$this->ThemeId,0,'');
}
}
RegisterPrefix("clsTheme","theme","kernel/include/theme.php");
class clsTheme extends clsParsedItem
{
var $Files;
var $FileCache;
var $IdCache;
var $ParseCacheDate;
var $ParseCacheTimeout;
function clsTheme($Id = NULL)
{
$this->clsParsedItem($Id);
$this->tablename = GetTablePrefix()."Theme";
$this->id_field = "ThemeId";
$this->NoResourceId=1;
$this->TagPrefix="theme";
$this->Files = new clsThemeFileList($Id);
$this->FileCache = array();
$this->IdCache = array();
$this->ParseCacheDate=array();
$this->ParseCacheTimeout = array();
if($Id)
$this->LoadFromDatabase($Id);
}
function ThemeDirectory()
{
global $objConfig, $pathchar, $pathtoroot;
$path = $pathtoroot."themes/".strtolower($this->Get("Name"));
return $path;
}
function UpdateFileCacheData($id,$CacheDate)
{
$sql = "UPDATE ".GetTablePrefix()."ThemeFiles SET CacheDate=$CacheDate WHERE FileId=$id";
$this->adodbConnection->Execute($sql);
}
function LoadFileCache()
{
$sql = "SELECT * FROM ".GetTablePrefix()."ThemeFiles WHERE ThemeId=".$this->Get("ThemeId");
$rs = $this->adodbConnection->Execute($sql);
while($rs && ! $rs->EOF)
{
//$this->Files->AddItemFromArray($rs->fields,TRUE);
$f = $rs->fields["FileName"];
$t = $rs->fields["FilePath"];
if(strlen($t))
$t .= "/";
$parts = pathinfo($f);
$fname = substr($f,0,(strlen($parts["extension"])+1)*-1);
// echo "Name: $fname<br>\n";
$t .= $fname;
$this->FileCache[$t] = $rs->fields["FileId"];
$this->IdCache[$rs->fields["FileId"]] = $t;
/*
if($rs->fields["EnableCache"]) // no such field in this table (commented by Alex)
{
$this->ParseCacheDate[$rs->fields["FileId"]] = $rs->fields["CacheDate"];
$this->ParseCacheTimeout[$rs->fields["FileId"]] = $rs->fields["CacheTimeout"];
}
*/
if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 )
adodb_movenext($rs);
else
$rs->MoveNext();
}
//echo "<PRE>"; print_r($this->IdCache); echo "</PRE>";
}
function GetTemplateById($FileId)
{
if(count($this->FileCache)==0)
$this->LoadFileCache();
$f = $this->IdCache[$FileId];
return $f;
}
function GetTemplateId($t)
{
if( count($this->IdCache) == 0 ) $this->LoadFileCache();
$f = isset( $this->FileCache[$t] ) ? $this->FileCache[$t] : '';
return is_numeric($f) ? $f : $t;
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
$this->SetFromArray($data);
$this->Clean();
$this->Files = new clsThemeFileList($Id);
return true;
}
function GetFileList($where,$OrderBy)
{
global $objConfig, $pathchar;
$this->Files->PerPageVar="";
$this->Files->ThemeId = $this->Get("ThemeId");
$this->Files->LoadFiles($this->Get("ThemeId"),$where,$OrderBy);
}
function VerifyTemplates($where = null,$OrderBy = null,$limit = null)
{
if(!is_object($this->Files))
$this->Files = new clsThemeFileList($this->Get("ThemeId"));
$this->Files->ThemeId = $this->Get("ThemeId");
$this->Files->FindMissingFiles(strtolower($this->Get("Name")),$where,$OrderBy,$limit);
}
function EditTemplateContents($FileId,$Contents)
{
$this->Files->SetFileContents($FileId,$Contents);
}
function ReadTemplateContents($FileId)
{
return $this->Files->GetFileContents($FileId);
}
function CreateDirectory()
{
$dir = $this->ThemeDirectory();
if(!is_dir($dir))
mkdir($dir);
}
function Delete()
{
$this->Files->DeleteAll();
$dir = $this->ThemeDirectory();
if(is_writable($dir))
@rmdir($dir);
parent::Delete();
}
function AdminIcon()
{
global $imagesURL;
$file = $imagesURL."/itemicons/icon16_theme";
if($this->Get("PrimaryTheme")==1)
{
$file .= "_primary.gif";
}
else
{
if($this->Get("Enabled")==0)
{
$file .= "_disabled";
}
$file .= ".gif";
}
return $file;
}
function ParseObject($element)
{
global $var_list_update, $objSession;
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
switch($field)
{
case "id":
$ret = $this->Get("ThemeId");
break;
case "name": // was "nane"
$ret = $this->Get("Name");
break;
case "description":
$ret = $this->Get("Description");
break;
case "adminicon":
$ret = $this->AdminIcon();
break;
case "directory":
$ret = $this->ThemeDirectory();
break;
case "select_url":
$var_list_update["t"] = "index";
$ret = GetIndexURL()."?env=".BuildEnv()."&Action=m_set_theme&ThemeId=".$this->Get("ThemeId");
break;
case "selected":
$ret = "";
if($this->Get("Name")==$objSession->Get("Theme"))
$ret = "SELECTED";
break;
default:
$tag = $this->TagPrefix."_".$field;
$ret = ""; $this->parsetag($tag);
break;
}
}
return $ret;
}
}
class clsThemeList extends clsItemCollection
{
var $Page;
var $PerPageVar;
function clsThemeList($id=NULL)
{
$this->clsItemCollection();
$this->classname="clsTheme";
$this->SourceTable=GetTablePrefix()."Theme";
$this->PerPageVar = "Perpage_Themes";
$this->AdminSearchFields = array("Name","Description");
}
function LoadThemes($where="",$order="")
{
global $objConfig;
$this->Clear();
$sql = "SELECT * FROM ".$this->SourceTable." ";
if(strlen(trim($where)))
$sql .= "WHERE ".$where." ";
if(strlen(trim($orderBy)))
$sql .= "ORDER BY $orderBy";
$sql .= GetLimitSQL($this->Page,$objConfig->Get($this->PerPageVar));
return $this->Query_Item($sql);
}
function AddTheme($Name,$Description,$Enabled,$Primary,$CacheTimeout=3600)
{
$t = new clsTheme();
$t->tablename = $this->SourceTable;
$t->Set(array("Name","Description","Enabled","PrimaryTheme","CacheTimeout"),
array($Name,$Description,$Enabled,$Primary,$CacheTimeout));
$t->Create();
if($Primary==1)
{
$sql = "UPDATE ".$this->SourceTable." SET PrimaryTheme=0 WHERE ThemeId != ".$t->Get("ThemeId");
$this->adodbConnection->Execute($sql);
}
return $t;
}
function EditTheme($ThemeId,$Name,$Description,$Enabled,$Primary, $CacheTimeout)
{
$t = $this->GetItem($ThemeId);
$t->Set(array("Name","Description","Enabled","PrimaryTheme","CacheTimeout"),
array($Name, $Description, $Enabled, $Primary, $CacheTimeout));
$t->Dirty();
$t->Update();
if($Primary==1)
{
$sql = "UPDATE ".$this->SourceTable." SET PrimaryTheme=0 WHERE ThemeId!=$ThemeId";
$this->adodbConnection->Execute($sql);
}
return $t;
}
function DeleteTheme($ThemeId)
{
$t = $this->GetItem($ThemeId);
$t->Delete();
}
function SetPrimaryTheme($ThemeId)
{
$theme = $this->GetItem($ThemeId);
$theme->Dirty();
if($theme->Get("Enabled")==1)
{
$sql = "UPDATE ".$this->SourceTable." SET PrimaryTheme=0";
$this->adodbConnection->Execute($sql);
$theme->Set("PrimaryTheme","1");
$theme->Update();
}
}
function GetPrimaryTheme($field="ThemeId")
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE PrimaryTheme=1";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$l = $rs->fields[$field];
}
else
$l = 0;
return $l;
}
function CreateMissingThemes()
{
global $objConfig,$pathchar, $pathtoroot;
$path = $pathtoroot."themes";
$themes = array();
if ($dir = @opendir($path))
{
while (($file = readdir($dir)) !== false)
{
if($file !="." && $file !=".." && substr($file,0,1)!="_")
{
if(is_dir($path."/".$file))
{
$file = strtolower($file);
$themes[$file]=0;
}
}
}
}
closedir($dir);
$this->Clear();
$this->Query_Item("SELECT * FROM ".$this->SourceTable);
foreach($this->Items as $i)
{
$n = strtolower($i->Get("Name"));
$themes[$n] = $i->Get("ThemeId");
}
$names = array_keys($themes);
for($i=0;$i<count($names);$i++)
{
$name = $names[$i];
$value = $themes[$name];
if($value==0)
{
$t = $this->AddTheme($name,"New Theme",0,0);
$themes[$name] = $t->Get("ThemeId");
}
}
$where = implode(",",array_values($themes));
$sql = "DELETE FROM ".$this->SourceTable." WHERE ThemeId NOT IN ($where)";
}
function CopyFromEditTable()
{
global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
$sql = "SELECT * FROM $edit_table";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
$c->Dirty();
if($data["ThemeId"]>0)
{
$c->Update();
}
else
{
$c->UnsetIdField();
$c->Create();
$c->CreateDirectory();
}
if($c->Get("PrimaryTheme"))
{
$this->SetPrimaryTheme($c->Get("ThemeId"));
}
$rs->MoveNext();
}
$this->adodbConnection->Execute($sql);
+ unset($GLOBALS['_CopyFromEditTable']);
}
function PurgeEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
}
?>
Property changes on: trunk/kernel/include/theme.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.7
\ No newline at end of property
+1.8
\ No newline at end of property
Index: trunk/kernel/include/itemdb.php
===================================================================
--- trunk/kernel/include/itemdb.php (revision 700)
+++ trunk/kernel/include/itemdb.php (revision 701)
@@ -1,557 +1,569 @@
<?php
define('FT_OPTION', 1); // option formatter
class clsItemDB
{
var $Formatters = Array(); // by Alex
var $m_dirtyFieldsMap = array();
var $Data = array();
var $adodbConnection;
var $tablename;
var $BasePermission;
var $id_field;
var $NoResourceId;
var $debuglevel;
var $SelectSQL = 'SELECT * FROM %s WHERE %s';
function clsItemDB()
{
$this->adodbConnection = &GetADODBConnection();
$this->tablename="";
$this->NoResourceId=0;
$this->debuglevel=0;
}
// ============================================================================================
function GetFormatter($field)
{
return $this->HasFormatter($field) ? $this->Formatters[$field] : false;
}
function SetFormatter($field, $type, $params)
{
// by Alex
// all params after 2nd are formmater type specific
$this->Formatters[$field]['type'] = $type;
switch($type)
{
case FT_OPTION:
$this->Formatters[$field]['options'] = $params;
break;
}
}
/*
function FormatFields()
{
// format item in list data before printing
foreach($this->Formatters as $field => $formatter)
$this->Data[$field] = $this->FormatField($field);
}
*/
function FormatField($field)
{
// formats single field if it has formatter
if( $this->HasFormatter($field) )
{
$fmt = $this->Formatters[$field];
switch($fmt['type'])
{
case FT_OPTION:
return $fmt['options'][ $this->Data[$field] ];
break;
}
}
else
return $this->Get($field);
}
function HasFormatter($field)
{
// checks if formatter is set for field
return isset($this->Formatters[$field]) ? 1 : 0;
}
// ============================================================================================
function UnsetIdField()
{
$f = $this->IdField();
unset($this->Data[$f]);
unset($this->m_dirtyFieldsMap[$f]);
}
function UnsetField($field)
{
unset($this->Data[$field]);
unset($this->m_dirtyFieldsMap[$field]);
}
function IdField()
{
if(!strlen($this->id_field))
{
return $this->tablename."Id";
}
else
return $this->id_field;
}
function UniqueId()
{
return $this->Get($this->IdField());
}
function SetUniqueId($value)
{
$var = $this->IdField();
$this->Set($var, $value);
}
function SetModified($UserId=NULL)
{
global $objSession;
$keys = array_keys($this->Data);
if(in_array("Modified",$keys))
{
$this->Set("Modified",adodb_date("U"));
}
if(in_array("ModifiedById",$keys))
{
if(!$UserId)
$UserId = $objSession->Get("PortalUserId");
$this->Set("ModifiedById",$UserId);
}
}
function PrintVars()
{
echo '<pre>'.print_r($this->Data, true).'</pre>';
}
// =================================================================
function GetFormatted($name)
{
// get formatted field value
return $this->FormatField($name);
}
function Get($name)
{
// get un-formatted field value
//if( !isset($this->Data[$name]) ) print_pre( debug_backtrace() );
return $this->HasField($name) ? $this->Data[$name] : '';
}
// =================================================================
function HasField($name)
{
// checks if field exists in item
return isset($this->Data[$name]) ? 1 : 0;
}
function Set($name, $value)
{
//echo "Setting Field <b>$name</b>: = [$value]<br>";
if( is_array($name) )
{
for ($i=0; $i < sizeof($name); $i++)
{
$var = "m_" . $name[$i];
if( !$this->HasField($name[$i]) || ($this->Data[$name[$i]] != $value[$i]))
{
$this->Data[$name[$i]] = $value[$i];
$this->m_dirtyFieldsMap[$name[$i]] = $value[$i];
}
}
}
else
{
$var = "m_" . $name;
if( !$this->HasField($name) || $this->Data[$name] != $value )
{
$this->Data[$name] = $value;
$this->m_dirtyFieldsMap[$name] = $value;
}
}
}
function Dirty($list=NULL)
{
if($list==NULL)
{
foreach($this->Data as $field => $value)
{
$this->m_dirtyFieldsMap[$field] = $value;
}
}
else
{
foreach($list as $field)
{
$this->m_dirtyFieldsMap[$field] = $this->Data[$field];
}
}
}
function Clean($list=NULL)
{
if($list == NULL)
{
unset($this->m_dirtyFieldsMap);
$this->m_dirtyFieldsMap=array();
}
else
{
foreach($list as $value)
{
$varname = "m_" . $value;
unset($this->m_dirtyFieldsMap[$value]);
}
}
}
function SetDebugLevel($value)
{
$this->debuglevel = $value;
}
function SetFromArray($data, $dirty = false)
{
if(is_array($data))
{
$this->Data = $data;
if($dirty) $this->m_dirtyFieldsMap = $data;
}
}
function GetData()
{
return $this->Data;
}
function SetData($data, $dirty = false)
{
$this->SetFromArray($data, $dirty);
}
function Delete()
{
global $Errors;
if($this->Get($this->IdField())==0)
{
$Errors->AddError("error.AppError",NULL,'Internal error: Delete requires set id',"",get_class($this),"Delete");
return false;
}
$sql = sprintf('DELETE FROM %s WHERE %s = %s', $this->tablename, $this->IdField(),
$this->UniqueId());
if($this->debuglevel>0)
echo $sql."<br>";
if ($this->adodbConnection->Execute($sql) === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Delete");
return false;
}
return true;
}
function Update($UpdatedBy=NULL)
{
global $Errors, $objSession;
if(count($this->m_dirtyFieldsMap) == 0)
return true;
$this->SetModified($UpdatedBy);
$sql = "UPDATE ".$this->tablename ." SET ";
$first = 1;
foreach ($this->m_dirtyFieldsMap as $key => $value)
{
if(!is_numeric($key) && $key != $this->IdField())
{
if($first)
{
- $sql = sprintf("%s %s=%s",$sql,$key,$this->adodbConnection->qstr(stripslashes($value)));
+ if(isset($GLOBALS['_CopyFromEditTable']))
+ $sql = sprintf("%s %s=%s",$sql,$key,$this->adodbConnection->qstr(($value)));
+ else
+ $sql = sprintf("%s %s=%s",$sql,$key,$this->adodbConnection->qstr(stripslashes($value)));
$first = 0;
}
else
{
- $sql = sprintf("%s, %s=%s",$sql,$key,$this->adodbConnection->qstr(stripslashes($value)));
+ if(isset($GLOBALS['_CopyFromEditTable']))
+ $sql = sprintf("%s, %s=%s",$sql,$key,$this->adodbConnection->qstr(($value)));
+ else
+ $sql = sprintf("%s, %s=%s",$sql,$key,$this->adodbConnection->qstr(stripslashes($value)));
}
}
if (!(($value == '' || $value == 0) && ($this->Data[$key] == 'NULL' || $this->Data[$key] == '0' || $this->Data[$key] == ''))) {
if (!strstr($key, 'Modif') && $key != 'CreatedOn') {
$objSession->SetVariable("HasChanges", 1);
}
}
}
$sql = sprintf("%s WHERE %s = '%s'",$sql, $this->IdField(), $this->UniqueId());
if($this->debuglevel>0)
echo $sql."<br>";
if ($this->adodbConnection->Execute($sql) === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Update");
return false;
}
/* if ($this->adodbConnection->Affected_Rows() > 0) {
$objSession->SetVariable("HasChanges", 1);
}*/
return true;
}
function ReplaceID($new_id)
{
// replace item's id, because Update method
// is too dummy to do this autommatically
// USED in temporary table editing stuff
$db =& $this->adodbConnection;
$sql = "UPDATE %1\$s SET `%2\$s` = %3\$s WHERE `%2\$s` = %4\$s";
$sql = sprintf($sql, $this->tablename, $this->IdField(), $new_id, (int)$this->UniqueId() );
if($this->debuglevel > 0) echo $sql.'<br>';
$db->Execute($sql);
}
function CreateSQL()
{
global $Errors;
$sql = "INSERT INTO ".$this->tablename." (";
$first = 1;
foreach ($this->Data as $key => $value)
{
if($first)
{
$sql = sprintf("%s %s",$sql,$key);
$first = 0;
}
else
{
$sql = sprintf("%s, %s",$sql,$key);
}
}
$sql = sprintf('%s ) VALUES (',$sql);
$first = 1;
foreach ($this->Data as $key => $value)
{
if( is_array($value) )
{
echo "Invalid Value: ";
print_pre($value);
echo "Tracing:<br>";
trace();
die();
}
if($first)
{
- $sql = sprintf("%s %s",$sql,$this->adodbConnection->qstr(stripslashes($value)));
+ if(isset($GLOBALS['_CopyFromEditTable']))
+ $sql = sprintf("%s %s",$sql,$this->adodbConnection->qstr(($value)));
+ else
+ $sql = sprintf("%s %s",$sql,$this->adodbConnection->qstr(stripslashes($value)));
$first = 0;
}
else
{
- $sql = sprintf("%s, %s",$sql,$this->adodbConnection->qstr(stripslashes($value)));
+ if(isset($GLOBALS['_CopyFromEditTable']))
+ $sql = sprintf("%s, %s",$sql,$this->adodbConnection->qstr(($value)));
+ else
+ $sql = sprintf("%s, %s",$sql,$this->adodbConnection->qstr(stripslashes($value)));
}
}
$sql = sprintf('%s)',$sql);
return $sql;
}
function Create()
{
global $Errors, $objSession;
if($this->debuglevel) echo "Creating Item: ".get_class($this)."<br>";
if($this->NoResourceId!=1 && (int)$this->Get("ResourceId")==0)
{
$this->Set("ResourceId", GetNextResourceId());
}
$sql = $this->CreateSql();
if($this->debuglevel>0)
echo $sql."<br>\n";
if ($this->adodbConnection->Execute($sql) === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Create");
return false;
}
$this->SetUniqueId($this->adodbConnection->Insert_ID());
if ($this->adodbConnection->Affected_Rows() > 0) {
$objSession->SetVariable("HasChanges", 1);
}
return true;
}
function Increment($field)
{
global $Errors;
$sql = "Update ".$this->tablename." set $field=$field+1 where ".$this->IdField()."=" . $this->UniqueId();
if($this->debuglevel>0)
echo $sql."<br>";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Increment");
return false;
}
$this->Set($field,$this->Get($field)+1);
}
function Decrement($field)
{
global $Errors;
$sql = "Update ".$this->tablename." set $field=$field-1 where ".$this->IdField()."=" . $this->UniqueId();
if($this->debuglevel>0)
echo $sql;
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Decrement");
return false;
}
$this->Set($field,$this->Get($field)-1);
}
function GetFieldList($UseLoadedData=FALSE)
{
if(count($this->Data) && $UseLoadedData==TRUE)
{
$res = array_keys($this->Data);
}
else
{
$res = $this->adodbConnection->MetaColumnNames($this->tablename);
}
return $res;
}
function UsingTempTable()
{
global $objSession;
$temp = $objSession->GetEditTable($this->tablename);
$p = GetTablePrefix()."ses";
$t = substr($temp,0,strlen($p));
$ThisTable = substr($this->tablename,0,strlen($p));
if($t==$ThisTable)
{
return TRUE;
}
else
return FALSE;
}
function LoadFromDatabase($Id, $IdField = null) // custom IdField by Alex
{
global $objSession,$Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
// --------- multiple ids allowed: begin -----------------
$id_field = isset($IdField) ? $IdField : $this->IdField();
if( !is_array($id_field) ) $id_field = Array($id_field);
if( !is_array($Id) ) $Id = Array($Id);
$i = 0; $id_count = count($id_field);
$conditions = Array();
while($i < $id_count)
{
$conditions[] = "(`".$id_field[$i]."` = '".$Id[$i]."')";
$i++;
}
$sql = sprintf($this->SelectSQL, $this->tablename, implode(' AND ', $conditions) );
// --------- multiple ids allowed: end --------------------
if($this->debuglevel) echo "Load SQL: $sql<br>";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
if($this->debuglevel) print_pre($data);
if(is_array($data))
$this->SetFromArray($data);
$this->Clean();
return TRUE;
}
function FieldExists($field)
{
$res = array_key_exists($field,$this->Data);
return $res;
}
function ValueExists($Field,$Value)
{
$sql = "SELECT $Field FROM ".$this->tablename." WHERE $Field='$Value'";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
return TRUE;
}
else
return FALSE;
}
function FieldMax($Field)
{
$sql = "SELECT Max($Field) as m FROM ".$this->tablename;
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$ret = $rs->fields["m"];
}
else
$ret = 0;
}
function FieldMin($Field)
{
$sql = "SELECT Min($Field) as m FROM ".$this->tablename;
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$ret = $rs->fields["m"];
}
else
$ret = 0;
}
function TableExists($table = null)
{
// checks if table specified in item exists in db
$db =& $this->adodbConnection;
$sql = "SHOW TABLES LIKE '%s'";
if($table == null) $table = $this->tablename;
$rs = $db->Execute( sprintf($sql, $table) );
if( $rs->RecordCount() == 1 ) // table exists in normal case
return 1;
else // check if table exists in lowercase
$rs = $db->Execute( sprintf($sql, strtolower($table) ) );
return ($rs->RecordCount() == 1) ? 1 : 0;
}
}
?>
Property changes on: trunk/kernel/include/itemdb.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.8
\ No newline at end of property
+1.9
\ No newline at end of property
Index: trunk/kernel/include/portalgroup.php
===================================================================
--- trunk/kernel/include/portalgroup.php (revision 700)
+++ trunk/kernel/include/portalgroup.php (revision 701)
@@ -1,500 +1,502 @@
<?php
class clsPortalGroup extends clsParsedItem
{
var $UserCount;
function clsPortalGroup($GroupId=NULL)
{
$this->clsParsedItem($GroupId);
$this->tablename=GetTablePrefix()."PortalGroup";
$this->type=7;
$this->BasePermission="GROUP";
$this->id_field = "GroupId";
if($GroupId)
$this->LoadFromDatabase($GroupId);
}
function Validate()
{
global $objSession, $Errors;
$dataValid = true;
if(!isset($this->m_Name) || $this->m_Name == "")
{
$Errors->AddError("error.fieldIsRequired",'Login',"","",get_class($this),"Validate");
$dataValid = false;
}
return $dataValid;
}
function HasSystemPermission($PermissionName)
{
$GroupId = $this->Get("GroupId");
$sql = "SELECT * FROM ".GetTablePrefix()."Permissions WHERE GroupId=$GroupId AND Permission='$PermissionName' AND type=1";
$result = $this->adodbConnection->Execute($sql);
if($result && !$result->EOF)
{
$this->SysPermCache[$PermissionName] = (int)$result->fields["PermissionValue"];
return (int)$result->fields["PermissionValue"];
}
else
return -1;
}
/* set $Value to -1 to delete the permission row from the DB */
function SetSystemPermission($PermName,$Value)
{
//echo "Setting $PermName to $Value<br>\n";
$oldval = $this->HasSystemPermission($PermName);
if($Value != $oldval)
{
if($Value>-1)
{
if($oldval>-1)
{
$sql = "UPDATE ".GetTablePrefix()."Permissions SET PermissionValue=$Value ";
$sql .=" WHERE Type=1 AND Permission='$PermName' AND GroupId=".$this->Get("GroupId");
//echo "UPDATE SQL: $sql<br>";
}
else
{
$sql = "INSERT INTO ".GetTablePrefix()."Permissions (Permission, GroupId, PermissionValue, Type, CatId) ";
$sql .="VALUES ('$PermName',".$this->Get("GroupId").",$Value,1,0)";
//echo "INSERT SQL: $sql<br>";
}
$this->adodbConnection->Execute($sql);
//echo $sql."<br>\n";
}
else
{
$sql = "DELETE FROM ".GetTablePrefix()."Permissions ";
$sql .=" WHERE Type=1 AND Permission='$PermName' AND GroupId=".$this->Get("GroupId");
//echo "DELETE SQL: $sql<br>";
$this->adodbConnection->Execute($sql);
}
}
}
function CheckPermission($permissionName)
{
//Check permission and if needs approval set approval
global $objSession, $Errors;
if(!$objSession->HasSystemPermission($permissionName))
{
//$Errors->AddError("error.AccessDenied","","","",get_class($this),"CheckPermission");
return false;
}
return true;
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = "SELECT * FROM ".$this->tablename." WHERE GroupId = $Id";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
$this->SetFromArray($data);
$this->Clean();
return true;
}
function AddUser($UserId,$PrimaryGroup=0)
{
// add user to group OR just updates it's status there
$db =& $this->adodbConnection;
$table = GetTablePrefix().'UserGroup';
$group_id = $this->Get('GroupId');
$sql_patterns['check'] = 'SELECT PortalUserId FROM %s WHERE GroupId = %s AND PortalUserId = %s';
$sql_patterns['reset_primary'] = 'UPDATE %s SET PrimaryGroup = 0 WHERE PortalUserId = %s';
$sql_patterns['set_primary'] = 'UPDATE %s SET PrimaryGroup = 1 WHERE GroupId = %s AND PortalUserId = %s';
$sql_patterns['add_to_group'] = 'INSERT INTO %s (PortalUserId,GroupId,PrimaryGroup) VALUES (%s, %s, %s)';
$tmp_sql = sprintf($sql_patterns['check'], $table, $group_id, $UserId);
$check_result = $db->GetOne($tmp_sql);
if(!$check_result)
{
// user is not a memeber of this group
$GroupCount = TableCount($table,"PortalUserId = $UserId", 0);
if(!$PrimaryGroup) $PrimaryGroup = ($GroupCount == 0) ? 1 : 0; // reset primary status if not already
$tmp_sql = sprintf($sql_patterns['add_to_group'], $table, $UserId, $group_id, $PrimaryGroup);
$db->Execute($tmp_sql);
}
if($PrimaryGroup)
{
$tmp_sql = sprintf($sql_patterns['reset_primary'], $table, $UserId);
$db->Execute($tmp_sql);
$tmp_sql = sprintf($sql_patterns['set_primary'], $table, $group_id, $UserId);
$db->Execute($tmp_sql);
}
}
function DeleteUser($UserId)
{
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortalUserId=$UserId AND GroupId=".$this->Get("GroupId");
$this->adodbConnection->Execute($sql);
}
function GetCustomField( $fieldName)
{
global $Errors;
if(!isset($this->m_UserId))
{
$Errors->AddError("error.AppError",NULL,"Get field is required in order to set custom field values","","clsPortalGroup","GetCustomField");
return false;
}
return GetCustomFieldValue($this->m_UserId,"portaluser",$fieldName);
}
function SetCustomField( $fieldName, $value)
{
global $Errors;
if(!isset($this->m_UserId))
{
$Errors->AddError("error.AppError",NULL,"Set field is required in order to set custom field values","","clsPortalGroup","SetCustomField");
return false;
}
return SetCustomFieldValue($this->m_UserId,"portaluser",$fieldName,$value);
}
function GetUserCount()
{
if(!is_numeric($this->UserCount))
{
$sql = "SELECT count(*) as UserCount FROM ".GetTablePrefix()."UserGroup WHERE GroupId=".$this->Get("GroupId");
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
$users = $rs->fields["UserCount"];
$this->UserCount = (int)$users;
}
return $this->UserCount;
}
function GetUserList()
{
$sql = "SELECT * FROM ".GetTablePrefix()."UserGroup WHERE GroupId=".$this->Get("GroupId");
$rs = $this->adodbConnection->Execute($sql);
$res = array();
while($rs && !$rs->EOF)
{
$res[] = $rs->fields["PortalUserId"];
$rs->MoveNext();
}
return $res;
}
function parsetag($tag)
{
global $var_list_update, $objConfig;
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "group_id":
return $this->Get("GroupId");
break;
case "group_name":
return $this->Get("Name");
break;
case "group_desc":
return $this->Get("Description");
break;
case "group_date":
return LangDate($this->Get("CreatedOn"));
break;
case "group_name":
return $this->Get("Name");
break;
case "group_enabled":
return $this->Get("Enabled");
break;
case "group_date_month":
return adodb_date("m", $this->Get("CreatedOn"));
break;
case "group_date_day":
return adodb_date("d", $this->Get("CreatedOn"));
break;
case "group_date_year":
return adodb_date("Y", $this->Get("CreatedOn"));
break;
case "group_system":
if ($this->Get("System") == 1)
return "System";
else
return "User Defined";
break;
case "group_status":
if ($this->Get("Enabled") == 1)
return "Enabled";
else
return "Disabled";
break;
default:
if (substr($tag, 0, 6) == "custom")
return Users_Custom($this->Get("ResourceId"), $tag);
else
return "Undefined:$tagname";
break;
}
}
}
class clsGroupList extends clsItemCollection
{
var $Page;
function clsGroupList()
{
$this->clsItemCollection();
$this->classname = "clsPortalGroup";
$this->SetTable('live', GetTablePrefix()."PortalGroup");
$this->AdminSearchFields = array("name");
$this->id_field = "GroupId";
}
function NumGroups()
{
return $this->NumItems();
}
function GetGroup($GroupID)
{
return $this->GetItem($GroupID);
}
function GetPersonalGroup($UserLogin)
{
$n = "_".$UserLogin;
$g = $this->GetItemByField("Name",$n);
return $g;
}
function LoadGroups($where = "",$orderBy = "")
{
global $objConfig;
$this->Clear();
if($this->Page<1)
$this->Page=1;
if(is_numeric($objConfig->Get("Perpage_Groups")))
{
$Start = ($this->Page-1)*$objConfig->Get("Perpage_Groups");
$limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Groups");
}
else
$limit = NULL;
if(strlen($where) == 0) $where = '1';
$this->QueryItemCount=TableCount($this->SourceTable, $where, 0);
//echo $this->QueryItemCount."<br>\n";
if ($orderBy!="")
{
$this->Query_PortalGroup($where,$orderBy,$limit);
}
else
{
$this->Query_PortalGroup($where,"Name DESC",$limit);
}
}
function Query_PortalGroup($whereClause=NULL,$orderByClause=NULL,$limit=null)
{
global $m_var_list,$objSession,$Errors;
$sql = "SELECT * FROM ".$this->SourceTable." ";
if(strlen($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(strlen($orderByClause))
if(strlen(trim($orderByClause)))
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
if( isset($limit) ) $sql .= ' '.$limit;
return $this->Query_Item($sql);
}
function Query_UserPortalGroup($whereClause,$orderByClause)
{
global $m_var_list,$objSession,$Errors;
if ($m_var_list["action"] == "m_group_search")
$table = $userSession->Get("SessionKey") . "_search";
else
$table = $this->SourceTable;
$sql = "SELECT * FROM $table LEFT JOIN UserGroup USING (GroupId) ";
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause))
if (strlen(trim($orderByClause)))
{
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
}
$result = $this->adodbConnection->Execute($sql);
return $this->Query_Item($sql);
}
function GetAllGroupList()
{
static $GroupListCache;
if(!is_array($GroupListCache))
{
$GroupListCache = array();
$sql = "SELECT GroupId FROM ".$this->SourceTable." WHERE Enabled=1";
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$GroupListCache[] = $rs->fields["GroupId"];
$rs->MoveNext();
}
}
return $GroupListCache;
}
function Group_Custom($ResourceId, $tag)
{
$fieldname= substr($tag, 7);
$sql = "SELECT Value FROM ".GetTablePrefix()."CustomMetaData LEFT JOIN ".GetTablePrefix()."CustomField USING (CustomFieldId) where ".GetTablePrefix()."CustomMetaData.ResourceId=$ResourceId AND ".GetTablePrefix()."CustomField.FieldName='$fieldname'";
$result = $this->adodbConnection->Execute($sql);
if ($result->EOF)
return "";
else
return $result->fields["Value"];
}
function Add_Users_To_Group($groupid)
{
global $g_usergroup_status;
$userids = explode("-", $g_usergroup_status);
$g = $this->GetItem($groupid);
foreach($userids as $userid)
$g->AddUser($userid);
}
function Delete_Group($GroupId)
{
$g = $this->GetItem($GroupId);
if(is_object($g))
{
$g->Delete();
}
}
function Edit_Group($GroupId, $Name, $Description)
{
$g = $this->GetItem($GroupId);
$g->Set(array("Name", "Description"), array($Name, $Description));
$g->Update();
return $g;
}
function &Add_Group($Name, $Description, $System=1)
{
$g = new clsPortalGroup(NULL);
$g->tablename = $this->SourceTable;
$g->Set(array("Name", "Description", "System"),array($Name, $Description,$System));
$g->Set("CreatedOn",adodb_date("U"));
$g->Create();
return $g;
}
function CopyFromEditTable($idfield)
{
global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$sql = "SELECT * FROM $edit_table";
$rs = $this->adodbConnection->Execute($sql);
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->Clean(array("OrgId"));
$c->Create();
$sql = "UPDATE ".GetTablePrefix()."UserGroup SET GroupId=".$c->Get("GroupId")." WHERE GroupId=$old_id";
$this->adodbConnection->Execute($sql);
$sql = "UPDATE ".GetTablePrefix()."Permissions SET GroupId=".$c->Get("GroupId")." WHERE GroupId=$old_id";
$this->adodbConnection->Execute($sql);
}
$c->Update();
unset($c);
unset($r);
$rs->MoveNext();
}
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
+ unset($GLOBALS['_CopyFromEditTable']);
}
function PurgeEditTable($idfield)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE GroupId<1";
$this->adodbConnection->Execute($sql);
$sql = "DELETE FROM ".GetTablePrefix()."Permissions WHERE GroupId<1";
$this->adodbConnection->Execute($sql);
}
}
/*
class clsUserGroupList extends clsItemCollection
{
function clsUserGroupList()
{
$this->clsItemCollection();
$this->classname = "clsPortalGroup";
$this->SetTable('live', GetTablePrefix()."UserGroup");
$this->id_field = "PortalUserId"; // don't try to insert by this ID :)
}
}
*/
?>
Property changes on: trunk/kernel/include/portalgroup.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.7
\ No newline at end of property
+1.8
\ No newline at end of property
Index: trunk/kernel/include/image.php
===================================================================
--- trunk/kernel/include/image.php (revision 700)
+++ trunk/kernel/include/image.php (revision 701)
@@ -1,1135 +1,1137 @@
<?php
class clsImage extends clsParsedItem
{
var $Pending;
function clsImage($id=NULL)
{
global $objSession;
$this->clsParsedItem();
$this->tablename = GetTablePrefix()."Images";
$this->Pending = FALSE;
$this->id_field = "ImageId";
$this->type=-30;
$this->TagPrefix = "image";
$this->NoResourceId=1;
if($id)
$this->LoadFromDatabase($id);
//$this->SetDebugLevel(0);
}
function GetFileName($thumb = 0)
{
global $pathtoroot;
if($thumb)
{
$p = $this->Get("ThumbPath");
}
else
{
$p = $this->Get("LocalPath");
if(!strlen($p) && $this->Get("SameImages"))
{
$p = $this->Get("ThumbPath");
}
}
if(strlen($p))
{
$parts = pathinfo($pathtoroot.$p);
$filename = $parts["basename"];
}
else
$filename = "";
return $filename;
}
function GetImageDir()
{
global $pathtoroot;
$p = $this->Get("ThumbPath");
if(strlen($p))
{
$parts = pathinfo($pathtoroot.$p);
$d = $parts["dirname"]."/";
}
if($this->Pending)
$d .= "pending/";
return $d;
}
function Delete()
{
$this->DeleteLocalImage();
parent::Delete();
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ImageId = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false || $result->EOF)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
$this->SetFromArray($data);
$this->Clean();
return true;
}
function LoadFromResource($Id,$ImageIndex)
{
global $Errors;
if(!isset($Id) || !isset($ImageIndex))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromResource");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ResourceId = '%s'AND ImageIndex = '%s'",$Id,$ImageIndex);
$result = $this->adodbConnection->Execute($sql);
if ($result === false || $result->EOF)
{
// $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromResource");
return false;
}
$data = $result->fields;
$this->SetFromArray($data);
return true;
}
function LocalImageExists()
{
global $objConfig, $pathtoroot;
$result=FALSE;
if($this->Get("LocalImage")==1 && $this->Get("SameImages")==0)
{
//$imagepath = $pathtoroot.$this->Get("LocalPath");
$imagepath = $this->GetImageDir().$this->GetFileName();
// echo "PATH: ".$this->GetImageDir()."; FILE: ".$this->GetFileName()."<BR>";
if(strlen($imagepath)>0)
{
$result = file_exists($imagepath);
}
}
return $result;
}
function LocalThumbExists()
{
$result=FALSE;
global $objConfig, $pathtoroot;
if($this->Get("LocalThumb")==1)
{
//$imagepath = $pathtoroot.$this->Get("ThumbPath");
$imagepath = $this->GetImageDir().$this->GetFileName(1);
if(strlen($imagepath)>0)
{
$result = file_exists($imagepath);
}
}
return $result;
}
function DeleteLocalImage($Thumb=TRUE,$Full=TRUE)
{
global $pathtoroot;
if($Full)
{
if($this->LocalImageExists())
{
$filename = $this->GetImageDir().$this->GetFileName();
// echo "FULL: $filename<BR>\n";
@unlink($filename);
}
}
if($Thumb)
{
if($this->LocalThumbExists())
{
$filename = $this->GetImageDir().$this->GetFileName(1);
// echo "THUMB: $filename<BR>\n";
@unlink($filename);
}
}
}
function StoreUploadedImage($file, $rewrite_name=1,$DestDir,$IsThumb=0,$IsUpload=TRUE)
{
/* move the uploaded image to its final location and update the LocalPath property */
/* returns the destination filename on success */
global $objConfig,$pathtoroot;
$Dest_Dir = $DestDir;
if($this->Pending)
$Dest_Dir .= "pending/";
if(((int)$file["error"]==0) && (substr($file["type"],0,6)=="image/"))
{
$parts = pathinfo($file["name"]);
$ext = strtolower($parts["extension"]);
if( $GLOBALS['debuglevel'] ) echo "Processing ".$file["tmp_name"]."<br>\n";
if($rewrite_name==1)
{
if($IsThumb)
$filename = "th_";
$filename .= $this->Get("ResourceId")."_".$this->Get("ImageIndex").".".$ext;
}
else
{
$filename = $file["name"];
}
$destination = $pathtoroot.$Dest_Dir.$filename;
if( $GLOBALS['debuglevel'] ) echo $file["tmp_name"]."=>".$destination."<br>\n";
if($IsUpload==TRUE)
{
$result = @move_uploaded_file($file["tmp_name"],$destination);
}
else
$result = copy($file["tmp_name"],$destination);
if($result)
{
@chmod($Dest_Dir.$filename, 0666);
return $Dest_Dir.$filename;
}
else
return "";
}
else
return "";
}
function CopyToPending()
{
global $pathtoroot;
$ThumbPath = (strlen($this->Get("ThumbPath"))>0) ? $pathtoroot.$this->Get("ThumbPath") : '';
$FullPath = strlen($this->Get("LocalPath")) ? $pathtoroot.$this->Get("LocalPath") : '';
$dest = $this->GetImageDir()."pending/";
// echo "DESTIN DIR: $dest<BR>";
// echo "THUMB PATH: $ThumbPath <BR>";
if(strlen($ThumbPath))
{
if(file_exists($ThumbPath))
{
$p = pathinfo($ThumbPath);
$d = $dest.$p["basename"];
if(file_exists($d))
unlink($d);
copy($ThumbPath,$d);
@chmod($ThumbPath.$d, 0666);
}
}
if(strlen($FullPath))
{
if(file_exists($FullPath))
{
$p = pathinfo($FullPath);
$d = $dest.$p["basename"];
if(file_exists($d))
unlink($d);
copy($FullPath,$d);
@chmod($FullPath.$d, 0666);
}
}
}
function CopyFromPending()
{
global $pathtoroot,$pathchar;
$ThumbPath = $this->Get("ThumbPath");
$FullPath = $this->Get("LocalPath");
// $src = $this->GetImageDir()."pending/";
$src = $this->GetImageDir();
if(strlen($ThumbPath))
{
if(strpos($ThumbPath,"pending/"))
{
if(file_exists($pathtoroot.$ThumbPath))
{
$path = pathinfo($pathtoroot.$ThumbPath);
$p = explode("/",$ThumbPath);
unset($p[count($p)-2]);
$d = $pathtoroot.implode("/",$p);
if(file_exists($d))
unlink($d);
copy($pathtoroot.$ThumbPath,$d);
@chmod($pathtoroot.$ThumbPath.$d, 0666);
unlink($pathtoroot.$ThumbPath);
}
}
}
if(strlen($FullPath))
{
if(file_exists($pathtoroot.$FullPath))
{
if(strpos($FullPath,"pending/"))
{
$path = pathinfo($pathtoroot.$FullPath);
$p = explode("/",$FullPath);
unset($p[count($p)-2]);
$d = $pathtoroot.implode("/",$p);
if(file_exists($d))
unlink($d);
copy($pathtoroot.$FullPath,$d);
@chmod($pathtoroot.$FullPath.$d, 0666);
unlink($pathtoroot.$FullPath);
}
}
}
}
function DeleteFromPending()
{
global $pathtoroot;
$ThumbPath = $pathtoroot.$this->Get("ThumbPath");
$FullPath = $pathtoroot.$this->Get("LocalPath");
$src = $this->GetImageDir()."pending/";
$p = pathinfo($ThumbPath);
$d = $src.$p["basename"];
if(file_exists($d))
@unlink($d);
$p = pathinfo($FullPath);
$d = $src.$p["basename"];
if(file_exists($d))
@unlink($d);
}
function RenameFiles($OldResId,$NewResId)
{
global $pathtoroot;
if($this->Pending)
{
$ThumbPath = $this->GetImageDir().$this->GetFileName(TRUE);
}
else
$ThumbPath = $pathtoroot.$this->Get("ThumbPath");
$parts = pathinfo($ThumbPath);
$ext = $parts["extension"];
$pending="";
if($this->Pending)
{
$pending="pending/";
$FullPath = $this->GetImageDir().$this->GetFileName(FALSE);
}
else
$FullPath = $pathtoroot.$this->Get("LocalPath");
$NewThumb = $pathtoroot."kernel/images/".$pending."th_$NewResId_".$this->Get("ImageIndex").".$ext";
$NewFull = $pathtoroot."kernel/images/".$pending."$NewResId_".$this->Get("ImageIndex").".$ext";
if(file_exists($ThumbPath))
{
@rename($ThumbPath,$NewThumb);
}
if(file_exists($FullPath))
{
@rename($FullPath,$NewFull);
}
}
function ReplaceImageFile($file)
{
global $objConfig;
if($file["error"]==0)
{
$this->DeleteLocalImage();
move_uploaded_file($file,$this->Get("LocalPath"));
@chmod($this->Get("LocalPath"), 0666);
}
}
function FullURL($ForceNoThumb=FALSE,$Default="kernel/images/noimage.gif")
{
global $rootURL, $objConfig,$pathtoroot;
if($this->Get("SameImages") && !$ForceNoThumb)
return $this->ThumbURL();
if(strlen($this->Get("Url")))
return $this->Get("Url");
if($this->Get("LocalImage")=="1")
{
$url = $this->Get("LocalPath");
//$url = $this->GetImageDir().$this->GetFileName();
if(file_exists($pathtoroot.$url))
{
if(strlen($url))
{
$url = $rootURL.$url;
return $url;
}
else
{
if(strlen($Default))
$url = $rootURL.$Default;
return $url;
}
}
else
{
if(strlen($Default))
{
return $rootURL.$Default;
}
else
return "";
}
}
else
{
if(strlen($Default))
{
return $rootURL.$Default;
}
else
return "";
}
}
function ThumbURL()
{
global $rootURL, $pathtoroot, $objConfig;
if(strlen($this->Get("ThumbUrl")))
return $this->Get("ThumbUrl");
if($this->Get("LocalThumb")=="1")
{
$url = $this->Get("ThumbPath");
//$url = $this->GetImageDir().$this->GetFileName();
if(file_exists($pathtoroot.$url))
{
if(strlen($url))
{
$url = $rootURL.$url;
}
else
$url = $rootURL."kernel/images/noimage.gif";
return $url;
}
else
return $rootURL."kernel/images/noimage.gif";
}
else
return $rootURL."kernel/images/noimage.gif";
}
function ParseObject($element)
{
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
switch($field)
{
case "name":
$ret = $this->Get("Name");
break;
case "alt":
$ret = $this->Get("AltName");
break;
case "full_url":
$ret = $this->FullURL();
break;
case "thumb_url":
$ret = $this->ThumbURL();
break;
}
}
else
$ret = $element->Execute();
return $ret;
}
function parsetag($tag)
{
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "image_name":
$ret = $this->Get("Name");
break;
case "image_alt":
$ret = $this->Get("AltName");
break;
case "image_url":
$ret = $this->FullURL();
break;
case "thumb_url":
$ret = $this->ThumbURL();
break;
}
return $ret;
}
//Changes priority
function MoveUp()
{
$this->Increment("Priority");
}
function MoveDown()
{
$this->Decrement("Priority");
}
function GetMaxPriority()
{
$SourceId = $this->Get("ResourceId");
$sql = "SELECT MAX(Priority) as p from ".$this->tablename."WHERE ResourceId=$SourceId";
$result = $this->adodbConnection->Execute($sql);
return $result->fields["p"];
}
function GetMinPriority()
{
$SourceId = $this->Get("ResourceId");
$sql = "SELECT MIN(Priority) as p from ".$this->tablename."WHERE ResourceId=$SourceId";
$result = $this->adodbConnection->Execute($sql);
return $result->fields["p"];
}
function UpdatePriority()
{
$SourceId = $this->Get("ResourceId");
$sql = "SELECT MAX(Priority) as p from ".$this->tablename."WHERE ReourceId=$SourceId";
$result = $this->adodbConnection->Execute($sql);
$this->Set("Priority", $result->fields["p"]+1);
}
}
class clsImageList extends clsItemCollection
{
var $Page;
var $PerPageVar;
function clsImageList()
{
$this->clsItemCollection();
$this->PerPageVar = "Perpage_Images";
$this->SourceTable = GetTablePrefix()."Images";
$this->classname = "clsImage";
}
function LoadImages($where="",$orderBy = "")
{
global $objConfig;
$this->Clear();
if($this->Page<1)
$this->Page=1;
if(is_numeric($objConfig->Get("Perpage_Images")))
{
$Start = ($this->Page-1)*$objConfig->Get("Perpage_Images");
$limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Images");
}
else
$limit = NULL;
$this->QueryItemCount=TableCount("Images",$where,0);
//echo $this->QueryItemCount."<br>\n";
if(strlen(trim($orderBy))>0)
{
$orderBy = "Priority DESC, ".$orderBy;
}
else
$orderBy = "Priority DESC";
return $this->Query_Images($where,$orderBy,$limit);
}
function Query_Images($whereClause,$orderByClause=NULL,$limit=NULL)
{
global $objSession, $Errors;
$sql = "SELECT * FROM ".$this->SourceTable;
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause) && strlen(trim($orderByClause))>0)
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
if(isset($limit) && strlen(trim($limit)))
$sql .= " ".$limit;
//echo $sql;
return $this->Query_Item($sql);
}
function &Add($Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,
$Url, $ThumbUrl, $Enabled=1, $Priority=0, $DefaultImg=0, $ImageIndex=0,
$SameImages=0, $ImageId=-999)
{
if($DefaultImg==1)
{
$sql = "UPDATE ".$this->SourceTable." SET DefaultImg=0 WHERE ResourceId=$ResourceId";
$this->adodbConnection->Execute($sql);
}
$img = new clsImage();
$img->tablename = $this->SourceTable;
$img->Set(array("Name","AltName","ResourceId","LocalImage","LocalThumb",
"Url","ThumbUrl","Enabled","Priority","DefaultImg","ImageIndex","SameImages"),
array($Name,$Alt,$ResourceId,$LocalImage,$LocalThumb,
$Url,$ThumbUrl,$Enabled,$Priority,$DefaultImg,$ImageIndex,$SameImages));
if ($ImageId != -999)
{
$img->Set("ImageId", $ImageId);
}
if((int)$ImageIndex==0)
$img->Set("ImageIndex",$this->GetNextImageIndex($ResourceId));
$img->Create();
array_push($this->Items,$img);
return $img;
}
function Edit($ImageId,$Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,
$Url, $ThumbUrl, $Enabled=1, $Priority=0, $DefaultImg=0, $ImageIndex=0,
$SameImages=0)
{
$img = $this->GetItem($ImageId);
if((int)$ImageIndex==0)
$ImageIndex = $img->Get("ImageIndex");
if(!strlen($ThumbUrl) && !$LocalThumb)
$ThumbUrl = $img->Get("ThumbUrl");
$img->Set(array("Name","AltName","ResourceId","LocalImage","LocalThumb",
"Url","ThumbUrl","Enabled","Priority","DefaultImg","ImageIndex","SameImages"),
array($Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,
$Url, $ThumbUrl, $Enabled, $Priority, $DefaultImg, $ImageIndex,$SameImages));
if((int)$ImageIndex==0)
$img->Set("ImageIndex",$this->GetNextImageIndex($ResourceId));
$img->Update();
if($DefaultImg==1)
{
$sql = "UPDATE ".$this->SourceTable." SET DefaultImg=0 WHERE ResourceId=".$ResourceId." AND ImageId !=$ImageId";
$this->adodbConnection->Execute($sql);
}
array_push($this->Items,$img);
return $img;
}
function Delete_Image($ImageId)
{
$i = $this->GetItem($ImageId);
$i->Delete();
}
function DeleteResource($ResourceId)
{
$this->Clear();
$images = $this->Query_Images("ResourceId=".$ResourceId);
if(is_array($images))
{
foreach($images as $i)
{
$i->Delete();
}
}
}
function LoadResource($ResourceId)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId";
$this->Query_Item($sql);
}
function CopyResource($SourceId,$DestId)
{
global $pathtoroot;
$this->Clear();
$this->LoadResource($SourceId);
foreach($this->Items as $i)
{
if($i->Get("LocalThumb"))
{
$f = $pathtoroot.$i->Get("ThumbPath");
if(file_exists($f))
{
$p = pathinfo($f);
$dir = $p["dirname"];
$ext = $p["extension"];
$newfile = $dir."/th_".$DestId."_".$i->Get("ImageIndex").".".$ext;
if(file_exists($newfile))
@unlink($newfile);
// echo $f." -> ".$newfile;
copy($f,$newfile);
}
}
if($i->Get("LocalImage"))
{
$f = $pathtoroot.$i->Get("LocalPath");
if(file_exists($f))
{
$p = pathinfo($f);
$dir = $p["dirname"];
$ext = $p["extension"];
$newfile = $dir."/".$DestId."_".$i->Get("ImageIndex").".".$ext;
if(file_exists($newfile))
@unlink($newfile);
// echo $f." -> ".$newfile;
copy($f,$newfile);
}
}
}
parent::CopyResource($SourceId,$DestId);
$this->Clear();
$this->LoadResource($DestId);
foreach($this->Items as $img)
{
if($img->Get("LocalThumb"))
{
$f = str_replace("th_$SourceId","th_$DestId",$img->Get("ThumbPath"));
$img->Set("ThumbPath",$f);
}
if($img->Get("LocalImage"))
{
$f = str_replace("/".$SourceId."_","/".$DestId."_",$img->Get("LocalPath"));
$img->Set("LocalPath",$f);
}
$img->Update();
}
}
function GetImageByResource($ResourceId,$Index)
{
$found=FALSE;
if($this->NumItems()>0)
{
foreach($this->Items as $i)
{
if($i->Get("ResourceID")==$ResourceId and ($i->Get("ImageIndex")==$Index))
{
$found=TRUE;
break;
}
}
}
if(!$found)
{
$i = NULL;
$i = new clsImage();
if($i->LoadFromResource($ResourceId,$Index))
{
array_push($this->Items, $i);
}
else
unset($i);
}
if(is_object($i))
{
return $i;
}
else
return FALSE;
}
function &GetDefaultImage($ResourceId)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId AND DefaultImg=1";
$rs = $this->adodbConnection->Execute($sql);
if($rs && ! $rs->EOF)
{
$data = $rs->fields;
$img= new clsImage();
$img->SetFromArray($data);
$img->Clean();
return $img;
}
else
return FALSE;
}
function HandleImageUpload($FILE,$ResourceId,$RelatedTo,$DestDir, $Name="",$AltName="",$IsThumb=0)
{
global $objConfig;
$img = $this->GetImageByResource($ResourceId,$RelatedTo);
if(is_object($img) && $RelatedTo>0)
{
$img->Set("LocalImage",1);
$img->Set("Name",$Name);
$img->Set("AltName",$AltName);
$img->Set("IsThumbnail",$IsThumb);
$dest = $img->StoreUploadedImage($FILE,1,$DestDir);
if(strlen($dest))
{
$img->Set("Url", $objConfig->Get("Site_Path").$dest);
$img->Update();
}
}
else
{
$img=$this->NewLocalImage($ResourceId,$RelatedTo,$Name,$AltName,$IsThumb,$FILE,$DestDir);
}
return $img;
}
function GetResourceImages($ResourceId)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=".$ResourceId;
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$img = new clsImage();
$img->LoadFromResource($ResourceId,$rs->fields["RelatedTo"]);
array_push($this->Images,$img);
$rs->MoveNext();
}
}
function GetResourceThumbnail($ResourceId)
{
$found=FALSE;
foreach($this->Images as $img)
{
if($img->Get("ResourceId")==$ResourceId && $img->Get("IsThumbnail")==1)
{
$found=TRUE;
break;
}
}
if($found)
{
return $img;
}
else
return FALSE;
}
function &GetImageByName($ResourceId,$name)
{
$found = FALSE;
foreach($this->Items as $img)
{
if($img->Get("ResourceId")==$ResourceId && $img->Get("Name")==$name)
{
$found=TRUE;
break;
}
}
if($found)
{
return $img;
}
else
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId AND Name LIKE '$name'";
//echo $sql;
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$img = $this->AddItemFromArray($rs->fields);
return $img;
}
else
return FALSE;
}
}
function CopyToPendingFiles()
{
$sql = "SELECT * FROM ".$this->SourceTable;
$this->Clear();
$this->Query_Item($sql);
foreach($this->Items as $i)
{
if(strlen($i->Get("LocalImage")) || strlen($i->Get("LocalThumb")))
{
$i->CopyToPending();
}
}
}
function CopyFromPendingFiles($edit_table)
{
$sql = "SELECT * FROM ".$edit_table;
$this->Clear();
$this->Query_Item($sql);
foreach($this->Items as $i)
{
## Delete original Images
$OrgImage = new clsImage($i->Get("ImageId"));
$OrgImage->DeleteLocalImage();
if($i->Get("LocalImage") || $i->Get("LocalThumb"))
{
$i->CopyFromPending();
$t = $i->Get("LocalPath");
$p = pathinfo($t);
$p_arr = explode("/", $p['dirname']);
if (eregi("pending", $p_arr[count($p_arr)-1]))
{
unset($p_arr[count($p_arr)-1]);
$p['dirname'] = implode("/", $p_arr);
$LocalPath = $p['dirname']."/".$p['basename'];
$i->Set("LocalPath", $LocalPath);
}
$t = $i->Get("ThumbPath");
$p = pathinfo($t);
$p_arr = explode("/", $p['dirname']);
if (eregi("pending", $p_arr[count($p_arr)-1]))
{
unset($p_arr[count($p_arr)-1]);
$p['dirname'] = implode("/", $p_arr);
$ThumbPath = $p['dirname']."/".$p['basename'];
$i->Set("ThumbPath", $ThumbPath);
}
$i->tablename = $edit_table;
$update = 1;
}
## Empty the fields if are not used
if (!$i->Get("LocalImage"))
{
$i->Set("LocalPath", "");
$update = 1;
}
if (!$i->Get("LocalThumb"))
{
$i->Set("ThumbPath", "");
$update = 1;
}
if ($update)
$i->Update();
}
}
function DeletePendingFiles($edit_table)
{
$sql = "SELECT * FROM ".$edit_table;
$this->Clear();
$this->Query_Item($sql);
foreach($this->Items as $i)
{
$i->DeleteFromPending();
}
}
function CopyToEditTable($idfield, $idlist)
{
global $objSession;
$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);
$this->SourceTable = $edit_table;
$this->CopyToPendingFiles();
$this->UpdateFilenamesToPendings();
}
function UpdateFilenamesToPendings()
{
global $objSession;
$edit_table = $this->SourceTable;
$sql = "SELECT * FROM ".$edit_table." WHERE (LocalPath!='' AND LocalPath IS NOT NULL) OR (ThumbPath!='' AND ThumbPath IS NOT NULL)";
$this->Clear();
$this->Query_Item($sql);
foreach($this->Items as $i)
{
$set = "";
$ImageId = $i->Get("ImageId");
## Update Local Image Path -> add "pending/" to PATH
if (strlen($i->Get("LocalPath")))
{
$p = pathinfo($i->Get("LocalPath"));
if (!eregi("/pending $", $p['dirname']))
{
$LocalPath = $p['dirname']."/pending/".$p['basename'];
$set = "SET LocalPath='$LocalPath'";
}
}
// echo "LocalImage: ".$i->Get("LocalImage").", PATH: ".$i->Get("LocalPath")."<BR>";
## Update Local Thumb Path -> add "pending/" to PATH
if (strlen($i->Get("ThumbPath")))
{
$p = pathinfo($i->Get("ThumbPath"));
if (!eregi("/pending $", $p['dirname']))
{
$LocalThumb = $p['dirname']."/pending/".$p['basename'];
if (strlen($set))
$set.= ", ThumbPath='$LocalThumb'";
else
$set = "SET ThumbPath='$LocalThumb'";
}
}
// echo "LocalThumb: ".$i->Get("LocalThumb").", PATH: ".$i->Get("ThumbPath")."<BR>";
if (strlen($set))
{
$sql = "UPDATE $edit_table $set WHERE ImageId=$ImageId";
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
$this->adodbConnection->Execute($sql);
}
}
}
function CopyFromEditTable($idfield)
{
global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$dummy =& $this->GetDummy();
if( !$dummy->TableExists($edit_table) )
{
echo 'ERROR: Table "<b>'.$edit_table.'</b>" missing (class: <b>'.get_class($this).'</b>)<br>';
//exit;
return;
}
$rs = $this->adodbConnection->Execute("SELECT * FROM $edit_table WHERE ResourceId=0");
while($rs && !$rs->EOF)
{
$id = $rs->fields["ImageId"];
if($id>0)
{
$img = $this->GetItem($id);
$img->Delete();
}
$rs->MoveNext();
}
$this->adodbConnection->Execute("DELETE FROM $edit_table WHERE ResourceId=0");
$this->CopyFromPendingFiles($edit_table);
parent::CopyFromEditTable($idfield);
+ unset($GLOBALS['_CopyFromEditTable']);
}
function PurgeEditTable($idfield)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$this->DeletePendingFiles($edit_table);
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function GetNextImageIndex($ResourceId)
{
$sql = "SELECT MAX(ImageIndex) as MaxVal FROM ".$this->SourceTable." WHERE ResourceId=".$ResourceId;
$rs = $this->adodbConnection->Execute($sql);
if($rs)
{
$val = (int)$rs->fields["MaxVal"];
$val++;
}
return $val;
}
function GetMaxPriority($ResourceId)
{
$sql = "SELECT MAX(Priority) as p from ".$this->SourceTable."WHERE ResourceId=$ResourceId";
$result = $this->adodbConnection->Execute($sql);
return $result->fields["p"];
}
function GetMinPriority($ResourceId)
{
$sql = "SELECT MIN(Priority) as p from ".$this->SourceTable."WHERE ResourceId=$ResourceId";
$result = $this->adodbConnection->Execute($sql);
return $result->fields["p"];
}
} /*clsImageList*/
?>
Property changes on: trunk/kernel/include/image.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.7
\ No newline at end of property
+1.8
\ No newline at end of property
Index: trunk/kernel/include/language.php
===================================================================
--- trunk/kernel/include/language.php (revision 700)
+++ trunk/kernel/include/language.php (revision 701)
@@ -1,748 +1,752 @@
<?php
class clsPhrase extends clsItemDB
{
function clsPhrase($id=NULL)
{
$this->clsItemDB();
$this->tablename = GetTablePrefix()."Phrase";
$this->id_field = "PhraseId";
$this->NoResourceId=1;
if($id)
$this->LoadFromDatabase($id);
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
if($Id)
{
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
$this->SetFromArray($data);
$this->Clean();
return true;
}
else
return FALSE;
}
function AdminIcon()
{
global $imagesURL;
return $imagesURL."/itemicons/icon16_language_var.gif";
}
}
class clsPhraseList extends clsItemCollection
{
var $Page;
var $PerPageVar;
function clsPhraseList()
{
$this->clsItemCollection();
$this->SourceTable = GetTablePrefix()."Phrase";
$this->classname = "clsPhrase";
$this->PerPageVar = "Perpage_Phrase";
$this->AdminSearchFields = array("p.Phrase","p.Translation");
}
function &AddPhrase($Phrase,$LangId,$Translation,$Type)
{
$tmpphrase = $this->GetPhrase($Phrase, $LangId);
if (!$tmpphrase) {
$p = new clsPhrase();
$p->tablename = $this->SourceTable;
$p->Set(array("Phrase","LanguageId","Translation","PhraseType"),
array($Phrase,$LangId,$Translation,$Type));
$p->Dirty();
$p->Create();
return $p;
}
else {
//echo 'phrase already exists with label <b>'.$Phrase.'</b><br>';
$add_error = "Error";
return $add_error;
/* $tmpphrase->Set(array("Phrase","LanguageId","Translation","PhraseType"),
array($Phrase,$LangId,$Translation,$Type));
$tmpphrase->Dirty();
$tmpphrase->Update();
return $tmpphrase;*/
}
}
function &EditPhrase($id,$Phrase,$LangId,$Translation,$Type)
{
$p = $this->GetItem($id);
$p->Set(array("Phrase","LanguageId","Translation","PhraseType"),
array($Phrase,$LangId,$Translation,$Type));
$p->Dirty();
$p->Update();
return $p;
}
function DeletePhrase($id)
{
$p = $this->GetItem($id);
$p->Delete();
}
function DeleteLanguage($LangId)
{
$sql = "DELETE FROM ".$this->SourceTable." WHERE LanguageId=$LangId";
if( $GLOBALS['debuglevel'] ) echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
}
function CopyFromEditTable()
{
global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
$edit_table = $objSession->GetEditTable($this->SourceTable);
//$idlist = array();
$sql = "SELECT * FROM $edit_table";
//echo "performing mass create/update<br>";
flush();
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
$c->Dirty();
if($data["PhraseId"]>0)
{
$c->Update();
}
else
{
$c->debuglevel=0;
$c->UnsetIdField();
$c->Create();
}
$rs->MoveNext();
}
// Phrases deleted from temporary table are marked with LanguageId = 0, when saving we need to actually delete them all
// The idea was taken from Images edit by Kostja
$sql = "DELETE FROM ".$this->SourceTable." WHERE LanguageId = 0";
$this->adodbConnection->Execute($sql);
if( $GLOBALS['debuglevel'] ) echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
+ unset($GLOBALS['_CopyFromEditTable']);
}
function PurgeEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function GetPhrase($Phrase,$Lang, $no_db=FALSE)
{
$found = FALSE;
foreach($this->Items as $i)
{
if($i->Get("Phrase")==$Phrase && $i->Get("LanguageId")==$Lang)
{
$found = TRUE;
break;
}
}
if(!$found && !$no_db)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE Phrase='$Phrase' AND LanguageId='$Lang'";
//echo $sql."<br>\n";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$i = $this->AddItemFromArray($data);
}
else
$i = FALSE;
}
return $i;
}
}
RegisterPrefix("clsLanguage","lang","kernel/include/language.php");
class clsLanguage extends clsParsedItem
{
function clsLanguage($id=NULL)
{
$this->clsParsedItem();
$this->tablename = GetTablePrefix()."Language";
$this->id_field = "LanguageId";
$this->NoResourceId=1;
$this->TagPrefix="lang";
if($id)
$this->LoadFromDatabase($id);
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
$this->SetFromArray($data);
$this->Clean();
return true;
}
function Delete()
{
$p = new clsPhraseList();
//$id = $this->Get("LanguageId");
//$p->DeleteLanguage($id);
parent::Delete();
}
function ParseObject($element)
{
global $m_var_list,$m_var_list_update, $var_list,$var_list_update, $TemplateRoot;
//echo "<PRE>"; print_r($element); echo "</PRE>";
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
switch($field)
{
case "id":
$ret = $this->Get("LanguageId");
break;
case "packname":
$ret = $this->Get("PackName");
break;
case "localname":
$ret = $this->Get("LocalName");
break;
case "link":
$t = $element->attributes["_template"];
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$m_var_list_update["lang"] = $this->Get("LanguageId");
$ret = GetIndexURL()."?env=".BuildEnv();
unset($var_list_update["t"],$m_var_list_update["lang"]);
break;
case "primary":
$ret = "";
if($this->Get("PrimaryLang")==1)
$ret = "1";
break;
case "icon":
$ret = "";
$icon = $this->Get("IconUrl");
if(strlen($icon)>0)
{
$file = $TemplateRoot."/".$icon;
//echo "File:$file <br>\n";
if(file_exists($file))
$ret = $icon;
}
if(!strlen($ret))
$ret = $element->attributes["_default"];
//echo $ret;
break;
}//switch
}//if
return $ret;
}
function AdminIcon()
{
global $imagesURL;
$file = $imagesURL."/itemicons/icon16_language";
if($this->Get("PrimaryLang")==1)
{
$file .= "_primary.gif";
}
else
{
if($this->Get("Enabled")==0)
{
$file .= "_disabled";
}
$file .= ".gif";
}
return $file;
}
}
class clsLanguageList extends clsItemCollection
{
var $m_Primary;
function clsLanguageList()
{
$this->clsItemCollection();
$this->SourceTable = GetTablePrefix()."Language";
$this->classname = "clsLanguage";
$this->AdminSearchFields = array("PackName","LocalName");
}
function SetPrimary($lang_id)
{
$sql = "UPDATE ".$this->SourceTable." SET PrimaryLang=0 ";
$this->adodbConnection->Execute($sql);
$l = $this->GetItem($lang_id);
$l->Set("PrimaryLang","1");
$l->Update();
$this->m_Primary =$lang_id;
}
function GetPrimary($Field="LanguageId")
{
if(!$this->m_Primary)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE PrimaryLang=1";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$l = $rs->fields[$Field];
}
else
$l = 0;
$this->m_Primary=$l;
}
else
$l = $this->m_Primary;
return $l;
}
function LoadAllLanguages()
{
$sql = "SELECT * FROM ".$this->SourceTable;
$this->Query_Item($sql);
}
function &AddLanguage($PackName,$LocalName,$Enabled,$Primary, $IconUrl="",$Datefmt,$TimeFmt,$Dec,$Thousand)
{
$l = new clsLanguage();
$l->tablename = $this->SourceTable;
$l->Set(array("PackName","LocalName","Enabled","PrimaryLang","IconUrl","DateFormat","TimeFormat",
"DecimalPoint","ThousandSep"),
array($PackName,$LocalName,$Enabled,$Primary,$IconUrl,$Datefmt,$TimeFmt,$Dec,$Thousand));
$l->Dirty();
$l->Create();
return $l;
}
function EditLanguage($id,$PackName,$LocalName,$Enabled,$Primary, $IconUrl="",$Datefmt,$TimeFmt,$Dec,$Thousand)
{
$l = $this->GetItem($id);
$l->Set(array("PackName","LocalName","Enabled","PrimaryLang","IconUrl","DateFormat","TimeFormat",
"DecimalPoint","ThousandSep"),
array($PackName,$LocalName,$Enabled,$Primary,$IconUrl,$Datefmt,$TimeFmt,$Dec,$Thousand));
$l->Update();
return $l;
}
function DeleteLanguage($id)
{
$l = $this->GetItem($id);
$l->Delete();
}
function CopyFromEditTable()
{
global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
$sql = "SELECT * FROM $edit_table";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
$c->Dirty();
if($data["LanguageId"]>0)
{
$c->Update();
}
else
{
$oldid = $c->Get("LanguageId");
$c->UnsetIdField();
$c->Create();
$id = $c->Get("LanguageId");
$phrase_table = $objSession->GetEditTable("Phrase");
$message_table = $objSession->GetEditTable("EmailMessage");
$sql = "UPDATE $phrase_table SET LanguageId=$id WHERE LanguageId=$oldid";
$this->adodbConnection->Execute($sql);
$sql = "UPDATE $message_table SET LanguageId=$id WHERE LanguageId=$oldid";
$this->adodbConnection->Execute($sql);
}
$rs->MoveNext();
}
+ unset($GLOBALS['_CopyFromEditTable']);
}
function ExportPhrases($file,$LangIds=NULL,$PhraseTypes=null)
{
$output = array();
$this->Clear();
$where_parts = Array();
if( isset($LangIds) ) $where_parts[] = 'LanguageId IN ('.$LangIds.')';
$where = count($where_parts) ? ' WHERE '.implode(' AND ', $where_parts) : '';
$this->Query_Item($sql = 'SELECT * FROM '.$this->SourceTable.$where);
$objXML = new xml_doc();
$RootNode =& $objXML->getTagByID($objXML->createTag("LANGUAGES"));
$ret = 0;
if($this->NumItems()>0)
{
$phrase_where = isset($PhraseTypes) ? ' AND PhraseType IN ('.$PhraseTypes.')' : '';
$event_where = isset($PhraseTypes) ? ' AND Type+1 IN ('.$PhraseTypes.')' : '';
foreach($this->Items as $l)
{
$LangRoot =& $objXML->getTagByID($RootNode->addChild($objXML,"LANGUAGE",array("PackName"=>$l->Get("PackName")),""));
$LangRoot->addChild($objXML,"DATEFORMAT",array(),$l->Get("DateFormat"));
$LangRoot->addChild($objXML,"TIMEFORMAT",array(),$l->Get("TimeFormat"));
$LangRoot->addChild($objXML,"DECIMAL",array(),$l->Get("DecimalPoint"));
$LangRoot->addChild($objXML,"THOUSANDS",array(),$l->Get("ThousandSep"));
$PhraseRoot =& $objXML->getTagByID($LangRoot->addChild($objXML,"PHRASES"));
$sql = "SELECT * FROM ".GetTablePrefix()."Phrase WHERE LanguageId=".$l->Get("LanguageId").$phrase_where;
$rs=$this->adodbConnection->Execute($sql);
while($rs && ! $rs->EOF)
{
$PhraseRoot->addChild($objXML,"PHRASE",array("Label"=>$rs->fields["Phrase"],"Type"=>$rs->fields["PhraseType"]),base64_encode($rs->fields["Translation"]));
$rs->MoveNext();
}
$EventRoot =& $objXML->getTagByID($LangRoot->addChild($objXML,"EVENTS"));
$ev = GetTablePrefix()."Events";
$em = GetTablePrefix()."EmailMessage";
$sql = "SELECT $em.*,$ev.Event,$ev.Type FROM $em INNER JOIN $ev ON ($em.EventId=$ev.EventId) WHERE LanguageId=".$l->Get("LanguageId").$event_where;
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$EventRoot->AddChild($objXML,"EVENT",array("MessageType"=>$rs->fields["MessageType"],"Event"=>$rs->fields["Event"],"Type"=>$rs->fields["Type"]),base64_encode($rs->fields["Template"]));
$rs->MoveNext();
}
}
$objXML->generate();
$objXML->xml = str_replace("&","&amp;",$objXML->xml);
$fp = @fopen($file,"w");
@fputs($fp,$objXML->xml);
@fclose($fp);
}
return file_exists($file);
}
function ReadImportTable($TableName,$SetEnabled=0,$Types="0,1",$OverwitePhrases=FALSE,
$MaxInserts=100,$Offset=0)
{
global $objPhraseList;
if(!is_object($objPhraseList))
$objPhraseList = new clsPhraseList();
$PhraseList = new clsPhraseList();
$TypeArray = explode(",",$Types);
$Inserts = 0;
$sql = "SELECT * FROM $TableName WHERE PhraseType IN ($Types) LIMIT $Offset,$MaxInserts";
//echo $sql;
//$PhraseList->EnablePaging = false;
$PhraseList->Query_Item($sql);
if($PhraseList->NumItems()>0)
{
foreach($PhraseList->Items as $i)
{
$p = $objPhraseList->GetPhrase($i->Get("Phrase"),$i->Get("LanguageId"));
//echo "<pre>"; print_r($p); echo "</pre>";
if(is_object($p))
{
if($OverwitePhrases)
{
//$p->debuglevel=1;
$p->Set("Translation",$i->Get("Translation"));
//echo $i->Get("Translation")."<br>";
$p->Set("PhraseType",$i->Get("PhraseType"));
$p->Dirty();
$p->Update();
}
}
else {
//$i->debuglevel=1;
$i->Create();
}
$Inserts++;
}
}
$Offset = $Offset + $Inserts;
return $Offset;
}
function PurgeEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
}
class clsLanguageCache
{
var $m_CachedLanguage;
var $FullLoad = FALSE;
var $cache;
var $adodbConnection;
var $TemplateName;
var $TemplateCache;
var $TemplateDate;
var $ThemeId;
function clsLanguageCache($LangId=NULL)
{
global $objConfig;
$this->m_CachedLanguage = $LangId;
$this->adodbConnection =&GetADODBConnection();
$this->Clear();
}
function Clear()
{
unset($this->cache);
$this->cache = array();
$this->TemplateCache = array();
}
function LoadLanguage($LangId,$Type)
{
$this->Clear();
$this->m_CachedLanguage = $LangId;
$this->FullLoad = TRUE;
$sql = "SELECT Phrase,Translation FROM ".GetTablePrefix()."Phrase WHERE LanguageId=$LangId AND PhraseType=$Type";
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$this->cache[$rs->fields["Phrase"]] = $rs->fields["Translation"];
if(ADODB_EXTENSION>0)
{
adodb_movenext($rs);
}
else
$rs->MoveNext();
}
return (count($this->cache)>0);
}
function GetPhrase($Phrase,$Lang)
{
$t = "";
$sql = "SELECT PhraseId,Phrase,Translation FROM ".GetTablePrefix()."Phrase WHERE Phrase='$Phrase' AND LanguageId='$Lang'";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$t = $rs->fields["Translation"];
$this->TemplateCache[] = $rs->fields["PhraseId"];
}
return $t;
}
function LoadTemplateCache($t, $timeout, $ThemeId)
{
$this->TemplateName = $t;
$this->TemplateDate = 0;
$this->ThemeId = $ThemeId;
if($timeout > 0)
{
$sql = "SELECT * FROM ".GetTablePrefix()."PhraseCache WHERE Template='$t' AND ThemeId=$ThemeId";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$this->TemplateCache = explode(',', $rs->fields['PhraseList']);
$t_length = strlen($rs->fields['PhraseList']) ? 1 : 0;
$this->TemplateDate = $rs->fields["CacheDate"];
if(date("U") < $this->TemplateDate + $timeout || !$t_length)
{
$this->TemplateCache = Array();
$this->TemplateDate=0;
}
}
else
$this->TemplateDate = -1;
}
else
$this->TemplateDate=-2;
}
function LoadCachedVars($LangId)
{
if(count($this->TemplateCache))
{
$values = implode(",",$this->TemplateCache);
$this->FullLoad = FALSE;
$this->m_CachedLanguage = $LangId;
$sql = "SELECT Phrase,Translation FROM ".GetTablePrefix()."Phrase WHERE LanguageId=$LangId AND PhraseId IN ($values)";
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$this->cache[$rs->fields["Phrase"]] = $rs->fields["Translation"];
if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 )
adodb_movenext($rs);
else
$rs->MoveNext();
}
}
}
function SaveTemplateCache()
{
if($this->TemplateDate==0 || $this->TemplateDate==-1)
{
$value = implode(",",$this->TemplateCache);
if($this->TemplateDate==0)
{
$sql = "UPDATE ".GetTablePrefix()."PhraseCache SET PhraseList='$value',CacheDate=".date("U");
$sql .=" WHERE Template='".$this->TemplateName."' AND ThemeId=".$this->ThemeId;
}
else
{
$sql = "INSERT INTO ".GetTablePrefix()."PhraseCache (Template,PhraseList,CacheDate,ThemeId) VALUES ('";
$sql .= $this->TemplateName."','$value',".date("U").",".$this->ThemeId.")";
}
$this->adodbConnection->Execute($sql);
}
}
//This function returns a translation for a particular phrase
//if translation is not found then !phrase! is returned.
function GetTranslation($phrase,$language)
{
global $objSession, $LogPhraseLookups,$LangList, $MissingList;
$missing = FALSE;
if(!$this->FullLoad)
{
$this->RefreshCacheStatus($language);
if(!isset($this->cache[$phrase]))
{
$this->cache[$phrase] = $this->GetPhrase($phrase,$language);
$translation = $this->cache[$phrase];
//$translation = "";
}
else
$translation = $this->cache[$phrase];
}
else
{
$translation = $this->cache[$phrase];
}
if(!strlen($translation))
{
$missing = TRUE;
if($language != 1)
{
$translation=$this->GetTranslation($phrase,1);
}
else
{
$translation = "!".$phrase."!";
}
}
if($LogPhraseLookups==TRUE)
{
//if(!is_array($LangList))
// $LangList = array();
//$LangList[$phrase] = $LangList;
if($missing)
{
if(!is_array($MissingList))
{
$MissingList = array();
}
if(!in_array($phrase,$MissingList))
$MissingList[] = $phrase;
}
}
return $translation;
}
//This function checks if cache is current for current language
//if not clear it out
function RefreshCacheStatus($language)
{
//First remember what language we are caching
// if(!isset($this->m_CachedLanguage))
// $this->m_CachedLanguage = $language;
//If this is the different language, then clear the cache
// if($this->m_CachedLanguage != $language)
// {
// $this->Clear();
// $this->m_CachedLanguage = $language;
// }
}
}
?>
Property changes on: trunk/kernel/include/language.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10
\ No newline at end of property
+1.11
\ No newline at end of property
Index: trunk/kernel/include/adodb/drivers/adodb-mysql.inc.php
===================================================================
--- trunk/kernel/include/adodb/drivers/adodb-mysql.inc.php (revision 700)
+++ trunk/kernel/include/adodb/drivers/adodb-mysql.inc.php (revision 701)
@@ -1,588 +1,564 @@
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim (jlim@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 8.
MySQL code that does not support transactions. Use mysqlt if you need transactions.
Requires mysql client. Works on Windows and Unix.
28 Feb 2001: MetaColumns bug fix - suggested by Freek Dijkstra (phpeverywhere@macfreek.com)
*/
if (! defined("_ADODB_MYSQL_LAYER")) {
define("_ADODB_MYSQL_LAYER", 1 );
class ADODB_mysql extends ADOConnection {
var $databaseType = 'mysql';
var $dataProvider = 'mysql';
var $hasInsertID = true;
var $hasAffectedRows = true;
var $metaTablesSQL = "SHOW TABLES";
var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasLimit = true;
var $hasMoveFirst = true;
var $hasGenID = true;
var $upperCase = 'upper';
var $isoDates = true; // accepts dates in ISO format
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
var $hasTransactions = false;
var $forceNewConnect = false;
var $poorAffectedRows = true;
var $clientFlags = 0;
var $dbxDriver = 1;
function ADODB_mysql()
{
}
function ServerInfo()
{
$arr['description'] = $this->GetOne("select version()");
$arr['version'] = ADOConnection::_findvers($arr['description']);
return $arr;
}
// if magic quotes disabled, use mysql_real_escape_string()
function qstr($s,$magic_quotes=false)
{
if (!$magic_quotes) {
if (ADODB_PHPVER >= 0x4300) {
if (is_resource($this->_connectionID))
return "'".mysql_real_escape_string($s,$this->_connectionID)."'";
}
if ($this->replaceQuote[0] == '\\'){
$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
}
return "'".str_replace("'",$this->replaceQuote,$s)."'";
}
// undo magic quotes for "
$s = str_replace('\\"','"',$s);
return "'$s'";
}
function _insertid()
{
return mysql_insert_id($this->_connectionID);
}
function _affectedrows()
{
return mysql_affected_rows($this->_connectionID);
}
// See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
// Reference on Last_Insert_ID on the recommended way to simulate sequences
var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
var $_genSeqSQL = "create table %s (id int not null)";
var $_genSeq2SQL = "insert into %s values (%s)";
var $_dropSeqSQL = "drop table %s";
function CreateSequence($seqname='adodbseq',$startID=1)
{
if (empty($this->_genSeqSQL)) return false;
$u = strtoupper($seqname);
$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
if (!$ok) return false;
return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
}
function GenID($seqname='adodbseq',$startID=1)
{
// post-nuke sets hasGenID to false
if (!$this->hasGenID) return false;
$getnext = sprintf($this->_genIDSQL,$seqname);
$rs = @$this->Execute($getnext);
if (!$rs) {
$u = strtoupper($seqname);
$this->Execute(sprintf($this->_genSeqSQL,$seqname));
$this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
$rs = $this->Execute($getnext);
}
$this->genID = mysql_insert_id($this->_connectionID);
if ($rs) $rs->Close();
return $this->genID;
}
function &MetaDatabases()
{
$qid = mysql_list_dbs($this->_connectionID);
$arr = array();
$i = 0;
$max = mysql_num_rows($qid);
while ($i < $max) {
$db = mysql_tablename($qid,$i);
if ($db != 'mysql') $arr[] = $db;
$i += 1;
}
return $arr;
}
// Format date column in sql string given an input format that understands Y M D
function SQLDate($fmt, $col=false)
{
if (!$col) $col = $this->sysTimeStamp;
$s = 'DATE_FORMAT('.$col.",'";
$concat = false;
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= '%Y';
break;
case 'Q':
case 'q':
$s .= "'),Quarter($col)";
if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
else $s .= ",('";
$concat = true;
break;
case 'M':
$s .= '%b';
break;
case 'm':
$s .= '%m';
break;
case 'D':
case 'd':
$s .= '%d';
break;
case 'H':
$s .= '%H';
break;
case 'h':
$s .= '%I';
break;
case 'i':
$s .= '%i';
break;
case 's':
$s .= '%s';
break;
case 'a':
case 'A':
$s .= '%p';
break;
default:
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
$s .= $ch;
break;
}
}
$s.="')";
if ($concat) $s = "CONCAT($s)";
return $s;
}
// returns concatenated string
// much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
function Concat()
{
$s = "";
$arr = func_get_args();
$first = true;
/*
foreach($arr as $a) {
if ($first) {
$s = $a;
$first = false;
} else $s .= ','.$a;
}*/
// suggestion by andrew005@mnogo.ru
$s = implode(',',$arr);
if (strlen($s) > 0) return "CONCAT($s)";
else return '';
}
function OffsetDate($dayFraction,$date=false)
{
if (!$date) $date = $this->sysDate;
return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";
}
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (ADODB_PHPVER >= 0x4300)
$this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword,
$this->forceNewConnect,$this->clientFlags);
else if (ADODB_PHPVER >= 0x4200)
$this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword,
$this->forceNewConnect);
else
$this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (ADODB_PHPVER >= 0x4300)
$this->_connectionID = @mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);
else
$this->_connectionID = @mysql_pconnect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($this->autoRollback) $this->RollbackTrans();
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->forceNewConnect = true;
$this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
}
function &MetaColumns($table)
{
if ($this->metaColumnsSQL) {
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if ($rs === false) return false;
$retarr = array();
while (!$rs->EOF){
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$type = $rs->fields[1];
// split type into type(length):
if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
$fld->type = $query_array[1];
$fld->max_length = $query_array[2];
} else {
$fld->max_length = -1;
$fld->type = $type;
}
$fld->not_null = ($rs->fields[2] != 'YES');
$fld->primary_key = ($rs->fields[3] == 'PRI');
$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
$fld->binary = (strpos($fld->type,'blob') !== false);
if (!$fld->binary) {
$d = $rs->fields[4];
if ($d != "" && $d != "NULL") {
$fld->has_default = true;
$fld->default_value = $d;
} else {
$fld->has_default = false;
}
}
$retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
return false;
}
// returns true or false
function SelectDB($dbName)
{
$this->databaseName = $dbName;
if ($this->_connectionID) {
return @mysql_select_db($dbName,$this->_connectionID);
}
else return false;
}
// parameters use PostgreSQL convention, not MySQL
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false,$secs=0)
{
$offsetStr =($offset>=0) ? "$offset," : '';
return ($secs) ? $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr,$arg3)
: $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr,$arg3);
}
// returns queryID or false
function _query($sql,$inputarr)
{
//global $ADODB_COUNTRECS;
//if($ADODB_COUNTRECS)
- if(defined('EDD'))
- {
- $explain='';
-// if($result=mysql_query('EXPLAIN '.$sql,$this->_connectionID))
-// {
-// $dd=Array();
-// while($d=mysql_fetch_assoc($result))$dd[]=$d;
-// mysql_free_result($result);
-// $h='';$r='';
-// foreach($dd as $i=>$d)
-// {
-// foreach($d as $th=>$td)
-// {
-// if(!$i)$h.='<th>'.$th.'</th>';
-// $r.='<td>'.$td.'</td>';
-// }
-// if(!$i)$h='<tr>'.$h.'</tr>';
-// $h.='<tr>'.$r.'</tr>';
-// $r='';
-// }
-// $explain='<br /><table cellpadding=2 cellspacing=0 border=1 bgcolor=white bordercolor=black width=100% style="border:1 solid black;border-collapse:collapse;font-family:Tahoma;font-size:9">'.$h.'</table>';
-// }
- $GLOBALS['_Q'][]=$sql.$explain;
- }
return mysql_query($sql,$this->_connectionID);
//else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6
}
/* Returns: the last error message from previous database operation */
function ErrorMsg()
{
if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error();
else $this->_errorMsg = @mysql_error($this->_connectionID);
return $this->_errorMsg;
}
/* Returns: the last error number from previous database operation */
function ErrorNo()
{
if (empty($this->_connectionID)) return @mysql_errno();
else return @mysql_errno($this->_connectionID);
}
// returns true or false
function _close()
{
@mysql_close($this->_connectionID);
$this->_connectionID = false;
}
/*
* Maximum size of C field
*/
function CharMax()
{
return 255;
}
/*
* Maximum size of X field
*/
function TextMax()
{
return 4294967295;
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordSet_mysql extends ADORecordSet{
var $databaseType = "mysql";
var $canSeek = true;
function ADORecordSet_mysql($queryID,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
switch ($mode)
{
case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;
}
$this->ADORecordSet($queryID);
}
function _initrs()
{
//GLOBAL $ADODB_COUNTRECS;
// $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;
$this->_numOfRows = @mysql_num_rows($this->_queryID);
$this->_numOfFields = @mysql_num_fields($this->_queryID);
}
function &FetchField($fieldOffset = -1)
{
if ($fieldOffset != -1) {
$o = @mysql_fetch_field($this->_queryID, $fieldOffset);
$f = @mysql_field_flags($this->_queryID,$fieldOffset);
$o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com)
//$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
$o->binary = (strpos($f,'binary')!== false);
}
else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */
$o = @mysql_fetch_field($this->_queryID);
$o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com)
//$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
}
return $o;
}
function &GetRowAssoc($upper=true)
{
if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $this->fields;
return ADORecordSet::GetRowAssoc($upper);
}
/* Use associative array to get fields array */
function Fields($colname)
{
// added @ by "Michael William Miller" <mille562@pilot.msu.edu>
if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname];
if (!$this->bind) {
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
$this->bind[strtoupper($o->name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
}
function _seek($row)
{
if ($this->_numOfRows == 0) return false;
return @mysql_data_seek($this->_queryID,$row);
}
// 10% speedup to move MoveNext to child class
function MoveNext()
{
//global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return adodb_movenext($this);
if ($this->EOF) return false;
$this->_currentRow++;
$this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
if (is_array($this->fields)) return true;
$this->EOF = true;
/* -- tested raising an error -- appears pointless
$conn = $this->connection;
if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
$fn = $conn->raiseErrorFn;
$fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
}
*/
return false;
}
function _fetch()
{
$this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
return is_array($this->fields);
}
function _close() {
@mysql_free_result($this->_queryID);
$this->_queryID = false;
}
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; // mysql max_length is not accurate
switch (strtoupper($t)) {
case 'STRING':
case 'CHAR':
case 'VARCHAR':
case 'TINYBLOB':
case 'TINYTEXT':
case 'ENUM':
case 'SET':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
case 'LONGTEXT':
case 'MEDIUMTEXT':
return 'X';
// php_mysql extension always returns 'blob' even if 'text'
// so we have to check whether binary...
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':
case 'DATE': return 'D';
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP': return 'T';
case 'INT':
case 'INTEGER':
case 'BIGINT':
case 'TINYINT':
case 'MEDIUMINT':
case 'SMALLINT':
if (!empty($fieldobj->primary_key)) return 'R';
else return 'I';
default: return 'N';
}
}
}
}
?>
\ No newline at end of file
Property changes on: trunk/kernel/include/adodb/drivers/adodb-mysql.inc.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.3
\ No newline at end of property
Index: trunk/kernel/startup.php
===================================================================
--- trunk/kernel/startup.php (revision 700)
+++ trunk/kernel/startup.php (revision 701)
@@ -1,184 +1,184 @@
<?php
//if(get_magic_quotes_gpc())
//{
// function stripSlashesA($a)
// {
// foreach($a as $k=>$v)
// $a[$k]=is_array($v)?stripSlashesA($v):stripslashes($v);
// return $a;
// }
// foreach(Array(
// 'HTTP_GET_VARS','HTTP_POST_VARS','HTTP_COOKIE_VARS','HTTP_SESSION_VARS','HTTP_SERVER_VARS','$HTTP_POST_FILES',
// '_POST','_GET','_COOKIE','_SESSION','_SERVER','_FILES','_REQUEST') as $_)
// if(isset($GLOBALS[$_]))
// $GLOBALS[$_]=stripSlashesA($GLOBALS[$_]);
//}
if(!get_magic_quotes_gpc())
{
function addSlashesA($a)
{
foreach($a as $k=>$v)
$a[$k]=is_array($v)?addSlashesA($v):addslashes($v);
return $a;
}
foreach(Array(
- 'HTTP_GET_VARS','HTTP_POST_VARS','HTTP_COOKIE_VARS','HTTP_SESSION_VARS','HTTP_SERVER_VARS','$HTTP_POST_FILES',
- '_POST','_GET','_COOKIE','_SESSION','_SERVER','_FILES','_REQUEST') as $_)
+ 'HTTP_GET_VARS','HTTP_POST_VARS','HTTP_COOKIE_VARS','HTTP_SESSION_VARS','HTTP_SERVER_VARS',
+ '_POST','_GET','_COOKIE','_SESSION','_SERVER','_REQUEST') as $_)
if(isset($GLOBALS[$_]))
$GLOBALS[$_]=addSlashesA($GLOBALS[$_]);
}
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;
}
/*
startup.php: this is the primary startup sequence for in-portal services
*/
if( file_exists($pathtoroot.'debug.php') && !defined('DEBUG_MODE') ) include_once($pathtoroot.'debug.php');
if( !defined('DEBUG_MODE') ) error_reporting(0);
ini_set('memory_limit', '16M');
ini_set('include_path', '.');
$kernel_version = "1.0.0";
$FormError = array();
$FormValues = array();
/* include PHP version compatibility functions */
require_once($pathtoroot."compat.php");
/* set global variables and module lists */
require_once($pathtoroot."globals.php");
LogEntry("Initalizing System..\n");
/* for 64 bit timestamps */
require_once($pathtoroot."kernel/include/adodb/adodb-time.inc.php");
require_once($pathtoroot."kernel/include/dates.php");
/* create the global error object */
require_once($pathtoroot."kernel/include/error.php");
$Errors = new clsErrorManager();
require_once($pathtoroot."kernel/include/itemdb.php");
require_once($pathtoroot."kernel/include/config.php");
/* create the global configuration object */
LogEntry("Creating Config Object..\n");
$objConfig = new clsConfig();
$objConfig->Load(); /* Populate our configuration data */
LogEntry("Done Loading Configuration\n");
if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 )
LogEntry("ADO Extension: ".ADODB_EXTENSION."\n");
require_once($pathtoroot."kernel/include/parseditem.php");
require_once($pathtoroot."kernel/include/item.php");
require_once($pathtoroot."kernel/include/syscache.php");
require_once($pathtoroot."kernel/include/modlist.php");
require_once($pathtoroot."kernel/include/searchconfig.php");
require_once($pathtoroot."kernel/include/banrules.php");
$objModules = new clsModList();
$objSystemCache = new clsSysCacheList();
$objSystemCache->PurgeExpired();
$objBanList = new clsBanRuleList();
require_once($pathtoroot."kernel/include/image.php");
require_once($pathtoroot."kernel/include/itemtypes.php");
$objItemTypes = new clsItemTypeList();
require_once($pathtoroot."kernel/include/theme.php");
$objThemes = new clsThemeList();
require_once($pathtoroot."kernel/include/language.php");
$objLanguages = new clsLanguageList();
$objImageList = new clsImageList();
/* Load session and user class definitions */
//require_once("include/customfield.php");
//require_once("include/custommetadata.php");
require_once($pathtoroot."kernel/include/usersession.php");
require_once($pathtoroot."kernel/include/favorites.php");
require_once($pathtoroot."kernel/include/portaluser.php");
require_once($pathtoroot."kernel/include/portalgroup.php");
/* create the user management class */
$objFavorites = new clsFavoriteList();
$objUsers = new clsUserManager();
$objGroups = new clsGroupList();
require_once($pathtoroot."kernel/include/cachecount.php");
require_once($pathtoroot."kernel/include/customfield.php");
require_once($pathtoroot."kernel/include/custommetadata.php");
require_once($pathtoroot."kernel/include/permissions.php");
require_once($pathtoroot."kernel/include/relationship.php");
require_once($pathtoroot."kernel/include/category.php");
require_once($pathtoroot."kernel/include/statitem.php");
/* category base class, used by all the modules at some point */
$objPermissions = new clsPermList();
$objPermCache = new clsPermCacheList();
$objCatList = new clsCatList();
$objCustomFieldList = new clsCustomFieldList();
$objCustomDataList = new clsCustomDataList();
$objCountCache = new clsCacheCountList();
require_once($pathtoroot."kernel/include/smtp.php");
require_once($pathtoroot."kernel/include/emailmessage.php");
require_once($pathtoroot."kernel/include/events.php");
LogEntry("Creating Mail Queue..\n");
$objMessageList = new clsEmailMessageList();
$objEmailQueue = new clsEmailQueue();
LogEntry("Done creating Mail Queue Objects\n");
require_once($pathtoroot."kernel/include/searchitems.php");
require_once($pathtoroot."kernel/include/advsearch.php");
require_once($pathtoroot."kernel/include/parse.php");
require_once($pathtoroot."kernel/include/socket.php");
/* responsible for including module code as required
This script also creates an instance of the user session onject and
handles all session management. The global session object is created
and populated, then the global user object is created and populated
each module's parser functions and action code is included here
*/
LogEntry("Startup complete\n");
include_once("include/modules.php");
if( defined('DEBUG_MODE') && constant('DEBUG_MODE') == 1 && function_exists('DebugByFile') ) DebugByFile();
/* startup is complete, so now check the mail queue to see if there's anything that needs to be sent*/
$objEmailQueue->SendMailQeue();
$ado=&GetADODBConnection();
$rs = $ado->Execute("SELECT * FROM ".GetTablePrefix()."Modules WHERE LoadOrder = 0");
$kernel_version = $rs->fields['Version'];
$adminDir = $objConfig->Get("AdminDirectory");
if ($adminDir == '') {
$adminDir = 'admin';
}
if (strstr(__FILE__, $adminDir) && !GetVar('logout') && !strstr(__FILE__, "install") && !strstr(__FILE__, "index")) {
//echo "testz [".admin_login()."]<br>";
if (!admin_login())
{
if( !headers_sent() ) setcookie("sid"," ",time()-3600);
$objSession->Logout();
$url_add = isset($_GET['expired']) && $_GET['expired'] ? '?expired=1' : '';
header("Location: ".$adminURL.'/login.php'.$url_add);
die();
//require_once($pathtoroot."admin/login.php");
}
}
?>
\ No newline at end of file
Property changes on: trunk/kernel/startup.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.17
\ No newline at end of property
+1.18
\ No newline at end of property
Index: trunk/admin/category/addcategory_custom.php
===================================================================
--- trunk/admin/category/addcategory_custom.php (revision 700)
+++ trunk/admin/category/addcategory_custom.php (revision 701)
@@ -1,264 +1,263 @@
<?php
##############################################################
##In-portal ##
##############################################################
## In-portal ##
## Intechnic Corporation ##
## All Rights Reserved, 1998-2002 ##
## ##
## No portion of this code may be copied, reproduced or ##
## otherwise redistributed without proper written ##
## consent of Intechnic Corporation. Violation will ##
## result in revocation of the license and support ##
## privileges along maximum prosecution allowed by law. ##
##############################################################
if(!strlen($pathtoroot))
{
$path=dirname(realpath(__FILE__));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if(!strlen($pathtoroot))
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
//echo $pathtoroot;
require_once($pathtoroot."kernel/startup.php");
//admin only util
$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
$admin = $objConfig->Get("AdminDirectory");
if(!strlen($admin))
$admin = "admin";
$localURL=$rootURL."kernel/";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
//$pathtolocal = $pathtoroot."in-news/";
require_once ($pathtoroot.$admin."/include/elements.php");
require_once ($pathtoroot."kernel/admin/include/navmenu.php");
//require_once ($pathtolocal."admin/include/navmenu.php");
require_once($pathtoroot.$admin."/toolbar.php");
require_once($pathtoroot.$admin."/listview/listview.php");
$m = GetModuleArray();
foreach($m as $key=>$value)
{
$path = $pathtoroot. $value."admin/include/parser.php";
if(file_exists($path))
{
include_once($path);
}
}
unset($objEditItems);
$objEditItems = new clsCatList();
$objEditItems->SourceTable = $objSession->GetEditTable("Category");
//Multiedit init
$en = (int)$_GET["en"];
$objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable);
$itemcount=$objEditItems->NumItems();
$c = $objEditItems->GetItemByIndex($en);
if($itemcount>1)
{
if ($en+1 == $itemcount)
$en_next = -1;
else
$en_next = $en+1;
if ($en == 0)
$en_prev = -1;
else
$en_prev = $en-1;
}
$action = "m_edit_category";
$envar = "env=" . BuildEnv() . "&en=$en";
$section = 'in-portal:editcategory_custom';
$title = admin_language("la_Text_Editing")." ".admin_language("la_Text_Category")." '".$c->Get("Name")."' - ".admin_language("la_tab_Custom");
$formaction = $rootURL.$admin."/category/addcategory_custom.php?".$envar;
//echo $envar."<br>\n";
//Display header
$sec = $objSections->GetSection($section);
$objCatToolBar = new clsToolBar();
$ListForm = "permlistform";
$CheckClass = "PermChecks";
$objCatToolBar->Set("CheckClass",$CheckClass);
$objCatToolBar->Set("CheckForm",$ListForm);
$saveURL = $admin."/category/category_maint.php";
$cancelURL = $admin."/".$objSession->GetVariable('ReturnScript');
$objCatToolBar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","do_edit_save('category','CatEditStatus','$saveURL',1);","tool_select.gif");
$objCatToolBar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","do_edit_save('category','CatEditStatus','".$cancelURL."',2);","tool_cancel.gif");
if ( isset($en_prev) || isset($en_next) )
{
$url = $RootUrl.$admin."/category/addcategory_custom.php";
$StatusField = "CatEditStatus";
$form = "category";
MultiEditButtons($objCatToolBar,$en_next,$en_prev,$form,$StatusField,$url,$sec->Get("OnClick"),'','la_PrevCategory','la_NextCategory');
}
int_header($objCatToolBar,NULL,$title);
if ($objSession->GetVariable("HasChanges") == 1) {
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="toolbar">
<tr>
<td valign="top">
<?php int_hint_red(admin_language("la_Warning_Save_Item")); ?>
</td>
</tr>
</table>
<?php } ?>
<form id="category" name="category" action="" method=POST>
<?php
$objCustomFields = new clsCustomFieldList(1);
$objCustomDataList->SourceTable = $objSession->GetEditTable("CustomMetaData");
$objCustomDataList->LoadResource($c->Get("ResourceId"));
for($i=0;$i<$objCustomFields->NumItems(); $i++)
{
$field =& $objCustomFields->GetItemRefByIndex($i);
$fieldid = $field->Get("CustomFieldId");
$f = $objCustomDataList->GetDataItem($fieldid);
$fieldname = "CustomData[$fieldid]";
if(is_object($f))
{
- $val_field = "<input type=\"text\" tabindex=\"".($i+1)."\" VALUE=\"".inp_htmlize($f->Get("Value"))."\" name=\"$fieldname\">";
+ $val_field = "<input type=\"text\" tabindex=\"".($i+1)."\" VALUE=\"".inp_htmlize($f->Get("Value"))."\" name=\"$fieldname\">";
$field->Set("Value", $val_field);
-
if ($field->Get('Prompt') != '') {
$field->Set("FieldLabel", admin_language($field->Get('Prompt')));
}
else {
$field->Set("FieldLabel", admin_language('lu_fieldcustom__'.strtolower($field->Get('FieldName'))));
}
$field->Set("DataId",$f->Get("CustomDataId"));
}
else
{
$val_field = "<input type=text tabindex=\"".($i+1)."\" VALUE=\"\" name=\"$fieldname\">";
$field->Set("Value", $val_field);
if ($field->Get('Prompt') != '') {
$field->Set("FieldLabel", admin_language($field->Get('Prompt')));
}
else {
$field->Set("FieldLabel", admin_language('lu_fieldcustom__'.strtolower($field->Get('FieldName'))));
}
$field->Set("DataId",0);
}
}
$objCustomFields->SortField = $objConfig->Get("CustomData_LV_Sortfield");;
$objCustomFields->SortItems($objConfig->Get("CustomData_LV_Sortorder")!="desc");
$objListView = new clsListView($objCatToolBar,$objCustomFields);
$objListView->IdField = "DataId";
$order = $objConfig->Get("CustomData_LV_Sortfield");
$SortOrder=0;
if($objConfig->Get("CustomData_LV_Sortorder")=="asc")
$SortOrder=1;
$objListView->ColumnHeaders->Add("FieldName",admin_language("la_ColHeader_FieldName"),1,0,$order,"width=\"30%\"","CustomData_LV_Sortfield","CustomData_LV_Sortorder","FieldName");
$objListView->ColumnHeaders->Add("FieldLabel",admin_language("la_ColHeader_FieldLabel"),1,0,$order,"width=\"30%\"","CustomData_LV_Sortfield","CustomData_LV_Sortorder","FieldLabel");
$objListView->ColumnHeaders->Add("Value",admin_language("la_ColHeader_Value"),1,0,$order,"width=\"40%\"","CustomData_LV_Sortfield","CustomData_LV_Sortorder","Value");
$objListView->ColumnHeaders->SetSort($objConfig->Get("CustomData_LV_Sortfield"), $objConfig->Get("CustomData_LV_Sortorder"));
$objListView->PrintToolBar = FALSE;
$objListView->checkboxes = FALSE;
$objListView->CurrentPageVar = "Page_CustomData";
$objListView->PerPageVar = "Perpage_CustomData";
//$objListView->CheckboxName = "itemlist[]";
for($i=0;$i<count($objCustomFields->Items);$i++)
{
$objListView->RowIcons[] = $imagesURL."/itemicons/icon16_custom.gif";
}
$objListView->PageLinks = $objListView->PrintPageLinks();
$objListView->SliceItems();
print $objListView->PrintList();
?>
<input type="hidden" name="ItemId" value="<?php echo $c->Get("ResourceId"); ?>">
<input type="hidden" name="Action" value="m_edit_custom_data">
<input type="hidden" name="CatEditStatus" VALUE="0">
</FORM>
<FORM id="save_edit" method="POST" NAME="save_edit" ID="save_edit">
<input type="hidden" name="CatEditStatus" VALUE="0">
</FORM>
<!-- CODE FOR VIEW MENU -->
<form ID="viewmenu" method="post" action="<?php echo $_SERVER["PHP_SELF"]."?".$envar; ?>" name="viewmenu">
<input type="hidden" name="fieldname" value="">
<input type="hidden" name="varvalue" value="">
<input type="hidden" name="varvalue2" value="">
<input type="hidden" name="Action" value="">
</form>
<?php int_footer(); ?>
Property changes on: trunk/admin/category/addcategory_custom.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.8
\ No newline at end of property
+1.9
\ No newline at end of property
Index: trunk/admin/config/importlang_progress.php
===================================================================
--- trunk/admin/config/importlang_progress.php (revision 700)
+++ trunk/admin/config/importlang_progress.php (revision 701)
@@ -1,331 +1,337 @@
<?php
##############################################################
##In-portal ##
##############################################################
## In-portal ##
## Intechnic Corporation ##
## All Rights Reserved, 1998-2002 ##
## ##
## No portion of this code may be copied, reproduced or ##
## otherwise redistributed without proper written ##
## consent of Intechnic Corporation. Violation will ##
## result in revocation of the license and support ##
## privileges along maximum prosecution allowed by law. ##
##############################################################
if(!strlen($pathtoroot))
{
$path=dirname(realpath(__FILE__));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if(!strlen($pathtoroot))
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
//echo $pathtoroot;
$FrontEnd=2;
require_once($pathtoroot."kernel/startup.php");
//admin only util
$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
$admin = $objConfig->Get("AdminDirectory");
if(!strlen($admin))
$admin = "admin";
$localURL=$rootURL."kernel/";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
// $pathtolocal = $pathtoroot."in-link/";
require_once ($pathtoroot.$admin."/include/elements.php");
require_once ($pathtoroot."kernel/admin/include/navmenu.php");
//require_once ($pathtolocal."admin/include/navmenu.php");
require_once($pathtoroot.$admin."/toolbar.php");
require_once($pathtoroot.$admin."/listview/listview.php");
include_once($pathtoroot."kernel/include/xml.php");
$section = "in-portal:lang_import";
$ado = &GetADODBConnection();
$MaxInserts = 200;
$PhraseTable = "ses_".$objSession->GetSessionKey()."_".GetTablePrefix()."ImportPhrases";
$EventTable = "ses_".$objSession->GetSessionKey()."_".GetTablePrefix()."ImportEvents";
$OverWrite = $_POST['overwrite'];
if(count($_POST)>0)
{
$Offset = 0;
$CurrentLang=0;
$file = $_FILES["lang_file"];
if(is_array($file))
{
if((int)$file["size"]>0)
{
- move_uploaded_file($file["tmp_name"],$pathtoroot.$admin."/export/".$file["name"]);
- @chmod($pathtoroot.$admin."/export/".$file["name"], 0666);
-
$filename = $pathtoroot.$admin."/export/".$file["name"];
+ move_uploaded_file($file["tmp_name"],$filename)?1:0;
+ @chmod($filename, 0666);
+
if(file_exists($filename))
{
/* parse xml file */
$fp = @fopen($filename,"r");
$xml = @fread($fp,filesize($filename));
@fclose($fp);
$objInXML = new xml_doc($xml);
$objInXML->parse();
+ $ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
+ $ado->Execute("DROP TABLE IF EXISTS $EventTable");
$sql = "CREATE TABLE $PhraseTable SELECT Phrase,Translation,PhraseType,LanguageId FROM ".GetTablePrefix()."Phrase WHERE PhraseId=-1";
$ado->Execute($sql);
$sql = "CREATE TABLE $EventTable SELECT Template,MessageType,EventId,LanguageId FROM ".GetTablePrefix()."EmailMessage WHERE EmailMessageId=-1";
$ado->Execute($sql);
//$sql = "ALTER TABLE $EventTable ADD `Type` INT(11) default 0";
//$ado->Execute($sql);
$sql = "SELECT EventId,Event,Type FROM ".GetTablePrefix()."Events";
$rs = $ado->Execute($sql);
$Events = array();
while($rs && !$rs->EOF)
{
$Events[$rs->fields["Event"]."_".$rs->fields["Type"]] = $rs->fields["EventId"];
$rs->MoveNext();
}
$objInXML->getTag(0,$name,$attribs,$contents,$tags);
if(is_array($tags))
{
foreach($tags as $t)
{
$LangRoot =& $objInXML->getTagByID($t);
$PackName = $LangRoot->attributes["PACKNAME"];
$l = $objLanguages->GetItemByField("PackName",$PackName);
if(is_object($l))
{
$LangId = $l->Get("LanguageId");
}
else
{
$l = new clsLanguage();
$l->Create();
$NewLang = TRUE;
$LangId = $l->Get("LanguageId");
}
foreach($LangRoot->children as $tag)
{
switch($tag->name)
{
case "PHRASES":
foreach($tag->children as $PhraseTag)
{
$Phrase = $ado->qstr($PhraseTag->attributes["LABEL"]);
$Translation = $ado->qstr(base64_decode($PhraseTag->contents));
$PhraseType = $PhraseTag->attributes["TYPE"];
$psql = "INSERT INTO $PhraseTable (Phrase,Translation,PhraseType,LanguageId) VALUES ($Phrase,$Translation,$PhraseType,$LangId)";
$ado->Execute($psql);
//echo "$psql <br>\n";
}
break;
case "DATEFORMAT":
$DateFormat = $tag->contents;
break;
case "TIMEFORMAT":
$TimeFormat = $tag->contents;
break;
case "DECIMAL":
$Decimal = $tag->contents;
break;
case "THOUSANDS":
$Thousands = $tag->contents;
break;
case "EVENTS":
foreach($tag->children as $EventTag)
{
$event = $EventTag->attributes["EVENT"];
$MsgType = strtolower($EventTag->attributes["MESSAGETYPE"]);
$template = base64_decode($EventTag->contents);
$Type = $EventTag->attributes["TYPE"];
$EventId = $Events[$event."_".$Type];
$esql = "INSERT INTO $EventTable (Template,MessageType,EventId,LanguageId) VALUES ('$template','$MsgType',$EventId,$LangId)";
$ado->Execute($esql);
//echo htmlentities($esql)."<br>\n";
}
break;
}
if($NewLang)
{
$l->Set("PackName",$PackName);
$l->Set("LocalName",$PackName);
$l->Set("DateFormat",$DateFormat);
$l->Set("TimeFormat",$TimeFormat);
$l->Set("DecimalPoint",$Decimal);
$l->Set("ThousandSep",$Thousands);
$l->Update();
}
}
}
$Types = implode(",",$_POST["langtypes"]);
$objSession->SetVariable("lang_types",$Types);
$objSession->SetVariable("lang_overwrite",(int)$_POST["overwrite"]);
- $Total = TableCount($PhraseTable,"PhraseType IN ($Types)",0);
+ $Total = $Types?TableCount($PhraseTable,"PhraseType IN ($Types)",0):0;
$objSession->SetVariable("phrase_total",$Total);
$Total = TableCount($EventTable,"",0);
$objSession->SetVariable("event_total",$Total);
$Offset = 0;
$Status = 0;
//unlink($filename);
}
}
}
}
}
else
{
$Offset = (int)$_GET["Offset"];
$Status = (int)$_GET["Status"];
$OverWrite = $objSession->GetVariable("lang_overwrite");
$Types = $objSession->GetVariable("lang_types");
if($Status==0)
{
$Total = $objSession->GetVariable("phrase_total");
}
else
$Total = $objSession->GetVariable("event_total");
}
//echo $Total;
if ($Total == "") {
$url = $adminURL."/config/importlang.php?env=".BuildEnv()."&importerror=1";
Header("Location: $url");
//reload($url);
}
$title = admin_language("la_Text_LangImport")." - ".admin_language("la_Step")." 2";
int_header(NULL,NULL, $title);
?>
<TABLE cellSpacing="0" cellPadding="2" width="100%" class="tableborder">
<?php
if($Status==0)
{
$Total = $objSession->GetVariable("phrase_total");
stats(prompt_language("la_lang_import_progress"),$Offset,$Total);
$Offset = $objLanguages->ReadImportTable($PhraseTable,1,$Types,$OverWrite,$MaxInserts,$Offset);
if($Offset<$Total)
{
$url = $_SERVER["PHP_SELF"]."?env=".BuildEnv()."&Offset=$Offset&Status=0";
}
else
{
if($objSession->GetVariable("event_total")>0)
{
$url = $_SERVER["PHP_SELF"]."?env=".BuildEnv()."&Offset=0&Status=1";
}
else
+ {
+ $ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
+ $ado->Execute("DROP TABLE IF EXISTS $EventTable");
$url = $adminURL."/config/config_lang.php?env=".BuildEnv();
+ }
}
reload($url);
}
else
{
$Total = $objSession->GetVariable("event_total");
$Offset = $objMessageList->ReadImportTable($EventTable,$OverWrite,$MaxInserts,$Offset);
if($Offset<$Total)
{
$url = $_SERVER["PHP_SELF"]."?env=".BuildEnv()."&Offset=$Offset&Status=1";
}
else
{
$ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
$ado->Execute("DROP TABLE IF EXISTS $EventTable");
$url = $adminURL."/config/config_lang.php?env=".BuildEnv();
}
stats(prompt_language("la_event_import_progress"),$Offset,$Total);
reload($url);
}
function stats($caption,$myprogress,$totalnum)
{
global $rootURL, $CancelURL, $PageTitle;
if($totalnum>0)
{
$pct=round(($myprogress/ $totalnum)*100);
}
else
$pct = 100;
$o .="<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\" class=\"tableborder\">";
echo "\n";
$o .= int_subsection_title_ret($caption." - ".$pct."%");
$o .= "<TR><TD align=\"middle\"><br />";
$o .= " <TABLE CLASS=\"tableborder_full\" width=\"75%\">";
$o .=" <TR border=1><TD width=\"".$pct."%\" STYLE=\"background:url('".$rootURL."admin/images/progress_bar_segment.gif');\">&nbsp;</TD>";
$comp_pct = 100-$pct;
$o .= " <TD bgcolor=#FFFFFF width=\"".$comp_pct."%\"></TD></TR>";
$o .= " </TABLE>";
$o .= " <BR /><input type=button VALUE=\"".admin_language("la_Cancel")."\" CLASS=\"button\" ONCLICK=\"document.location='".$CancelURL."config_lang.php?env=".BuildEnv()."&action=cancel';\">";
echo $o."\n";
echo "</TD></TR></TABLE>";
}
function reload($url)
{
print "<script language=\"javascript\">" ;
print "setTimeout(\"document.location='$url';\",100);";
print " </script>";
//echo "<A HREF=\"$url\">Next </A>";
}
?>
<?php int_footer(); ?>
Property changes on: trunk/admin/config/importlang_progress.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.5
\ No newline at end of property
+1.6
\ No newline at end of property

Event Timeline