Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sun, Feb 2, 8:33 AM

in-portal

Index: trunk/kernel/include/emailmessage.php
===================================================================
--- trunk/kernel/include/emailmessage.php (revision 998)
+++ trunk/kernel/include/emailmessage.php (revision 999)
@@ -1,964 +1,965 @@
<?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);
}
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 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->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->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;
+ if($NumToSend < 0) $NumToSend=1; // Don't really know why, but this could happend, so issued this temp fix
$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;
}
$sendTo=addslashes($sendTo);
$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.40
\ No newline at end of property
+1.41
\ No newline at end of property
Index: trunk/kernel/include/debugger.php
===================================================================
--- trunk/kernel/include/debugger.php (revision 998)
+++ trunk/kernel/include/debugger.php (revision 999)
@@ -1,783 +1,793 @@
<?php
if(!defined('DBG_OPTIONS')) define('DBG_OPTIONS',0);
if(!defined('DBG_USE_HIGHLIGHT')) define('DBG_USE_HIGHLIGHT',1);
if(!defined('DBG_USE_SHUTDOWN_FUNC')) define('DBG_USE_SHUTDOWN_FUNC',1);
if(!defined('DBG_HANDLE_ERRORS')) define('DBG_HANDLE_ERRORS', isset($_REQUEST['debug_host']) ? 0 : 1);
if(!defined('DBG_RAISE_ON_WARNINGS')) define('DBG_RAISE_ON_WARNINGS',0);
if(!defined('DBG_SHOW_MEMORY_USAGE')) define('DBG_SHOW_MEMORY_USAGE',1);
if(!defined('DOC_ROOT')) define('DOC_ROOT',$_SERVER['DOCUMENT_ROOT']);
if(!defined('WINDOWS_ROOT')) define('WINDOWS_ROOT','w:');
if(!defined('WINDOWS_EDITOR'))
{
$dbg_editor = 0;
$dbg_editors[0] = Array('editor' => 'c:\Program Files\UltraEdit\uedit32.exe', 'params' => '%F/%L');
$dbg_editors[1] = Array('editor' => 'c:\Program Files\Zend\ZendStudio-4.0Beta\bin\ZDE.exe', 'params' => '%F');
define('WINDOWS_EDITOR',$dbg_editors[$dbg_editor]['editor'].' '.$dbg_editors[$dbg_editor]['params']);
unset($dbg_editors,$dbg_editor);
}
class Debugger
{
/**
* Debugger data for building report
*
* @var Array
*/
var $Data = Array();
var $ProfilerData = Array();
var $RecursionStack = Array(); // prevent recursion when processing debug_backtrace() function results
var $TraceNextError=false;
var $Options = 0;
var $OptionsMap = Array('shutdown_func' => 1, 'error_handler' => 2,
'output_buffer' => 4, 'highlight_output' => 8);
var $longErrors=Array();
/**
* Amount of memory used by debugger itself
*
* @var Array
* @access private
*/
var $memoryUsage=Array();
function Debugger()
{
$this->memoryUsage['error_handling']=0; // memory amount used by error handler
$this->appendRequest();
}
function initOptions()
{
}
function mapLongError($msg)
{
$key=$this->generateID();
$this->longErrors[$key]=$msg;
return $key;
}
function setOption($name,$value)
{
if( !isset($this->OptionsMap[$name]) ) die('undefined debugger option: ['.$name.']<br>');
if($value)
{
$this->Options|=$this->OptionsMap[$name];
}
else
{
$this->Options=$this->Options&~$this->OptionsMap[$name];
}
}
function getOption($name)
{
if( !isset($this->OptionsMap[$name]) ) die('undefined debugger option: ['.$name.']<br>');
return ($this->Options & $this->OptionsMap[$name]) == $this->OptionsMap[$name];
}
/**
* Set's flag, that next error that occurs will
* be prepended by backtrace results
*
*/
function traceNext()
{
$this->TraceNextError=true;
}
function dumpVars()
{
$dumpVars = func_get_args();
foreach($dumpVars as $varValue)
{
$this->Data[] = Array('value' => $varValue, 'debug_type' => 'var_dump');
}
}
function prepareHTML($dataIndex)
{
$Data =& $this->Data[$dataIndex];
if($Data['debug_type'] == 'html') return $Data['html'];
switch($Data['debug_type'])
{
case 'error':
$fileLink = $this->getFileLink($Data['file'],$Data['line']);
$ret = '<b class="debug_error">'.$this->getErrorNameByCode($Data['no']).'</b>: '.$Data['str'];
$ret .= ' in <b>'.$fileLink.'</b> on line <b>'.$Data['line'].'</b>';
return $ret;
break;
case 'var_dump':
$ret = $this->highlightString( print_r($Data['value'], true) );
return addslashes($ret);
break;
case 'trace':
ini_set('memory_limit','500M');
$trace =& $Data['trace'];
//return 'sorry';
//return $this->highlightString(print_r($trace,true));
$i = 0; $traceCount = count($trace);
$ret = '';
while($i < $traceCount)
{
$traceRec =& $trace[$i];
$argsID = 'trace_args_'.$dataIndex.'_'.$i;
if(isset($traceRec['file']))
{
$func_name=isset($traceRec['class'])?$traceRec['class'].$traceRec['type'].$traceRec['function']:$traceRec['function'];
$ret .= '<a href="javascript:toggleTraceArgs(\''.$argsID.'\');" title="Show/Hide Function Arguments"><b>Function</b></a>: '.$this->getFileLink($traceRec['file'],$traceRec['line'],$func_name);
$ret .= ' in <b>'.basename($traceRec['file']).'</b> on line <b>'.$traceRec['line'].'</b><br>';
}
else
{
$ret .= 'no file information available';
}
// ensure parameter value is not longer then 200 symbols
$this->processTraceArguments($traceRec['args']);
$args = $this->highlightString(print_r($traceRec['args'], true));
$ret .= '<div id="'.$argsID.'" style="display: none;">'.$args.'</div>';
$i++;
}
return $ret;
break;
case 'profiler':
$profileKey = $Data['profile_key'];
$Data =& $this->ProfilerData[$profileKey];
$runtime = ($Data['ends'] - $Data['begins']); // in seconds
return '<b>Name</b>: '.$Data['description'].'<br><b>Runtime</b>: '.$runtime.'s';
break;
default:
return 'incorrect debug data';
break;
}
}
function processTraceArguments(&$traceArgs)
{
if(!$traceArgs) return '';
foreach ($traceArgs as $argID => $argValue)
{
if( is_array($argValue) || is_object($argValue) )
{
if(is_object($argValue) && !in_array(get_class($argValue),$this->RecursionStack) )
{
// object & not in stack - ok
array_push($this->RecursionStack, get_class($argValue));
settype($argValue,'array');
$this->processTraceArguments($argValue);
array_pop($this->RecursionStack);
}
elseif(is_object($argValue) && in_array(get_class($argValue),$this->RecursionStack) )
{
// object & in stack - recursion
$traceArgs[$argID] = '**** RECURSION ***';
}
else
{
// normal array here
$this->processTraceArguments($argValue);
}
}
else
{
$traceArgs[$argID] = $this->cutStringForHTML($traceArgs[$argID]);
}
}
}
function cutStringForHTML($string)
{
if( strlen($string) > 200 ) $string = substr($string,0,50).' ...';
return $string;
}
/**
* Format SQL Query using predefined formatting
* and highlighting techniques
*
* @param string $sql
* @return string
*/
function formatSQL($sql)
{
$sql = preg_replace('/(\n|\t| )+/is',' ',$sql);
$sql = preg_replace('/(CREATE TABLE|DROP TABLE|SELECT|UPDATE|SET|REPLACE|INSERT|DELETE|VALUES|FROM|LEFT JOIN|INNER JOIN|LIMIT|WHERE|HAVING|GROUP BY|ORDER BY) /is', "\n\t$1 ",$sql);
return $this->highlightString($sql);
}
function highlightString($string)
{
if( defined('DBG_USE_HIGHLIGHT')&&DBG_USE_HIGHLIGHT )
{
$string = highlight_string('<?php '.$string.'?>', true);
return preg_replace('/&lt;\?(.*)php (.*)\?&gt;/s','$2',$string);
}
else
{
return $string;
}
}
function getFileLink($file, $lineno = 1, $title = '')
{
if(!$title) $title = $file;
- return '<a href="javascript:editFile(\''.$this->getLocalFile($file).'\','.$lineno.');" title="'.$file.'">'.$title.'</a>';
+ $is_mozilla=strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'firefox')!==false?true:false;
+ if($is_mozilla)
+ {
+ return '<a href="file://'.$this->getLocalFile($file).'">'.$title.'</a>';
+ }
+ else
+ {
+ return '<a href="javascript:editFile(\''.$this->getLocalFile($file).'\','.$lineno.');" title="'.$file.'">'.$title.'</a>';
+ }
+
}
function getLocalFile($remoteFile)
{
return str_replace(DOC_ROOT, WINDOWS_ROOT, $remoteFile);
}
function appendTrace()
{
$trace = debug_backtrace();
array_shift($trace);
$this->Data[] = Array('trace' => $trace, 'debug_type' => 'trace');
}
function appendHTML($html)
{
$this->Data[] = Array('html' => $html,'debug_type' => 'html');
}
/**
* Change debugger info that was already generated before.
* Returns true if html was set.
*
* @param int $index
* @param string $html
* @param string $type = {'append','prepend','replace'}
* @return bool
*/
function setHTMLByIndex($index,$html,$type='append')
{
if( !isset($this->Data[$index]) || $this->Data[$index]['debug_type'] != 'html' )
{
return false;
}
switch ($type)
{
case 'append':
$this->Data[$index]['html'] .= '<br>'.$html;
break;
case 'prepend':
$this->Data[$index]['html'] = $this->Data[$index]['html'].'<br>'.$html;
break;
case 'replace':
$this->Data[$index]['html'] = $html;
break;
}
return true;
}
/**
* Move $debugLineCount lines of input from debug output
* end to beginning.
*
* @param int $debugLineCount
*/
function moveToBegin($debugLineCount)
{
$lines = array_splice($this->Data,count($this->Data)-$debugLineCount,$debugLineCount);
$this->Data = array_merge($lines,$this->Data);
}
function appendRequest()
{
$script = $_SERVER['PATH_TRANSLATED'];
$this->appendHTML('ScriptName: <b>'.$this->getFileLink($script,1,basename($script)).'</b> (<b>'.dirname($script).'</b>)');
ob_start();
?>
<table width="100%" border="0" cellspacing="0" cellpadding="4" class="flat_table">
<thead style="font-weight: bold;">
<td width="20">Src</td><td>Name</td><td>Value</td>
</thead>
<?php
foreach($_REQUEST as $key => $value)
{
if( !is_array($value) && trim($value) == '' )
{
$value = '<b class="debug_error">no value</b>';
}
else
{
$value = htmlspecialchars(print_r($value, true));
}
$src = isset($_GET[$key]) ? 'GE' : (isset($_POST[$key]) ? 'PO' : (isset($_COOKIE[$key]) ? 'CO' : '?') );
echo '<tr><td>'.$src.'</td><td>'.$key.'</td><td>'.$value.'</td></tr>';
}
?>
</table>
<?php
$this->appendHTML( ob_get_contents() );
ob_end_clean();
}
function appendSession()
{
if( isset($_SESSION)&&$_SESSION )
{
$this->appendHTML('PHP Session: [<b>'.ini_get('session.name').'</b>]');
$this->dumpVars($_SESSION);
$this->moveToBegin(2);
}
}
function profileStart($key, $description)
{
$timeStamp = $this->getMoment();
$this->ProfilerData[$key] = Array('begins' => $timeStamp, 'ends' => 5000, 'debuggerRowID' => count($this->Data), 'description' => $description);
$this->Data[] = array('profile_key' => $key, 'debug_type' => 'profiler');
}
function profileFinish($key)
{
$this->ProfilerData[$key]['ends'] = $this->getMoment();
}
function getMoment()
{
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
function generateID()
{
list($usec, $sec) = explode(" ",microtime());
$id_part_1 = substr($usec, 4, 4);
$id_part_2 = mt_rand(1,9);
$id_part_3 = substr($sec, 6, 4);
$digit_one = substr($id_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$id_part_1 = ereg_replace("^0","",$id_part_1);
$id_part_1=$digit_one.$id_part_1;
}
return $id_part_1.$id_part_2.$id_part_3;
}
function getErrorNameByCode($errorCode)
{
switch($errorCode)
{
case E_USER_ERROR:
return 'Fatal Error';
break;
case E_WARNING:
case E_USER_WARNING:
return 'Warning';
break;
case E_NOTICE:
case E_USER_NOTICE:
return 'Notice';
break;
default:
return '';
break;
}
}
/**
* Generates report
*
*/
function printReport($returnResult = false)
{
$this->memoryUsage['debugger_start']=memory_get_usage();
// show php session if any
$this->appendSession();
// ensure, that 1st line of debug output always is this one:
$this->appendHTML('<a href="javascript:toggleDebugLayer(27);">Hide Debugger</a>');
$this->moveToBegin(1);
$i = 0; $lineCount = count($this->Data);
ob_start();
?>
<style type="text/css">
.flat_table TD {
border: 1px solid buttonface;
border-width: 1 1 0 0;
}
.debug_layer_table {
border-collapse: collapse;
width: 480px;
}
.debug_text, .debug_row_even TD, .debug_row_odd TD {
color: #000000;
font-family: Verdana;
font-size: 11px;
word-wrap: break-word;
}
.debug_cell {
border: 1px solid #FF0000;
padding: 2px;
word-wrap: break-word;
}
.debug_row_even {
background-color: #CCCCFF;
}
.debug_row_odd {
background-color: #FFFFCC;
}
.debug_layer_container {
left: 2px;
top: 1px;
width: 500px;
z-index: +1000;
position: absolute;
overflow: auto;
border: 2px solid;
padding: 3px;
border-top-color: threedlightshadow;
border-left-color: threedlightshadow;
border-right-color: threeddarkshadow;
border-bottom-color: threeddarkshadow;
background-color: buttonface;
}
.debug_layer {
padding: 0px;
width: 480px;
}
.debug_error {
color: #FF0000;
}
</style>
<div id="debug_layer" class="debug_layer_container" style="display: none;">
<div class="debug_layer">
<table width="100%" cellpadding="0" cellspacing="1" border="0" class="debug_layer_table">
<?php
while ($i < $lineCount)
{
echo '<tr class="debug_row_'.(($i % 2) ? 'odd' : 'even').'"><td class="debug_cell">'.$this->prepareHTML($i).'</td></tr>';
$i++;
}
?>
</table>
</div>
</div>
<script language="javascript">
function getEventKeyCode($e)
{
var $KeyCode = 0;
if($e.keyCode) $KeyCode = $e.keyCode;
else if($e.which) $KeyCode = $e.which;
return $KeyCode;
}
function keyProcessor($e)
{
if(!$e) $e = window.event;
var $KeyCode = getEventKeyCode($e);
if($KeyCode==123||$KeyCode==27) // F12 or ESC
{
toggleDebugLayer($KeyCode);
$e.cancelBubble = true;
if($e.stopPropagation) $e.stopPropagation();
}
}
function toggleDebugLayer($KeyCode)
{
var $isVisible=false;
var $DebugLayer = document.getElementById('debug_layer');
if( typeof($DebugLayer) != 'undefined' )
{
$isVisible = ($DebugLayer.style.display == 'none')?false:true;
if(!$isVisible&&$KeyCode==27) return false;
resizeDebugLayer(null);
$DebugLayer.style.display = $isVisible?'none':'block';
}
}
function prepareSizes($Prefix)
{
var $ret = '';
$ret = eval('document.body.'+$Prefix+'Top')+'; ';
$ret += eval('document.body.'+$Prefix+'Left')+'; ';
$ret += eval('document.body.'+$Prefix+'Height')+'; ';
$ret += eval('document.body.'+$Prefix+'Width')+'; ';
return $ret;
}
function resizeDebugLayer($e)
{
if(!$e) $e = window.event;
var $DebugLayer = document.getElementById('debug_layer');
var $TopMargin = 1;
if( typeof($DebugLayer) != 'undefined' )
{
$DebugLayer.style.top = parseInt(document.body.offsetTop + document.body.scrollTop) + $TopMargin;
$DebugLayer.style.height = document.body.clientHeight - $TopMargin - 5;
}
window.parent.status = 'OFFSET: '+prepareSizes('offset')+' | SCROLL: '+prepareSizes('scroll')+' | CLIENT: '+prepareSizes('client');
window.parent.status += 'DL Info: '+$DebugLayer.style.top+'; S.AH: '+screen.availHeight;
return true;
}
- function SetClipboard($data)
+ function SetClipboard(copyText)
{
- if (window.clipboardData)
- {
- window.clipboardData.setData('Text', $data);
+ if(window.clipboardData)
+ {
+ // IE send-to-clipboard method.
+ window.clipboardData.setData('Text', copyText);
}
else if (window.netscape)
{
- //netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
- var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
- if (!clip) return;
-
- var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
- if (!trans) return;
+ // You have to sign the code to enable this or allow the action in about:config by changing user_pref("signed.applets.codebase_principal_support", true);
+ netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
- trans.addDataFlavor('text/unicode');
- var str = new Object();
- var len = new Object();
+ // Store support string in an object.
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
+ if (!str) return false;
+ str.data=copyText;
- var $copytext=$data;
+ // Make transferable.
+ var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
+ if (!trans) return false;
- str.data=$copytext;
+ // Specify what datatypes we want to obtain, which is text in this case.
+ trans.addDataFlavor("text/unicode");
+ trans.setTransferData("text/unicode",str,copyText.length*2);
- trans.setTransferData("text/unicode",str,$copytext.length*2);
var clipid=Components.interfaces.nsIClipboard;
+ var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
function showProps($Obj, $Name)
{
var $ret = '';
for($Prop in $Obj)
{
$ret += $Name+'.'+$Prop+' = '+$Obj[$Prop]+"\n";
}
return $ret;
}
function editFile($fileName,$lineNo)
{
if(!document.all)
{
alert('Only works in IE');
return;
}
var $editorPath = '<?php echo defined('WINDOWS_EDITOR') ? addslashes(WINDOWS_EDITOR) : '' ?>';
if($editorPath)
{
var $obj = new ActiveXObject("LaunchinIE.Launch");
$editorPath = $editorPath.replace('%F',$fileName);
$editorPath = $editorPath.replace('%L',$lineNo);
$obj.LaunchApplication($editorPath);
}
else
{
alert('Editor path not defined!');
}
}
function toggleTraceArgs($ArgsLayerID)
{
var $ArgsLayer = document.getElementById($ArgsLayerID);
$ArgsLayer.style.display = ($ArgsLayer.style.display == 'none') ? 'block' : 'none';
}
document.onkeydown = keyProcessor;
window.onresize = resizeDebugLayer;
window.onscroll = resizeDebugLayer;
window.focus();
if( typeof($isFatalError) != 'undefined' && $isFatalError == 1 || <?php echo DBG_RAISE_ON_WARNINGS; ?> )
{
toggleDebugLayer();
}
if( typeof($isFatalError) != 'undefined' && $isFatalError == 1)
{
document.getElementById('debug_layer').scrollTop = 10000000;
}
</script>
<?php
$this->memoryUsage['debugger_finish']=memory_get_usage();
$this->memoryUsage['print_report']=$this->memoryUsage['debugger_finish']-$this->memoryUsage['debugger_start'];
$this->memoryUsage['total']=$this->memoryUsage['print_report']+$this->memoryUsage['error_handling'];
$this->memoryUsage['application']=memory_get_usage()-$this->memoryUsage['total'];
if($returnResult)
{
$ret = ob_get_contents();
ob_clean();
if( ConstOn('DBG_SHOW_MEMORY_USAGE') ) $ret.=$this->getMemoryUsageReport();
return $ret;
}
else
{
ob_end_flush();
if( ConstOn('DBG_SHOW_MEMORY_USAGE') ) echo $this->getMemoryUsageReport();
}
}
/**
* Format's memory usage report by debugger
*
* @return string
* @access private
*/
function getMemoryUsageReport()
{
$info=Array('printReport'=>'print_report',
'saveError'=>'error_handling',
'Total'=>'total',
'<u>Application</u>'=>'application');
$ret=Array();
foreach($info as $title => $value_key)
{
$ret[]=$title.': <b>'.$this->formatSize($this->memoryUsage[$value_key]).'</b>';
}
return implode('<br>',$ret);
}
/**
* User-defined error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param array $errcontext
*/
function saveError($errno, $errstr, $errfile = '', $errline = '', $errcontext = '')
{
$memory_used=Array();
$memory_used['begin']=memory_get_usage();
$errorType = $this->getErrorNameByCode($errno);
if(!$errorType)
{
trigger_error('Unknown error type ['.$errno.']', E_USER_ERROR);
return false;
}
$long_id_pos=strrpos($errstr,'#');
if($long_id_pos!==false)
{
// replace short message with long one (due triger_error limitations on message size)
$long_id=substr($errstr,$long_id_pos+1,strlen($errstr));
$errstr=$this->longErrors[$long_id];
unset($this->longErrors[$long_id]);
}
if( strpos($errfile,'eval()\'d code') !== false )
{
$errstr = '[<b>EVAL</b>, line <b>'.$errline.'</b>]: '.$errstr;
$tmpStr = $errfile;
$pos = strpos($tmpStr,'(');
$errfile = substr($tmpStr,0,$pos);
$pos++;
$errline = substr($tmpStr,$pos,strpos($tmpStr,')',$pos)-$pos);
}
if($this->TraceNextError)
{
$this->appendTrace();
$this->TraceNextError=false;
}
$this->Data[] = Array('no' => $errno, 'str' => $errstr, 'file' => $errfile, 'line' => $errline, 'context' => $errcontext, 'debug_type' => 'error');
$memory_used['end']=memory_get_usage();
$this->memoryUsage['error_handling']+=$memory_used['end']-$memory_used['begin'];
if( substr($errorType,0,5) == 'Fatal')
{
echo '<script language="javascript">var $isFatalError = 1;</script>';
exit;
}
}
function saveToFile($msg)
{
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/vb_debug.txt', 'a');
fwrite($fp,$msg."\n");
fclose($fp);
}
/**
* Formats file/memory size in nice way
*
* @param int $bytes
* @return string
* @access public
*/
function formatSize($bytes)
{
if ($bytes >= 1099511627776) {
$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "TB";
} elseif ($bytes >= 1073741824) {
$return = round($bytes / 1024 / 1024 / 1024, 2);
$suffix = "GB";
} elseif ($bytes >= 1048576) {
$return = round($bytes / 1024 / 1024, 2);
$suffix = "MB";
} elseif ($bytes >= 1024) {
$return = round($bytes / 1024, 2);
$suffix = "KB";
} else {
$return = $bytes;
$suffix = "Byte";
}
$return .= ' '.$suffix;
return $return;
}
}
function ConstOn($const_name)
{
return defined($const_name)&&constant($const_name);
}
$debugger = new Debugger();
if(ConstOn('DBG_HANDLE_ERRORS')) set_error_handler( array(&$debugger,'saveError') );
if(ConstOn('DBG_USE_SHUTDOWN_FUNC')) register_shutdown_function( array(&$debugger,'printReport') );
?>
\ No newline at end of file
Property changes on: trunk/kernel/include/debugger.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.20
\ No newline at end of property
+1.21
\ No newline at end of property
Index: trunk/admin/users/addgroup_users.php
===================================================================
--- trunk/admin/users/addgroup_users.php (revision 998)
+++ trunk/admin/users/addgroup_users.php (revision 999)
@@ -1,358 +1,358 @@
<?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");
unset($objEditItems);
$objEditItems = new clsGroupList();
$objEditItems->SourceTable = $objSession->GetEditTable("PortalGroup");
$objEditItems->EnablePaging = FALSE;
$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_group";
$envar = "env=" . BuildEnv() . "&en=$en";
/* -------------------------------------- Section configuration ------------------------------------------- */
$section = 'in-portal:editgroup_users';
$sec = $objSections->GetSection($section);
$SortFieldVar = "User_SortField";
$SortOrderVar = "User_SortOrder";
$DefaultSortField = "Login";
$PerPageVar = "Perpage_User";
$CurrentPageVar = "Page_UserList";
$CurrentFilterVar = "User_View";
$ListForm = "editgroup";
$CheckClass = "UserChecks";
/* ------------------------------------- Configure the toolbar ------------------------------------------- */
$objListToolBar = new clsToolBar();
$objListToolBar->Set("section",$section);
$objListToolBar->Set("load_menu_func","");
$objListToolBar->Set("CheckClass",$CheckClass);
$objListToolBar->Set("CheckForm",$ListForm);
$objListToolBar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","do_edit_save('editgroup','GroupEditStatus','".$admin."/users/user_groups.php',1);","tool_select.gif");
$objListToolBar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","do_edit_save('editgroup','GroupEditStatus','".$admin."/users/user_groups.php',2);","tool_cancel.gif");
if($itemcount == 1) $objListToolBar->Add("divider");
if ( isset($en_prev) || isset($en_next) )
{
$url = $RootUrl.$admin."/users/addgroup_users.php";
$StatusField = "GroupEditStatus";
$form = "editgroup";
MultiEditButtons($objListToolBar,$en_next,$en_prev,$form,$StatusField,$url,$sec->Get("OnClick"),'','la_PrevGroup','la_NextGroup');
$objListToolBar->Add("divider");
}
$listImages = array();
//$img, $alt, $link, $onMouseOver, $onMouseOut, $onClick
$objListToolBar->Add("new_group", "la_ToolTip_AddUserToGroup","","swap('new_group','toolbar/tool_usertogroup_f2.gif');",
"swap('new_group', 'toolbar/tool_usertogroup.gif');",
"OpenUserSelector('','','$envar&source=addgroup_users&GroupId=".$c->Get("GroupId")."&destform=popup&destfield=userlist&Selector=radio&dosubmit=1');",
"tool_usertogroup.gif");
$objListToolBar->Add("user_del","la_ToolTip_RemoveUserFromGroup","#", "if (UserChecks.itemChecked()) swap('user_del','toolbar/tool_delete_f2.gif');",
"if (UserChecks.itemChecked()) swap('user_del', 'toolbar/tool_delete.gif');","if (UserChecks.itemChecked()) UserChecks.check_submit('addgroup_users', 'm_group_removeuser');",
"tool_delete.gif");
$listImages[] = "UserChecks.addImage('user_del','$imagesURL/toolbar/tool_delete.gif','$imagesURL/toolbar/tool_delete_f3.gif',1); ";
$objListToolBar->Add("divider");
$objListToolBar->Add("user_print", "la_ToolTip_Print","#","swap('user_print','toolbar/tool_print_f2.gif');",
"swap('user_print', 'toolbar/tool_print.gif');","window.print();","tool_print.gif");
$objListToolBar->Add("viewmenubutton", "la_ToolTip_View","#","swap('viewmenubutton','toolbar/tool_view_f2.gif'); ",
"swap('viewmenubutton', 'toolbar/tool_view.gif');",
"ShowViewMenu();","tool_view.gif");
$objListToolBar->AddToInitScript($listImages);
$objListToolBar->AddToInitScript("fwLoadMenus();");
/* ----------------------------------------- Set the View Filter ---------------------------------------- */
/* bit place holders for category view menu */
$Bit_Pending=4;
$Bit_Disabled=2;
$Bit_Valid=1;
$Bit_All = 7;
$FilterLabels = array();
$FilterLabels[0] = admin_language("la_Text_Enabled");
$FilterLabels[1] = admin_language("la_Text_Disabled");
$FilterLabels[2] = admin_language("la_Text_Pending");
/* determine current view menu settings */
$UserView = $objConfig->Get("User_View");
if(!is_numeric($UserView))
{
$UserView = $Bit_All; //Set all bits ON
$UserFilter = "";
}
if($UserView & $Bit_Valid)
$Status[] = 1;
if($UserView & $Bit_Disabled)
$Status[] = 0;
if($UserView & $Bit_Pending)
$Status[] = 2;
if(count($Status)>0)
{
$UserFilter = "Status IN (".implode(",",$Status).")";
}
else
$UserFilter = "Status = -1";
$GroupUsers = $c->GetUserList();
if(count($GroupUsers)>0)
{
$list = implode(",",$GroupUsers);
$where = "u.PortalUserId IN ($list) ";
}
else
{
$list=0;
$where = "u.PortalUserId = -1 ";
}
$order = $objConfig->Get("User_SortOrder");
$SearchWords = $objSession->GetVariable("UserGroupSearchWord");
if(strlen($SearchWords))
{
$where .= $objUsers->AdminSearchWhereClause($SearchWords);
}
-$sql = "SELECT u.*,g.Name as GroupName,ELT(u.status+1,'".admin_language("la_Text_Disabled")." ','".admin_language("la_Text_Enabled")." ','".admin_language("la_Text_Pending")."') as UserStatus, ";
-$sql .="FROM_UNIXTIME(u.CreatedOn,'%m-%d-%Y') as DateCreated FROM ".GetTablePrefix()."PortalUser as u ";
-$sql .="LEFT JOIN ".$objSession->GetEditTable("UserGroup")." as ug ON (u.PortalUserId=ug.PortalUserId) AND (ug.PrimaryGroup = 1) ";
+$sql = "SELECT u.*,g.Name AS GroupName,ELT(u.status+1,'".admin_language("la_Text_Disabled")." ','".admin_language("la_Text_Enabled")." ','".admin_language("la_Text_Pending")."') as UserStatus, ";
+$sql .="FROM_UNIXTIME(u.CreatedOn,'%m-%d-%Y') AS DateCreated FROM ".GetTablePrefix()."PortalUser as u ";
+$sql .="LEFT JOIN ".GetTablePrefix()."UserGroup AS ug ON (u.PortalUserId=ug.PortalUserId) AND (ug.PrimaryGroup = 1) ";
$sql .="LEFT JOIN ".GetTablePrefix()."PortalGroup as g ON (ug.GroupId=g.GroupId) WHERE 1";
if(strlen($where))
$sql .= " AND ".$where;
//$sql .=" ".GetLimitSQL($objSession->GetVariable("Page_Userlist"),$objConfig->Get("Perpage_User"));
$objListView = new clsListView($objListToolBar);
$objListView->CurrentPageVar = "Page_Userlist";
$objListView->PerPageVar = "Perpage_User";
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
$objUsers->Query_Item($sql, $objListView->GetLimitSQL() );
$itemcount = $list?TableCount(GetTablePrefix()."PortalUser","PortalUserId IN ($list)",0):0;
$objListView->SetListItems($objUsers);
$objListView->IdField = "ResourceId";
$objListView->PageLinkTemplate = $pathtoroot. $admin."/templates/user_page_link.tpl";
$objListView->ColumnHeaders->Add("Login",admin_language("la_prompt_Username"),1,0,$order,"width=\"15%\"","User_SortField","User_SortOrder","Login");
$objListView->ColumnHeaders->Add("LastName",admin_language("la_prompt_Last_Name"),1,0,$order,"width=\"15%\"","User_SortField","User_SortOrder","LastName");
$objListView->ColumnHeaders->Add("FirstName",admin_language("la_prompt_First_Name"),1,0,$order,"width=\"15%\"","User_SortField","User_SortOrder","FirstName");
$objListView->ColumnHeaders->Add("Email",admin_language("la_prompt_Email"),1,0,$order,"width=\"20%\"","User_SortField","User_SortOrder","Email");
$objListView->ColumnHeaders->Add("GroupName",admin_language("la_prompt_PrimaryGroup"),1,0,$order,"width=\"20%\"","User_SortField","User_SortOrder","GroupName");
$objListView->ColumnHeaders->Add("DateCreated",admin_language("la_prompt_CreatedOn"),1,0,$order,"width=\"15%\"","User_SortField","User_SortOrder","DateCreated");
$objListView->ColumnHeaders->SetSort($objConfig->Get("User_SortField"),$order);
$objListView->PrintToolBar = FALSE;
$objListView->SearchBar = TRUE;
$objListView->SearchKeywords = $SearchWords;
$objListView->SearchAction="m_usergroup_search";
$objListView->CheckboxName = "itemlist[]";
$objListView->TotalItemCount = $itemcount;
for($i=0;$i<count($objUsers->Items);$i++)
{
$u =& $objUsers->GetItemRefByIndex($i);
$objListView->RowIcons[] = $u->StatusIcon();
}
$objListView->ConfigureViewMenu($SortFieldVar,$SortOrderVar,$DefaultSortField,
$CurrentFilterVar,$UserView,$Bit_All);
foreach($FilterLabels as $Bit=>$Label)
{
$objListView->AddViewMenuFilter($Label,$Bit);
}
$filter = false; // always initialize variables before use
if($objSession->GetVariable("UserGroupSearchWord") != '') {
$filter = true;
}
else {
if ($UserView != $Bit_All) {
$filter = true;
}
}
$title = GetTitle("la_Text_Group", "la_tab_Users", $c->Get('GroupId'), $c->Get('Name'));//prompt_language("la_Text_Editing")." ".prompt_language("la_Text_Group")." '".$c->Get("Name")."' - ".prompt_language("la_tab_Users");
$h = "\n\n<SCRIPT Language=\"JavaScript1.2\">\n".$objListView->GetViewMenu($imagesURL)."\n</SCRIPT>\n";
int_header($objListToolBar,NULL, $title,NULL,$h);
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 } ?>
<?php if ($filter) { ?>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="toolbar">
<tr>
<td valign="top">
<?php int_hint_red(admin_language("la_Warning_Filter")); ?>
</td>
</tr>
</table>
<?php } ?>
<FORM method="POST" ACTION="" NAME="editgroup" ID="editgroup">
<?php
print $objListView->PrintList();
?>
<input type="hidden" name="Action" value="">
<INPUT TYPE="HIDDEN" NAME="GroupId" VALUE="<?php echo $c->Get("GroupId"); ?>">
<input type="hidden" name="GroupEditStatus" VALUE="0">
</FORM>
<FORM NAME="popup" ID="popup" METHOD="POST" ACTION="<?php echo $_SERVER["PHP_SELF"]."?env=".BuildEnv(); ?>">
<INPUT TYPE="hidden" NAME="userlist">
<input TYPE="hidden" NAME="Action" VALUE="m_group_add_user">
<INPUT TYPE="HIDDEN" NAME="GroupId" VALUE="<?php echo $c->Get("GroupId"); ?>">
</FORM>
<!-- CODE FOR VIEW MENU -->
<form ID="viewmenu" method="post" action="<?php echo $_SERVER["PHP_SELF"]."?env=".BuildEnv(); ?>" 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>
<FORM ID="ListSearchForm" NAME="ListSearchForm" method="POST" action="<?php echo $_SERVER["PHP_SELF"]."?env=".BuildEnv(); ?>">
<INPUT TYPE="HIDDEN" NAME="Action" VALUE="">
<INPUT TYPE="HIDDEN" NAME="list_search">
</FORM>
<FORM NAME="save_edit_buttons" ID="save_edit_buttons" method="POST" ACTION="">
<tr <?php int_table_color(); ?>>
<td colspan="5">
<input type=hidden NAME="Action" VALUE="save_user_edit">
<input type="hidden" name="GroupEditStatus" VALUE="0">
</td>
</tr>
</FORM>
<script src="<?php echo $adminURL; ?>/listview/listview.js"></script>
<script>
initSelectiorContainers();
<?php echo $objListToolBar->Get("CheckClass").".setImages();"; ?>
</script>
<!-- END CODE-->
<?php int_footer(); ?>
\ No newline at end of file
Property changes on: trunk/admin/users/addgroup_users.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.9
\ No newline at end of property
+1.10
\ No newline at end of property

Event Timeline