True,
'get_info_msg' => True,
'get_info_msgs' => True,
'get_folders_list' => True,
'import_msgs' => True
);
var $ldap;
var $mbox;
var $imap_port;
var $has_cid;
var $imap_options = '';
var $functions;
var $foldersLimit;
function imap_functions (){
$this->foldersLimit = 200; //Limit of folders (mailboxes) user can see
$this->username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
$this->password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
$this->imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
$this->imap_port = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
$this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
$this->functions = new functions();
$this->has_cid = false;
if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
{
$this->imap_options = '/tls/novalidate-cert';
}
else
{
$this->imap_options = '/notls/novalidate-cert';
}
}
// BEGIN of functions.
function open_mbox($folder = False)
{
$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
$this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
return $this->mbox;
}
function parse_error($error){
// This error is returned from Imap.
if(strstr($error,'Connection refused')) {
return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
}
// This error is returned from Postfix.
elseif(strstr($error,'message file too big')) {
return str_replace("%1", ini_get('upload_max_filesize'),$this->functions->getLang('The size of this message has exceeded the limit (%1B).'));
}
elseif(strstr($error,'virus')) {
return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
}
// This condition verifies if SESSION is expired.
elseif(!count($_SESSION))
return "nosession";
return $error;
}
function get_range_msgs2($params)
{
$folder = $params['folder'];
$msg_range_begin = $params['msg_range_begin'];
$msg_range_end = $params['msg_range_end'];
$sort_box_type = $params['sort_box_type'];
$sort_box_reverse = $params['sort_box_reverse'];
$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
$sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
$return = array();
$i = 0;
$num_msgs = (is_array($sort_array_msg) ? count($sort_array_msg) : 0);
if($num_msgs) {
for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= $num_msgs)); $msg_range_begin++)
{
$msg_number = $sort_array_msg[$msg_range_begin-1];
$temp = $this->get_info_head_msg($msg_number);
if(!$temp)
return false;
$return[$i] = $temp;
$i++;
}
}
$return['num_msgs'] = $num_msgs;
return $return;
}
function get_info_head_msg($msg_number) {
$head_array = array();
include_once("class.imap_attachment.inc.php");
$imap_attachment = new imap_attachment();
/*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
* atributos do cabeçalho. Como eu preciso do atributo Importance
* para saber se o email é importante ou não, uso abaixo a função
* imap_fetchheader e busco o atributo importance nela para passar
* para as funções ajax. Isso faz com que eu acesse o cabeçalho
* duas vezes e de duas formas diferentes, mas em contrapartida, eu
* não preciso reimplementar o método utilizando o fetchheader.
* Como as mensagens são renderizadas de X em X, não parece ter
* perda considerável de performance.
*/
$flag = preg_match('/importance *: *(.*)\r/i',
imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
,$importance);
$head_array['Importance'] = $flag==0?"Normal":$importance[1];
$header = $this->get_header($msg_number);
if (!is_object($header))
return false;
$head_array['Recent'] = $header->Recent;
$head_array['Unseen'] = $header->Unseen;
if($header->Answered =='A' && $header->Draft == 'X'){
$head_array['Forwarded'] = 'F';
}
else {
$head_array['Answered'] = $header->Answered;
$head_array['Draft'] = $header->Draft;
}
$head_array['Deleted'] = $header->Deleted;
$head_array['Flagged'] = $header->Flagged;
$head_array['msg_number'] = $msg_number;
//$return[$i]['msg_folder'] = $folder;
$date_msg = gmdate("d/m/Y",$header->udate);
if (date("d/m/Y") == $date_msg)
$head_array['udate'] = gmdate("H:i",$header->udate);
else
$head_array['udate'] = $date_msg;
$head_array['aux_date'] = $date_msg; //Auxiliar apenas para mensagens locais.
$from = $header->from;
$head_array['from'] = array();
$tmp = imap_mime_header_decode($from[0]->personal);
$head_array['from']['name'] = $this->decode_string($tmp[0]->text);
$head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
if(!$head_array['from']['name'])
$head_array['from']['name'] = $head_array['from']['email'];
$to = $header->to;
$head_array['to'] = array();
$tmp = imap_mime_header_decode($to[0]->personal);
$head_array['to']['name'] = $this->decode_string($this->decode_string($tmp[0]->text));
$head_array['to']['email'] = $this->decode_string($to[0]->mailbox) . "@" . $to[0]->host;
if(!$head_array['to']['name'])
$head_array['to']['name'] = $head_array['to']['email'];
$head_array['subject'] = $this->decode_string($header->fetchsubject);
$head_array['Size'] = $header->Size;
$head_array['attachment'] = array();
$head_array['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
return $head_array;
}
function decode_string($string)
{
if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
{
$tmp = imap_mime_header_decode($string);
foreach ($tmp as $tmp1)
$return .= $this->htmlspecialchars_encode($tmp1->text);
return $return;
}
else if (strpos(strtolower($string), '=?utf-8') !== false)
{
$elements = imap_mime_header_decode($string);
for($i = 0;$i < count($elements);$i++) {
$charset = $elements[$i]->charset;
$text =$elements[$i]->text;
if(!strcasecmp($charset, "utf-8") ||
!strcasecmp($charset, "utf-7")) {
$text = iconv($charset, "ISO-8859-1", $text);
}
$decoded .= $this->htmlspecialchars_encode($text);
}
return $decoded;
}
else
return $this->htmlspecialchars_encode($string);
}
/**
* Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
* com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
*/
function import_msgs($params) {
if(!$this->mbox)
$this->mbox = $this->open_mbox();
$errors = array();
$invalid_format = false;
$filename = $params['FILES'][0]['name'];
$quota = imap_get_quotaroot($this->mbox, $params["folder"]);
if((($quota['limit'] - $quota['usage'])*1024) <= $params['FILES'][0]['size']){
return array( 'error' => $this->functions->getLang("fail in import:").
" ".$this->functions->getLang("Over quota"));
}
if(substr($filename,strlen($filename)-4)==".zip") {
$zip = zip_open($params['FILES'][0]['tmp_name']);
if ($zip) {
while ($zip_entry = zip_read($zip)) {
if (zip_entry_open($zip, $zip_entry, "r")) {
$email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
$status = @imap_append($this->mbox,
"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
$email
);
if(!$status)
array_push($errors,zip_entry_name($zip_entry));
zip_entry_close($zip_entry);
}
}
zip_close($zip);
}
}
else if(substr($filename,strlen($filename)-4)==".eml") {
$email = implode("",file($params['FILES'][0]['tmp_name']));
$status = @imap_append($this->mbox,
"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
$email
);
if(!$status){
array_push($errors,zip_entry_name($zip_entry));
zip_entry_close($zip_entry);
}
}
else
{
return array("error" => $this->functions->getLang("wrong file format"));
$invalid_format = true;
}
if(!$invalid_format) {
if(count($errors)>0) {
$message = $this->functions->getLang("fail in import:")."\n";
foreach($errors as $arquivo) {
$message.=$arquivo."\n";
}
return array("error" => $message);
}
else
return $this->functions->getLang("The import was executed successfully.");
}
}
/*
Remove os anexos de uma mensagem. A estratégia para isso é criar uma mensagem nova sem os anexos, mantendo apenas
a primeira parte do e-mail, que é o texto, sem anexos.
O método considera que o email é multpart.
*/
function remove_attachments($params) {
include_once("class.message_components.inc.php");
if(!$this->mbox || !is_resource($this->mbox))
$this->mbox = $this->open_mbox($params["folder"]);
$return["status"] = true;
$return["msg_num"] = $params["msg_num"];
$header = "";
$headertemp = explode("\n",imap_fetchheader($this->mbox, imap_msgno($this->mbox, $params["msg_num"])));
foreach($headertemp as $head) {//Se eu colocar todo o header do email dá pau no append, então procuro apenas o que interessa.
$head1 = explode(":",$head);
if ( (strtoupper($head1[0]) == strtoupper("to")) ||
(strtoupper($head1[0]) == strtoupper("from")) ||
(strtoupper($head1[0]) == strtoupper("subject")) ||
(strtoupper($head1[0]) == strtoupper("date")) )
$header .= $head."\r\n";
}
$msg = &new message_components($this->mbox);
$msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
Então uso essa classe para verificar a codificação e o charset,
para que o método decodeBody do expresso possa trazer tudo certinho*/
$status = @imap_append($this->mbox,
"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
$header.
"\r\n".
str_replace("\n","\r\n",$this->decodeBody(
imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),"1"),
$msg->encoding[$params["msg_num"]][0], $msg->charset[$params["msg_num"]][0]
)
)); //Append do novo email, só com header e conteúdo sem anexos.
if(!$status) {
$return["status"] = false;
$return["msg"] = lang("error appending mail on delete attachments");
}
@imap_delete($this->mbox, imap_msgno($this->mbox, $params["msg_num"])); //Insere o novo e-mail sem anexos.
@imap_expunge($this->mbox); //Deleta o e-mail com anexos
return $return;
}
/**
*
* @return
* @param $params Object
*/
function get_info_msgs($params) {
include_once("class.exporteml.inc.php");
$return = array();
$new_params = array();
$attach_params = array();
$new_params["msg_folder"]=$params["folder"];
$attach_params["folder"] = $params["folder"];
$msgs = explode(",",$params["msgs_number"]);
$exporteml = new ExportEml();
foreach($msgs as $msg_number) {
$new_params["msg_number"] = $msg_number;
//ini_set("display_errors","1");
$msg_info = $this->get_info_msg($new_params);
$this->mbox = $this->open_mbox($params['folder']); //Não sei porque, mas se não abrir de novo a caixa dá erro.
$msg_info['header'] = $this->get_info_head_msg($msg_number);
$attach_params["num_msg"] = $msg_number;
$msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
$msg_info['url_export_file'] = $exporteml->export_to_archive($msg_number,$params["folder"]);
imap_close($this->mbox);
$this->mbox=false;
array_push($return,serialize($msg_info));
}
return $return;
}
function get_info_msg($params)
{
$return = array();
$msg_number = $params['msg_number'];
$msg_folder = $params['msg_folder'];
if(!$this->mbox || !is_resource($this->mbox))
$this->mbox = $this->open_mbox($msg_folder);
$header = $this->get_header($msg_number);
if (!$header) {
$return['status_get_msg_info'] = "false";
return $return;
}
$all_header = explode("\n", imap_fetchheader($this->mbox, $msg_number, FT_UID));
$return_get_body = $this->get_body_msg($msg_number, $msg_folder);
//Substituição de links em email para abrir no próprio expresso
$body = ereg_replace("]*href=[\'\"]mailto:([^\"\']+)[\'\"]>([^<]+)","\\2",$return_get_body['body']);
$return['body'] = $body;
$return['attachments'] = $return_get_body['attachments'];
$return['thumbs'] = $return_get_body['thumbs'];
$return['signature'] = $return_get_body['signature'];
foreach($all_header as $line) {
if (eregi("^Disposition-Notification-To", $line)) {
eregi("^([^:]*): (.*)", $line, &$arg);
$return['DispositionNotificationTo'] = $arg[2];
}
}
$return['Recent'] = $header->Recent;
$return['Unseen'] = $header->Unseen;
$return['Deleted'] = $header->Deleted;
$return['Flagged'] = $header->Flagged;
if($header->Answered =='A' && $header->Draft == 'X'){
$return['Forwarded'] = 'F';
}
else {
$return['Answered'] = $header->Answered;
$return['Draft'] = $header->Draft;
}
$return['msg_number'] = $msg_number;
$return['msg_folder'] = $msg_folder;
$date_msg = gmdate("d/m/Y",$header->udate);
if (date("d/m/Y") == $date_msg)
$return['udate'] = gmdate("H:i",$header->udate);
else
$return['udate'] = $date_msg;
$return['msg_day'] = $date_msg;
$return['msg_hour'] = gmdate("H:i",$header->udate);
if (date("d/m/Y") == $date_msg) //no dia
{
$return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
$return['smalldate'] = gmdate("H:i",$header->udate);
$timestamp_now = strtotime("now");
$timestamp_msg_time = $header->udate;
// $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ.
// The variable $timestamp_diff is calculated without MailDate TZ.
$pdate = date_parse($header->MailDate);
$timestamp_diff = $timestamp_now - $timestamp_msg_time + ($pdate['zone']*(-60));
if (gmdate("H",$timestamp_diff) > 0)
{
$return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
}
else
{
if (gmdate("i",$timestamp_diff) == 0){
$return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
}
elseif (gmdate("i",$timestamp_diff) == 1){
$return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
}
else{
$return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
}
}
}
else{
$return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
$return['smalldate'] = gmdate("d/m/Y",$header->udate);
}
$from = $header->from;
$return['from'] = array();
$tmp = imap_mime_header_decode($from[0]->personal);
$return['from']['name'] = $this->decode_string($tmp[0]->text);
$return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
if ($return['from']['name'])
{
if (substr($return['from']['name'], 0, 1) == '"')
$return['from']['full'] = $return['from']['name'] . ' ' . '<' . $return['from']['email'] . '>';
else
$return['from']['full'] = '"' . $return['from']['name'] . '" ' . '<' . $return['from']['email'] . '>';
}
else
$return['from']['full'] = $return['from']['email'];
// Sender attribute
$sender = $header->sender;
$return['sender'] = array();
$tmp = imap_mime_header_decode($sender[0]->personal);
$return['sender']['name'] = $this->decode_string($tmp[0]->text);
$return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
if ($return['sender']['name'])
{
if (substr($return['sender']['name'], 0, 1) == '"')
$return['sender']['full'] = $return['sender']['name'] . ' ' . '<' . $return['sender']['email'] . '>';
else
$return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '<' . $return['sender']['email'] . '>';
}
else
$return['sender']['full'] = $return['sender']['email'];
if($return['from']['full'] == $return['sender']['full'])
$return['sender'] = null;
$to = $header->to;
$return['toaddress2'] = "";
if (!empty($to))
{
foreach ($to as $tmp)
{
if (!empty($tmp->personal))
{
$personal_tmp = imap_mime_header_decode($tmp->personal);
$return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
$return['toaddress2'] .= " ";
$return['toaddress2'] .= "<";
if ($tmp->host != 'unspecified-domain')
$return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
else
$return['toaddress2'] .= $tmp->mailbox;
$return['toaddress2'] .= ">";
$return['toaddress2'] .= ", ";
}
else
{
if ($tmp->host != 'unspecified-domain')
$return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
else
$return['toaddress2'] .= $tmp->mailbox;
$return['toaddress2'] .= ", ";
}
}
$return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
}
else
{
$return['toaddress2'] = "<Empty>";
}
$cc = $header->cc;
$return['cc'] = "";
if (!empty($cc))
{
foreach ($cc as $tmp_cc)
{
if (!empty($tmp_cc->personal))
{
$personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
$return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
$return['cc'] .= " ";
$return['cc'] .= "<";
$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
$return['cc'] .= ">";
$return['cc'] .= ", ";
}
else
{
$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
$return['cc'] .= ", ";
}
}
$return['cc'] = $this->del_last_two_caracters($return['cc']);
}
else
{
$return['cc'] = "";
}
##
# @AUTHOR Rodrigo Souza dos Santos
# @DATE 2008/09/12
# @BRIEF Adding the BCC field.
##
$bcc = $header->bcc;
$return['bcc'] = "";
if (!empty($bcc))
{
foreach ($bcc as $tmp_bcc)
{
if (!empty($tmp_bcc->personal))
{
$personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
$return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
$return['bcc'] .= " ";
$return['bcc'] .= "<";
$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
$return['bcc'] .= ">";
$return['bcc'] .= ", ";
}
else
{
$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
$return['bcc'] .= ", ";
}
}
$return['bcc'] = $this->del_last_two_caracters($return['bcc']);
}
else
{
$return['bcc'] = "";
}
$reply_to = $header->reply_to;
$return['reply_to'] = "";
if (is_object($reply_to[0]))
{
if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
{
if (!empty($reply_to[0]->personal))
{
$personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
if(!empty($personal_reply_to[0]->text)) {
$return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
$return['reply_to'] .= " ";
$return['reply_to'] .= "<";
$return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
$return['reply_to'] .= ">";
}
else {
$return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
}
}
else
{
$return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
}
}
}
$return['reply_to'] = $this->decode_string($return['reply_to']);
$return['subject'] = $this->decode_string($header->fetchsubject);
$return['Size'] = $header->Size;
$return['reply_toaddress'] = $header->reply_toaddress;
//All this is to help in local messages
$return['timestamp'] = $header->udate;
$return['login'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];//$GLOBALS['phpgw_info']['user']['account_id'];
$return['reply_toaddress'] = $header->reply_toaddress;
return $return;
}
function get_body_msg($msg_number, $msg_folder)
{
include_once("class.message_components.inc.php");
$msg = &new message_components($this->mbox);
$msg->fetch_structure($msg_number);
$return = array();
$return['attachments'] = $this-> download_attachment($msg,$msg_number);
if(!$this->has_cid)
{
$return['thumbs'] = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
$return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
}
if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
{
$attachment = array(); //No attachments
$content = '';
if (strtolower($msg->structure[$msg_number]->subtype) == "plain")
{
$content .= nl2br($this->decodeBody((imap_body($this->mbox, $msg_number, FT_UID)), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]));
}
else if (strtolower($msg->structure[$msg_number]->subtype) == "html")
{
$content .= $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
}
}
else
{ //Complicated message, multiple parts
$html_body = '';
$content = '';
$has_multipart = true;
$this->has_cid = false;
if (strtolower($msg->structure[$msg_number]->subtype) == "related")
$this->has_cid = true;
if (strtolower($msg->structure[$msg_number]->subtype) == "alternative") {
$show_only_html = false;
foreach($msg->pid[$msg_number] as $values => $msg_part) {
$file_type = strtolower($msg->file_type[$msg_number][$values]);
if($file_type == "text/html")
$show_only_html = true;
}
}
else
$show_only_html = false;
foreach($msg->pid[$msg_number] as $values => $msg_part)
{
$file_type = strtolower($msg->file_type[$msg_number][$values]);
if($file_type == "message/rfc822")
$has_multipart = false;
if($file_type == "multipart/alternative")
$has_multipart = false;
if(($file_type == "text/plain"
|| $file_type == "text/html")
&& $file_type != 'attachment')
{
if($file_type == "text/plain" && !$show_only_html && $has_multipart)
{
// if TXT file size > 100kb, then it will not expand.
if(!($file_type == "text/plain" && $msg->fsize[$msg_number][$values] > 102400)) {
$content .= nl2br(htmlentities($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values])));
}
}
// if HTML attachment file size > 300kb, then it will not expand.
else if($file_type == "text/html" && $msg->fsize[$msg_number][$values] < 307200)
{
$content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
$show_only_html = true;
}
}
else if($file_type == "message/delivery-status"){
$content .= "
";
$content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));
}
else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
include_once("class.imap_attachment.inc.php");
$att = new imap_attachment();
$attachments = $att -> get_attachment_info($this->mbox,$msg_number);
if($attachments['number_attachments'] > 0) {
foreach($attachments ['attachment'] as $index => $attachment){
if(strtolower($attachment['type']) == "delivery-status" ||
strtolower($attachment['type']) == "rfc822" ||
strtolower($attachment['type']) == "rfc822-headers" ||
strtolower($attachment['type']) == "plain"
){
$obj = imap_rfc822_parse_headers(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values]);
$content .= "
";
$content .= "
";
$content .= "".$this->functions->getLang("Subject").": | ".$this->decode_string($obj->subject)." |
";
$content .= "".$this->functions->getLang("From").": | ".$this->decode_string($obj->from[0]->mailbox."@".$obj->from[0]->host)." |
";
$content .= "".$this->functions->getLang("Date").": | ".$obj->date." |
";
$content .= "".$this->functions->getLang("TO").": | ".$this->decode_string($obj->to[0]->mailbox."@".$obj->to[0]->host)." |
";
$content .= !$obj->cc ? "
" :"".$this->functions->getLang("CC").": | ".$this->decode_string($obj->cc[0]->mailbox."@".$obj->cc[0]->host)." |
";
$ix_part = strtolower($attachment['type']) == "delivery-status" ? 1 : 0;
$content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, ($attachment['part_in_msg']+$ix_part).".1", FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));
break;
}
}
}
}
}
if($file_type == "text/plain" && ($show_only_html && $msg_part == 1) || (!$show_only_html && $msg_part == 3)){
if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" && $msg_part == 1)
$content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
$content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));
}
}
// Force message with flag Seen (imap_fetchbody not works correctly)
$params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");
$this->set_messages_flag($params);
$content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
$content = $this->replace_special_characters($content);
$return['body'] = $content;
return $return;
}
function htmlfilter($body)
{
require_once('htmlfilter.inc');
$tag_list = Array(
false,
'blink',
'object',
'meta',
'html',
'link',
'frame',
'iframe',
'layer',
'ilayer',
'plaintext'
);
/**
* A very exclusive set:
*/
// $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
$rm_tags_with_content = Array(
'script',
'style',
'applet',
'embed',
'head',
'frameset',
'xml',
'xmp'
);
$self_closing_tags = Array(
'img',
'br',
'hr',
'input'
);
$force_tag_closing = true;
$rm_attnames = Array(
'/.*/' =>
Array(
'/target/i',
//'/^on.*/i', -> onClick, dos compromissos da agenda.
'/^dynsrc/i',
'/^datasrc/i',
'/^data.*/i',
'/^lowsrc/i'
)
);
/**
* Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
* some idea of what's going on here. :)
*/
$bad_attvals = Array(
'/.*/' =>
Array(
'/.*/' =>
Array(
Array(
'/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
//'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
'/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
'/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
),
Array(
'\\1oddjob:\\2\\1',
//'\\1uucp:\\2\\1', -> doclinks notes
'\\1amaretto:\\2\\1',
'\\1round:\\2\\1'
)
),
'/^style/i' =>
Array(
Array(
'/expression/i',
'/behaviou*r/i',
'/binding/i',
'/include-source/i',
'/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
'/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
),
Array(
'idiocy',
'idiocy',
'idiocy',
'idiocy',
'url(\\1http://securityfocus.com/\\1)',
'url(\\1http://securityfocus.com/\\1)'
)
)
)
);
$add_attr_to_tag = Array(
'/^a$/i' => Array('target' => '"_new"')
);
$trusted_body = sanitize($body,
$tag_list,
$rm_tags_with_content,
$self_closing_tags,
$force_tag_closing,
$rm_attnames,
$bad_attvals,
$add_attr_to_tag
);
return $trusted_body;
}
function decodeBody($body, $encoding, $charset=null)
{
/**
* replace e-mail by anchor.
*/
// HTML Filter
//$body = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1\\2@\\3", $body);
$body = str_replace("\r\n", "\n", $body);
if ($encoding == 'quoted-printable')
{
for($i=0;$i<256;$i++) {
$c1=dechex($i);
if(strlen($c1)==1){$c1="0".$c1;}
$c1="=".$c1;
$myqprinta[]=$c1;
$myqprintb[]=chr($i);
}
$body = str_replace($myqprinta,$myqprintb,($body));
$body = quoted_printable_decode($body);
while (ereg("=\n", $body))
{
$body = ereg_replace ("=\n", '', $body);
}
}
else if ($encoding == 'base64')
{
$body = base64_decode($body);
}
/*else if ($encoding == '7bit')
{
$body = quoted_printable_decode($body);
}*/
// All other encodings are returned raw.
if (strtolower($charset) == "utf-8")
return utf8_decode($body);
else
return $body;
}
function process_embedded_images($msg, $msgno, $body, $msg_folder)
{
if (count($msg->inline_id[$msgno]) > 0)
{
foreach ($msg->inline_id[$msgno] as $index => $cid)
{
$cid = eregi_replace("<", "", $cid);
$cid = eregi_replace(">", "", $cid);
$msg_part = $msg->pid[$msgno][$index];
//$body = eregi_replace("alt=\"\"", "", $body);
$body = eregi_replace("
", "", $body);
$body = str_replace("src=\"cid:".$cid."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
$body = str_replace("src='cid:".$cid."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
$body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
}
}
return $body;
}
function replace_special_characters($body)
{
// Suspected TAGS!
/*$tag_list = Array(
'blink','object','meta',
'html','link','frame',
'iframe','layer','ilayer',
'plaintext','script','style','img',
'applet','embed','head',
'frameset','xml','xmp');
*/
// Layout problem: Change html elements
// with absolute position to relate position, CASE INSENSITIVE.
$body = @eregi_replace("POSITION: ABSOLUTE;","",$body);
$tag_list = Array('head','blink','object','frame',
'iframe','layer','ilayer','plaintext','script',
'applet','embed','frameset','xml','xmp','style');
$body = $this-> replace_links($body);
$blocked_tags = array();
foreach($tag_list as $index => $tag) {
$new_body = eregi_replace("<$tag", "", $new_body);
}
// Malicious Code Remove
$dirtyCodePattern = "/(<([\w]+)([^>]*)on(mouse(move|over|down|up)|load|blur|change|click|dblclick|focus|key(down|up|press)|select)=[\"'][^>\"']*[\"']([^>]*)>)(.*)(<\/\\2>)?/isU";
preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
foreach($rest[0] as $i => $val)
if (!(preg_match("/window\.open/i",$rest[1][$i]) && strtoupper($rest[4][$i]) == "CLICK" )) //Calendar events
$body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
return "".$body;
}
function replace_links($body) {
$matches = array();
// Verify exception.
@preg_match("/)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[:\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\:\/\w.\-~&=?%;@+]*))/i';
$replacement = '$1';
return preg_replace($pattern, $replacement, $body);
// Original
//return preg_replace('/(?<=[\s|(
)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\/\w.\-~&=?%;@+]*))/i', 'http$3://$4$5', $body);
}
function get_signature($msg, $msg_number, $msg_folder)
{
foreach ($msg->file_type[$msg_number] as $index => $file_type)
{
$file_type = strtolower($file_type);
if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
{
if ($file_type == 'application/x-pkcs7-signature' || $file_type == 'application/pkcs7-signature')
{
$export_mail = new ExportEml();
$params['folder'] = $msg_folder;
$params['msgs_to_export'] = $msg_number;
$tempDir = ini_get("session.save_path");
$cert_file = $tempDir."/certificate_".base_convert(microtime(), 10, 36).".crt";
$result = openssl_pkcs7_verify($export_mail->export_msg($params),PKCS7_NOVERIFY,$cert_file);
if (file_exists($cert_file))
{
$handle = fopen ($cert_file,"r");
$pemout = fread($handle,filesize($cert_file));
fclose($handle);
$cert=openssl_x509_parse($pemout);
$temp = "\\nSigned by: ".$cert[subject][CN];
$temp .= "\\nEmail Address: ".$cert[subject][emailAddress];
$temp .= "\\nCertificate issued by: ".$cert[issuer][CN]."\\n";
}
/* Message verified */
if ($result === true)
$sign = $temp;
else
$sign = "void";
}
}
}
return $sign;
}
function get_thumbs($msg, $msg_number, $msg_folder)
{
$thumbs_array = array();
$i = 0;
foreach ($msg->file_type[$msg_number] as $index => $file_type)
{
$file_type = strtolower($file_type);
if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
$img = "pid[$msg_number][$index].">";
$href = "pid[$msg_number][$index]."','mywindow','width=700,height=600,scrollbars=yes');\">". $img ."";
$thumbs_array[] = $href;
}
$i++;
}
}
return $thumbs_array;
}
/*function delete_msg($params)
{
$folder = $params['folder'];
$msgs_to_delete = explode(",",$params['msgs_to_delete']);
$mbox_stream = $this->open_mbox($folder);
foreach ($msgs_to_delete as $msg_number){
imap_delete($mbox_stream, $msg_number, FT_UID);
}
imap_close($mbox_stream, CL_EXPUNGE);
return $params['msgs_to_delete'];
}*/
// Novo
function delete_msgs($params)
{
$folder = $params['folder'];
$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
$msgs_number = explode(",",$params['msgs_number']);
$border_ID = $params['border_ID'];
$return = array();
if ($params['get_previous_msg']){
$return['previous_msg'] = $this->get_info_previous_msg($params);
// Fix problem in unserialize function JS.
$return['previous_msg']['body'] = str_replace(array('{','}'), array('{','}'), $return['previous_msg']['body']);
}
//$mbox_stream = $this->open_mbox($folder);
$mbox_stream = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
foreach ($msgs_number as $msg_number)
{
if (imap_delete($mbox_stream, $msg_number, FT_UID));
$return['msgs_number'][] = $msg_number;
}
$return['folder'] = $folder;
$return['border_ID'] = $border_ID;
if($mbox_stream)
imap_close($mbox_stream, CL_EXPUNGE);
return $return;
}
function refresh($params)
{
include_once("class.imap_attachment.inc.php");
$imap_attachment = new imap_attachment();
$folder = $params['folder'];
$msg_range_begin = $params['msg_range_begin'];
$msg_range_end = $params['msg_range_end'];
$msgs_existent = $params['msgs_existent'];
$sort_box_type = $params['sort_box_type'];
$sort_box_reverse = $params['sort_box_reverse'];
$msgs_in_the_server = array();
$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
$sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
if(!count($sort_array_msg))
return array();
$num_msgs = (count($sort_array_msg) - imap_num_recent($this->mbox));
$msgs_in_the_client = explode(",", $msgs_existent);
for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= count($sort_array_msg))); $msg_range_begin++)
{
$msgs_in_the_server[] = $sort_array_msg[$msg_range_begin-1];
}
if ((count($msgs_in_the_server) < 1) && ($msg_range_begin != 0))
{
$range = $msg_range_end - $msg_range_begin;
$msg_range_begin = $msg_range_begin - $range;
$msg_range_end = $msg_range_end - $range;
for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= count($sort_array_msg))); $msg_range_begin++)
{
$msgs_in_the_server[] = $sort_array_msg[$msg_range_begin-1];
}
}
$msg_to_insert = array_diff($msgs_in_the_server, $msgs_in_the_client);
$msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
$msgs_to_exec = array();
if ((count($msg_to_insert)) && ($msgs_existent))
{
foreach($msg_to_insert as $index => $msg_number)
{
if ($msgs_in_the_server[$index+1])
{
//$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
$msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
}
else
{
//$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
$msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
}
}
ksort($msgs_to_exec);
}
elseif(!$msgs_existent)
{
foreach($msgs_in_the_server as $index => $msg_number)
{
$msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
}
}
$return = array();
$i = 0;
foreach($msgs_to_exec as $msg_number => $command)
{
/*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
* atributos do cabeçalho. Como eu preciso do atributo Importance
* para saber se o email é importante ou não, uso abaixo a função
* imap_fetchheader e busco o atributo importance nela para passar
* para as funções ajax. Isso faz com que eu acesse o cabeçalho
* duas vezes e de duas formas diferentes, mas em contrapartida, eu
* não preciso reimplementar o método utilizando o fetchheader.
* Como na atualização são poucas as mensagens que devem ser renderizadas,
* a perda em performance é insignificante.
*/
$flag = preg_match('/importance *: *(.*)\r/i',
imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
,$importance);
$return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
$header = $this->get_header($msg_number);
if (!is_object($header))
return false;
$return[$i]['msg_number'] = $msg_number;
$return[$i]['command'] = $command;
$return[$i]['msg_folder'] = $folder;
$return[$i]['Recent'] = $header->Recent;
$return[$i]['Unseen'] = $header->Unseen;
$return[$i]['Answered'] = $header->Answered;
$return[$i]['Deleted'] = $header->Deleted;
$return[$i]['Draft'] = $header->Draft;
$return[$i]['Flagged'] = $header->Flagged;
$date_msg = gmdate("d/m/Y",$header->udate);
if (gmdate("d/m/Y") == $date_msg)
$return[$i]['udate'] = gmdate("H:i",$header->udate);
else
$return[$i]['udate'] = $date_msg;
$from = $header->from;
$return[$i]['from'] = array();
$tmp = imap_mime_header_decode($from[0]->personal);
$return[$i]['from']['name'] = $tmp[0]->text;
$return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
//$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
if(!$return[$i]['from']['name'])
$return[$i]['from']['name'] = $return[$i]['from']['email'];
/*$toaddress = imap_mime_header_decode($header->toaddress);
$return[$i]['toaddress'] = '';
foreach ($toaddress as $tmp)
$return[$i]['toaddress'] .= $tmp->text;*/
$to = $header->to;
$return[$i]['to'] = array();
$tmp = imap_mime_header_decode($to[0]->personal);
$return[$i]['to']['name'] = $tmp[0]->text;
$return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
$return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
$return[$i]['subject'] = $this->decode_string($header->fetchsubject);
$return[$i]['Size'] = $header->Size;
$return[$i]['reply_toaddress'] = $header->reply_toaddress;
$return[$i]['attachment'] = array();
$return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
$i++;
}
$return['new_msgs'] = imap_num_recent($this->mbox);
$return['msgs_to_delete'] = $msg_to_delete;
if($this->mbox && is_resource($this->mbox))
imap_close($this->mbox);
return $return;
}
function get_folders_list($params = null)
{
$mbox_stream = $this->open_mbox();
$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
$folders_list = imap_getmailboxes($mbox_stream, $serverString, "*");
$folders_list = array_slice($folders_list,0,$this->foldersLimit);
$tmp = array();
$result = array();
if (is_array($folders_list)) {
reset($folders_list);
$i = 0;
while (list($key, $val) = each($folders_list)) {
$status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
$result[$i]['folder_unseen'] = $status->unseen;
//$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
$tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
$folder_id = $tmp_folder_id[1];
$result[$i]['folder_id'] = $folder_id;
$tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
$result[$i]['folder_name'] = array_pop($tmp_folder_parent);
$result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
if (is_numeric($result[$i]['folder_name'])) {
$this->ldap = new ldap_functions();
if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])){
$result[$i]['folder_name'] = $cn;
}
}
$tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
$result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
$result[$i]['folder_hasChildren'] = 1;
else
$result[$i]['folder_hasChildren'] = 0;
$i++;
}
}
foreach ($result as $folder_info)
{
$array_tmp[] = $folder_info['folder_id'];
}
natcasesort($array_tmp);
foreach ($array_tmp as $key => $folder_id)
{
$result2[] = $result[$key];
}
$current_folder = "INBOX";
if($params && $params['folder'])
$current_folder = $params['folder'];
return array_merge($result2, $this->get_quota(array(folder_id => $current_folder)));
}
function create_mailbox($arr)
{
$namebox = $arr['newp'];
$mbox_stream = $this->open_mbox();
$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
$namebox = mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
$result = "Ok";
if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
{
$result = implode("
\n", imap_errors());
}
if($mbox_stream)
imap_close($mbox_stream);
return $result;
}
function create_extra_mailbox($arr)
{
$nameboxs = explode(";",$arr['nw_folders']);
$result = "";
$mbox_stream = $this->open_mbox();
$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
foreach($nameboxs as $key=>$tmp){
if($tmp != ""){
if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
$result = implode("
\n", imap_errors());
if($mbox_stream)
imap_close($mbox_stream);
return $result;
}
}
}
if($mbox_stream)
imap_close($mbox_stream);
return true;
}
function delete_mailbox($arr)
{
$namebox = $arr['del_past'];
$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
$mbox_stream = $this->open_mbox();
//$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
$result = "Ok";
$namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
{
$result = implode("
\n", imap_errors());
}
if($mbox_stream)
imap_close($mbox_stream);
return $result;
}
function ren_mailbox($arr)
{
$namebox = $arr['current'];
$new_box = $arr['rename'];
$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
$mbox_stream = $this->open_mbox();
//$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
$result = "Ok";
$namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
$new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
{
$result = imap_errors();
}
if($mbox_stream)
imap_close($mbox_stream);
return $result;
}
function get_num_msgs($params)
{
$folder = $params['folder'];
if(!$this->mbox || !is_resource($this->mbox)) {
$this->mbox = $this->open_mbox($folder);
if(!$this->mbox || !is_resource($this->mbox))
return imap_last_error();
}
$num_msgs = imap_num_msg($this->mbox);
if($this->mbox && is_resource($this->mbox))
imap_close($this->mbox);
return $num_msgs;
}
function send_mail($params)
{
include_once("class.phpmailer.php");
$mail = new PHPMailer();
include_once("class.db_functions.inc.php");
$db = new db_functions();
$fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
##
# @AUTHOR Rodrigo Souza dos Santos
# @DATE 2008/09/17
# @BRIEF Checks if the user has permission to send an email with the email address used.
##
if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
{
$deny = true;
foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
$deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
if ( $deny )
return "The server denied your request to send a mail, you cannot use this mail address.";
}
//new_message_to backs to mailto: pattern
$params['body'] = eregi_replace("]+)'\)\">[^>]+","\\1",$params['body']);
$toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
$ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
$ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
$subject = $params['input_subject'];
$msg_uid = $params['msg_id'];
$return_receipt = $params['input_return_receipt'];
$is_important = $params['input_important_message'];
$body = $params['body'];
//echo "";
$attachments = $params['FILES'];
$forwarding_attachments = $params['forwarding_attachments'];
$local_attachments = $params['local_attachments'];
$folder =$params['folder'];
$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
$folder_name = $params['folder_name'];
// Fix problem with cyrus delimiter changes.
// Dots in names: enabled/disabled.
$folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
$folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
// End Fix.
if ($folder != 'null'){
$mail->SaveMessageInFolder = $folder;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
$mail->SMTPDebug = false;
$mail->IsSMTP();
$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
$mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
if($fromaddress){
$mail->Sender = $mail->From;
$mail->SenderName = $mail->FromName;
$mail->FromName = $fromaddress[0];
$mail->From = $fromaddress[1];
}
$this->add_recipients("to", $toaddress, &$mail);
$this->add_recipients("cc", $ccaddress, &$mail);
$this->add_recipients("cco", $ccoaddress, &$mail);
$mail->Subject = $subject;
$mail->IsHTML(true);
$mail->Body = $params['body'];
////////////////////////////////////////////////////////////////////////////////////////////////////
// Build CID for embedded Images!!!
$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
$cid_imgs = '';
$name_cid_files = array();
preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
$cid_array = array();
foreach($cid_imgs[6] as $j => $val){
if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
{
$cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
}
$cid = $cid_array[$cid_imgs[4][$j].$val];
$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
{
$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
$fileName = "image_".($j).".jpg";
$fileCode = "base64";
$fileType = "image/jpg";
}
else
{
$attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
$file_description = unserialize(rawurldecode($attach_img));
foreach($file_description as $i => $descriptor){
$file_description[$i] = eregi_replace('\'*\'','',$descriptor);
}
$fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
$fileName = $file_description[2];
$fileCode = $file_description[4];
$fileType = $this->get_file_type($file_description[2]);
unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
}
$tempDir = ini_get("session.save_path");
$file = "cid_image_".base_convert(microtime(), 10, 36).".dat";
$f = fopen($tempDir.'/'.$file,"w");
fputs($f,$fileContent);
fclose($f);
if ($fileContent)
$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
//else
// return "Error loading image attachment content";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Build Uploading Attachments!!!
if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
{
$total_uploaded_size = 0;
$upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
foreach ($attachments as $attach)
{
$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name'])); // optional name
$total_uploaded_size = $total_uploaded_size + $attach['size'];
}
if( $total_uploaded_size > $upload_max_filesize)
return $this->parse_error("message file too big");
}
else if(($params['is_local_forward']=="1") && (count($local_attachments))) { //Caso seja forward de mensagens locais
$total_uploaded_size = 0;
$upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
foreach($local_attachments as $local_attachment) {
$file_description = unserialize(rawurldecode($local_attachment));
$tmp = array_values($file_description);
foreach($file_description as $i => $descriptor){
$tmp[$i] = eregi_replace('\'*\'','',$descriptor);
}
$mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2])); // optional name
$total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
}
if( $total_uploaded_size > $upload_max_filesize)
return 'false';
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Build Forwarding Attachments!!!
if (count($forwarding_attachments) > 0)
{
// Bug fixed for array_search function
if(count($name_cid_files) > 0) {
$name_cid_files[count($name_cid_files)] = $name_cid_files[0];
$name_cid_files[0] = null;
}
foreach($forwarding_attachments as $forwarding_attachment)
{
$file_description = unserialize(rawurldecode($forwarding_attachment));
$tmp = array_values($file_description);
foreach($file_description as $i => $descriptor){
$tmp[$i] = eregi_replace('\'*\'','',$descriptor);
}
$file_description = $tmp;
$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
$fileName = $file_description[2];
if(!array_search(trim($fileName),$name_cid_files)) {
$mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Important message
if($is_important)
$mail->isImportant();
////////////////////////////////////////////////////////////////////////////////////////////////////
// Disposition-Notification-To
if ($return_receipt)
$mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
////////////////////////////////////////////////////////////////////////////////////////////////////
$sent = $mail->Send();
if(!$sent)
{
return $this->parse_error($mail->ErrorInfo);
}
else
{
if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
{
$userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
$userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
$now = date("d/m/y H:i:s");
$addrs = $toaddress.$ccaddress.$ccoaddress;
$sent = trim($sent);
error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
}
if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
$contacts = new dynamic_contacts();
$new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
return array("success" => true, "new_contacts" => $new_contacts);
}
return array("success" => true);
}
}
function add_recipients($recipient_type, $full_address, $mail)
{
$parse_address = imap_rfc822_parse_adrlist($full_address, "");
foreach ($parse_address as $val)
{
//echo "";
if ($val->mailbox == "INVALID_ADDRESS")
continue;
if (empty($val->personal))
{
switch($recipient_type)
{
case "to":
$mail->AddAddress($val->mailbox."@".$val->host);
break;
case "cc":
$mail->AddCC($val->mailbox."@".$val->host);
break;
case "cco":
$mail->AddBCC($val->mailbox."@".$val->host);
break;
}
}
else
{
switch($recipient_type)
{
case "to":
$mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
break;
case "cc":
$mail->AddCC($val->mailbox."@".$val->host, $val->personal);
break;
case "cco":
$mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
break;
}
}
}
return true;
}
function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
{
$mbox_stream = $this->open_mbox($msg_folder);
$fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
if($encoding == 'base64')
# The function imap_base64 adds a new line
# at ASCII text, with CRLF line terminators.
# So is being exchanged for base64_decode.
#
#$fileContent = imap_base64($fileContent);
$fileContent = base64_decode($fileContent);
else if($encoding == 'quoted-printable')
$fileContent = quoted_printable_decode($fileContent);
return $fileContent;
}
function del_last_caracter($string)
{
$string = substr($string,0,(strlen($string) - 1));
return $string;
}
function del_last_two_caracters($string)
{
$string = substr($string,0,(strlen($string) - 2));
return $string;
}
function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type)
{
$sort = array();
$sort_uid = array();
$num_msgs = imap_num_msg($this->mbox);
for ($i=1; $i<=$num_msgs; $i++)
{
$header = $this->get_header(imap_uid($this->mbox,$i));
// List UNSEEN messages.
if($search_box_type == "UNSEEN" && (!trim($header->Recent) && !trim($header->Unseen))){
continue;
}
// List SEEN messages.
elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
continue;
}
// List ANSWERED messages.
elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
continue;
}
// List FLAGGED messages.
elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
continue;
}
if($sort_box_type=='SORTFROM') {
if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
$from = $header->to;
else
$from = $header->from;
$tmp = imap_mime_header_decode($from[0]->personal);
if ($tmp[0]->text != "")
$sort[$i] = $tmp[0]->text;
else
$sort[$i] = $from[0]->mailbox . "@" . $from[0]->host;
}
else if($sort_box_type=='SORTSUBJECT') {
$sort[$i] = $header->subject;
}
else if($sort_box_type=='SORTSIZE') {
$sort[$i] = $header->Size;
}
else {
$sort[$i] = $header->udate;
}
}
natcasesort($sort);
foreach($sort as $index => $header_msg)
{
$sort_uid[] = imap_uid($this->mbox, $index);
}
if ($sort_box_reverse)
$sort_uid = array_reverse($sort_uid);
return $sort_uid;
}
/**
* Deprecated
*
* Replaced for the method messages_sort
*/
function imap_sortfrom($sort_box_reverse, $search_box_type)
{
$sortfrom = array();
$sortfrom_uid = array();
$num_msgs = imap_num_msg($this->mbox);
for ($i=1; $i<=$num_msgs; $i++)
{
$header = $this->get_header(imap_uid($this->mbox,$i));
// List UNSEEN messages.
if($search_box_type == "UNSEEN" && (!trim($header->Recent) && !trim($header->Unseen))){
continue;
}
// List SEEN messages.
elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
continue;
}
// List ANSWERED messages.
elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
continue;
}
// List FLAGGED messages.
elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
continue;
}
if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
$from = $header->to;
else
$from = $header->from;
$tmp = imap_mime_header_decode($from[0]->personal);
if ($tmp[0]->text != "")
$sortfrom[$i] = $tmp[0]->text;
else
$sortfrom[$i] = $from[0]->mailbox . "@" . $from[0]->host;
}
natcasesort($sortfrom);
foreach($sortfrom as $index => $header_msg)
{
$sortfrom_uid[] = imap_uid($this->mbox, $index);
}
if ($sort_box_reverse)
$sortfrom_uid = array_reverse($sortfrom_uid);
return $sortfrom_uid;
}
function move_search_messages($params){
$params['selected_messages'] = urldecode($params['selected_messages']);
$params['new_folder'] = urldecode($params['new_folder']);
$params['new_folder_name'] = urldecode($params['new_folder_name']);
$sel_msgs = explode(",", $params['selected_messages']);
@reset($sel_msgs);
$sorted_msgs = array();
foreach($sel_msgs as $idx => $sel_msg) {
$sel_msg = explode(";", $sel_msg);
if(array_key_exists($sel_msg[0], $sorted_msgs)){
$sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
}
else {
$sorted_msgs[$sel_msg[0]] = $sel_msg[1];
}
}
@ksort($sorted_msgs);
$last_return = false;
foreach($sorted_msgs as $folder => $msgs_number) {
$params['msgs_number'] = $msgs_number;
$params['folder'] = $folder;
if($params['new_folder'] && $folder != $params['new_folder']){
$last_return = $this -> move_messages($params);
}
elseif(!$params['new_folder'] || $params['delete'] ){
$last_return = $this -> delete_msgs($params);
$last_return['deleted'] = true;
}
}
return $last_return;
}
function move_messages($params)
{
$folder = $params['folder'];
$mbox_stream = $this->open_mbox($folder);
$newmailbox = ($params['new_folder']);
$newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
$new_folder_name = $params['new_folder_name'];
$msgs_number = $params['msgs_number'];
$return = array('msgs_number' => $msgs_number,
'folder' => $folder,
'new_folder_name' => $new_folder_name,
'border_ID' => $params['border_ID'],
'status' => true); //Status foi adicionado para validar as permissoes ACL
//Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
if (substr($folder,0,4) == 'user'){
$acl = $this->getacltouser($folder);
/*
* l - lookup (mailbox is visible to LIST/LSUB commands)
* r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
* s - keep seen/unseen information across sessions (STORE SEEN flag)
* w - write (STORE flags other than SEEN and DELETED)
* i - insert (perform APPEND, COPY into mailbox)
* p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
* c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
* d - delete (STORE DELETED flag, perform EXPUNGE)
* a - administer (perform SETACL)
*/
if (strpos($acl, "d") === false){
$return['status'] = false;
return $return;
}
}
//Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
if (substr($new_folder_name,0,4) == 'user'){
$this->ldap = new ldap_functions();
$tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
$return['new_folder_name'] = array_pop($tmp_folder_name);
if (is_numeric($return['new_folder_name']))
if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
$return['new_folder_name'] = $cn;
}
// Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
{
$return['previous_msg'] = $this->get_info_previous_msg($params);
// Fix problem in unserialize function JS.
$return['previous_msg']['body'] = str_replace(array('{','}'), array('{','}'), $return['previous_msg']['body']);
}
$mbox_stream = $this->open_mbox($folder);
if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
imap_expunge($mbox_stream);
if($mbox_stream)
imap_close($mbox_stream);
return $return;
}else {
if(strstr(imap_last_error(),'Over quota')) {
$accountID = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
$pass = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
$userID = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
$server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
$mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}INBOX", $accountID, $pass) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
if(!$mbox)
return imap_last_error();
$quota = imap_get_quotaroot($mbox_stream, "INBOX");
if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
if($mbox_stream)
imap_close($mbox_stream);
if($mbox)
imap_close($mbox);
return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
}
if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
imap_expunge($mbox_stream);
if($mbox_stream)
imap_close($mbox_stream);
// return to original quota limit.
if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
if($mbox)
imap_close($mbox);
return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
}
return $return;
}
else {
if($mbox_stream)
imap_close($mbox_stream);
if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
if($mbox)
imap_close($mbox);
return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
}
return imap_last_error();
}
}
else {
if($mbox_stream)
imap_close($mbox_stream);
return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
}
}
}
function save_msg($params)
{
include_once("class.phpmailer.php");
$mail = new PHPMailer();
include_once("class.db_functions.inc.php");
$toaddress = $params['input_to'];
$ccaddress = $params['input_cc'];
$subject = $params['input_subject'];
$msg_uid = $params['msg_id'];
$body = $params['body'];
$body = str_replace("%nbsp;"," ",$params['body']);
$body = preg_replace("/\n/"," ",$body);
$body = preg_replace("/\r/","",$body);
$forwarding_attachments = $params['forwarding_attachments'];
$attachments = $params['FILES'];
$return_files = $params['FILES'];
$folder = $params['folder'];
$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
// Fix problem with cyrus delimiter changes.
// Dots in names: enabled/disabled.
$folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
$folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
// End Fix.
$mail->SaveMessageInFolder = $folder;
$mail->SMTPDebug = false;
$mail->IsSMTP();
$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
$mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
$mail->Sender = $mail->From;
$mail->SenderName = $mail->FromName;
$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
$this->add_recipients("to", $toaddress, &$mail);
$this->add_recipients("cc", $ccaddress, &$mail);
$mail->Subject = $subject;
$mail->IsHTML(true);
$mail->Body = $body;
// Build CID for embedded Images!!!
$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
$cid_imgs = '';
$name_cid_files = array();
preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
$cid_array = array();
foreach($cid_imgs[6] as $j => $val){
if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
{
$cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
}
$cid = $cid_array[$cid_imgs[4][$j].$val];
$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
{
$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
//prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
$fileName = "image_".($j).".jpg";
$fileCode = "base64";
$fileType = "image/jpg";
$file_attached[0] = $cid_imgs[2][$j];
$file_attached[1] = $cid_imgs[4][$j];
$file_attached[2] = $fileName;
$file_attached[3] = $cid_imgs[6][$j];
$file_attached[4] = 'base64';
$file_attached[5] = strlen($fileContent); //Size of file
$return_forward[] = $file_attached;
}
else
{
$attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
$file_description = unserialize(rawurldecode($attach_img));
foreach($file_description as $i => $descriptor){
$file_description[$i] = eregi_replace('\'*\'','',$descriptor);
}
$fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
$fileName = $file_description[2];
$fileCode = $file_description[4];
$fileType = $this->get_file_type($file_description[2]);
unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
if (!empty($file_description))
{
$file_description[5] = strlen($fileContent); //Size of file
$return_forward[] = $file_description;
}
}
$tempDir = ini_get("session.save_path");
$file = "cid_image_".base_convert(microtime(), 10, 36).".dat";
$f = fopen($tempDir.'/'.$file,"w");
fputs($f,$fileContent);
fclose($f);
if ($fileContent)
$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
//else
// return "Error loading image attachment content";
}
// Build Forwarding Attachments!!!
if (count($forwarding_attachments) > 0)
{
foreach($forwarding_attachments as $forwarding_attachment)
{
$file_description = unserialize(rawurldecode($forwarding_attachment));
$tmp = array_values($file_description);
foreach($file_description as $i => $descriptor){
$tmp[$i] = eregi_replace('\'*\'','',$descriptor);
}
$file_description = $tmp;
$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
$fileName = $file_description[2];
$file_description[5] = strlen($fileContent); //Size of file
$return_forward[] = $file_description;
$mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
}
}
if ((count($return_forward) > 0) && (count($return_files) > 0))
$return_files = array_merge_recursive($return_forward,$return_files);
else
if (count($return_files) < 1)
$return_files = $return_forward;
// Build Uploading Attachments!!!
if (count($attachments))
foreach ($attachments as $attach)
$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name'])); // optional name
if(!empty($mail->AltBody))
$mail->ContentType = "multipart/alternative";
$mail->error_count = 0; // reset errors
$mail->SetMessageType();
$header = $mail->CreateHeader();
$body = $mail->CreateBody();
if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
{
$imap_options = '/tls/novalidate-cert';
}
else
{
$imap_options = '/notls/novalidate-cert';
}
$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
$imap_port = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
$mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
$new_header = str_replace("\n", "\r\n", $header);
$new_body = str_replace("\n", "\r\n", $body);
$return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
$status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
$return['msg_no'] = $status->uidnext - 1;
$return['folder_id'] = $folder;
if($mbox_stream)
imap_close($mbox_stream);
if (is_array($return_files))
foreach ($return_files as $index => $_attachment) {
if (array_key_exists("name",$_attachment)){
unset($return_files[$index]);
$return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
}
else
{
unset($return_files[$index]);
$return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
}
}
$return['files'] = serialize($return_files);
$return["subject"] = $subject;
if (!$return['append'])
$return['append'] = imap_last_error();
return $return;
}
function set_messages_flag($params)
{
$folder = $params['folder'];
$msgs_to_set = $params['msgs_to_set'];
$flag = $params['flag'];
$return = array();
$return["msgs_to_set"] = $msgs_to_set;
$return["flag"] = $flag;
if(!$this->mbox && !is_resource($this->mbox))
$this->mbox = $this->open_mbox($folder);
if ($flag == "unseen")
$return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
elseif ($flag == "seen")
$return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
elseif ($flag == "answered"){
$return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
}
elseif ($flag == "forwarded")
$return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
elseif ($flag == "flagged")
$return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
elseif ($flag == "unflagged") {
$flag_importance = false;
$msgs_number = explode(",",$msgs_to_set);
$unflagged_msgs = "";
foreach($msgs_number as $msg_number) {
preg_match('/importance *: *(.*)\r/i',
imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
,$importance);
if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
$flag_importance=true;
}
else {
$unflagged_msgs.=$msg_number.",";
}
}
if($unflagged_msgs!="") {
imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
$return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
}
else {
$return["msgs_unflageds"] = false;
}
if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
$return["status"] = false;
$return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
}
else {
$return["status"] = true;
}
}
if($this->mbox && is_resource($this->mbox))
imap_close($this->mbox);
return $return;
}
function get_file_type($file_name)
{
$file_name = strtolower($file_name);
$strFileType = strrev(substr(strrev($file_name),0,4));
if ($strFileType == ".asf")
return "video/x-ms-asf";
if ($strFileType == ".avi")
return "video/avi";
if ($strFileType == ".doc")
return "application/msword";
if ($strFileType == ".zip")
return "application/zip";
if ($strFileType == ".xls")
return "application/vnd.ms-excel";
if ($strFileType == ".gif")
return "image/gif";
if ($strFileType == ".jpg" || $strFileType == "jpeg")
return "image/jpeg";
if ($strFileType == ".png")
return "image/png";
if ($strFileType == ".wav")
return "audio/wav";
if ($strFileType == ".mp3")
return "audio/mpeg3";
if ($strFileType == ".mpg" || $strFileType == "mpeg")
return "video/mpeg";
if ($strFileType == ".rtf")
return "application/rtf";
if ($strFileType == ".htm" || $strFileType == "html")
return "text/html";
if ($strFileType == ".xml")
return "text/xml";
if ($strFileType == ".xsl")
return "text/xsl";
if ($strFileType == ".css")
return "text/css";
if ($strFileType == ".php")
return "text/php";
if ($strFileType == ".asp")
return "text/asp";
if ($strFileType == ".pdf")
return "application/pdf";
if ($strFileType == ".txt")
return "text/plain";
if ($strFileType == ".wmv")
return "video/x-ms-wmv";
if ($strFileType == ".sxc")
return "application/vnd.sun.xml.calc";
if ($strFileType == ".stc")
return "application/vnd.sun.xml.calc.template";
if ($strFileType == ".sxd")
return "application/vnd.sun.xml.draw";
if ($strFileType == ".std")
return "application/vnd.sun.xml.draw.template";
if ($strFileType == ".sxi")
return "application/vnd.sun.xml.impress";
if ($strFileType == ".sti")
return "application/vnd.sun.xml.impress.template";
if ($strFileType == ".sxm")
return "application/vnd.sun.xml.math";
if ($strFileType == ".sxw")
return "application/vnd.sun.xml.writer";
if ($strFileType == ".sxq")
return "application/vnd.sun.xml.writer.global";
if ($strFileType == ".stw")
return "application/vnd.sun.xml.writer.template";
return "application/octet-stream";
}
function htmlspecialchars_encode($str)
{
return str_replace( array('&', '"','\'','<','>','{','}'), array('&','"',''','<','>','{','}'), $str);
}
function htmlspecialchars_decode($str)
{
return str_replace( array('&','"',''','<','>','{','}'), array('&', '"','\'','<','>','{','}'), $str);
}
function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse){
if(!$this->mbox || !is_resource($this->mbox)){
$this->mbox = $this->open_mbox($folder);
}
return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type);
/*switch($sort_box_type){
case 'SORTFROM':
return $this->imap_sortfrom($sort_box_reverse, $search_box_type);
case 'SORTSUBJECT':
return imap_sort($this->mbox, SORTSUBJECT, $sort_box_reverse, SE_UID, $search_box_type);
case 'SORTSIZE':
return imap_sort($this->mbox, SORTSIZE, $sort_box_reverse, SE_UID, $search_box_type);
default:
return imap_sort($this->mbox, SORTARRIVAL, $sort_box_reverse, SE_UID, $search_box_type);
}*/
}
function get_info_next_msg($params)
{
$msg_number = $params['msg_number'];
$folder = $params['msg_folder'];
$sort_box_type = $params['sort_box_type'];
$sort_box_reverse = $params['sort_box_reverse'];
$reuse_border = $params['reuse_border'];
$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
$sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
$success = false;
if (is_array($sort_array_msg))
{
foreach ($sort_array_msg as $i => $value){
if ($value == $msg_number)
{
$success = true;
break;
}
}
}
if (! $success || $i >= sizeof($sort_array_msg)-1)
{
$params['status'] = 'false';
$params['command_to_exec'] = "delete_border('". $reuse_border ."');";
return $params;
}
$params = array();
$params['msg_number'] = $sort_array_msg[($i+1)];
$params['msg_folder'] = $folder;
$return = $this->get_info_msg($params);
$return["reuse_border"] = $reuse_border;
return $return;
}
function get_info_previous_msg($params)
{
$msg_number = $params['msgs_number'];
$folder = $params['folder'];
$sort_box_type = $params['sort_box_type'];
$sort_box_reverse = $params['sort_box_reverse'];
$reuse_border = $params['reuse_border'];
$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
$sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
$success = false;
if (is_array($sort_array_msg))
{
foreach ($sort_array_msg as $i => $value){
if ($value == $msg_number)
{
$success = true;
break;
}
}
}
if (! $success || $i == 0)
{
$params['status'] = 'false';
$params['command_to_exec'] = "delete_border('". $reuse_border ."');";
return $params;
}
$params = array();
$params['msg_number'] = $sort_array_msg[($i-1)];
$params['msg_folder'] = $folder;
$return = $this->get_info_msg($params);
$return["reuse_border"] = $reuse_border;
return $return;
}
// This function updates the values: quota, paging and new messages menu.
function get_menu_values($params){
$return_array = array();
$return_array = $this->get_quota($params);
$mbox_stream = $this->open_mbox($params['folder']);
$return_array['num_msgs'] = imap_num_msg($mbox_stream);
if($mbox_stream)
imap_close($mbox_stream);
return $return_array;
}
function get_quota($params){
// folder_id = user/{uid} for shared folders
if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
$array_folder = explode($this->imap_delimiter,$params['folder_id']);
$folder_id = "user".$this->imap_delimiter.$array_folder[1];
}
// folder_id = INBOX for inbox folders
else
$folder_id = "INBOX";
if(!$this->mbox)
$this->mbox = $this->open_mbox();
$quota = imap_get_quotaroot($this->mbox, $folder_id);
if($this->mbox && is_resource($this->mbox))
imap_close($this->mbox);
if (!$quota){
return array(
'quota_percent' => 0,
'quota_used' => 0,
'quota_limit' => 0
);
}
if(count($quota) && $quota['limit']) {
$quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
$quota_used = (($quota['usage']/1024)* 100 + .5 )* .01;
if($quota_used >= $quota_limit)
{
$quotaPercent = 100;
}
else
{
$quotaPercent = ($quota_used / $quota_limit)*100;
$quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
}
return array(
'quota_percent' => floor($quotaPercent),
'quota_used' => floor($quota_used),
'quota_limit' => floor($quota_limit)
);
}
else
return array();
}
function send_notification($params){
require_once("class.phpmailer.php");
$mail = new PHPMailer();
$toaddress = $params['notificationto'];
$subject = 'Confirmação de leitura: ' . $params['subject'];
$body = 'Sua mensagem: ' . $params['subject'] . '
';
$body .= 'foi lida por: ' . $_SESSION['phpgw_info']['expressomail']['user']['fullname'] . ' <' . $_SESSION['phpgw_info']['expressomail']['user']['email'] . '> em ' . date("d/m/Y H:i");
$mail->SMTPDebug = false;
$mail->IsSMTP();
$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
$mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
$mail->AddAddress($toaddress);
$mail->Subject = $this->htmlspecialchars_decode($subject);
$mail->IsHTML(true);
$mail->Body = $body;
if(!$mail->Send()){
return $mail->ErrorInfo;
}
else
return true;
}
function empty_trash()
{
$folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
$mbox_stream = $this->open_mbox($folder);
$return = imap_delete($mbox_stream,'1:*');
if($mbox_stream)
imap_close($mbox_stream, CL_EXPUNGE);
return $return;
}
function search($params)
{
include("class.imap_attachment.inc.php");
$imap_attachment = new imap_attachment();
$criteria = $params['criteria'];
$return = array();
$folders = $this->get_folders_list();
$j = 0;
foreach($folders as $folder)
{
$mbox_stream = $this->open_mbox($folder);
$messages = imap_search($mbox_stream, $criteria, SE_UID);
if ($messages == '')
continue;
$i = 0;
$return[$j] = array();
$return[$j]['folder_name'] = $folder['name'];
foreach($messages as $msg_number)
{
$header = $this->get_header($msg_number);
if (!is_object($header))
return false;
$return[$j][$i]['msg_folder'] = $folder['name'];
$return[$j][$i]['msg_number'] = $msg_number;
$return[$j][$i]['Recent'] = $header->Recent;
$return[$j][$i]['Unseen'] = $header->Unseen;
$return[$j][$i]['Answered'] = $header->Answered;
$return[$j][$i]['Deleted'] = $header->Deleted;
$return[$j][$i]['Draft'] = $header->Draft;
$return[$j][$i]['Flagged'] = $header->Flagged;
$date_msg = gmdate("d/m/Y",$header->udate);
if (gmdate("d/m/Y") == $date_msg)
$return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
else
$return[$j][$i]['udate'] = $date_msg;
$fromaddress = imap_mime_header_decode($header->fromaddress);
$return[$j][$i]['fromaddress'] = '';
foreach ($fromaddress as $tmp)
$return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
$from = $header->from;
$return[$j][$i]['from'] = array();
$tmp = imap_mime_header_decode($from[0]->personal);
$return[$j][$i]['from']['name'] = $tmp[0]->text;
$return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
$return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
$to = $header->to;
$return[$j][$i]['to'] = array();
$tmp = imap_mime_header_decode($to[0]->personal);
$return[$j][$i]['to']['name'] = $tmp[0]->text;
$return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
$return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
$subject = imap_mime_header_decode($header->fetchsubject);
$return[$j][$i]['subject'] = '';
foreach ($subject as $tmp)
$return[$j][$i]['subject'] .= $tmp->text;
$return[$j][$i]['Size'] = $header->Size;
$return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
$return[$j][$i]['attachment'] = array();
$return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
$i++;
}
$j++;
if($mbox_stream)
imap_close($mbox_stream);
}
return $return;
}
function delete_and_show_previous_message($params)
{
$return = $this->get_info_previous_msg($params);
$params_tmp1 = array();
$params_tmp1['msgs_to_delete'] = $params['msg_number'];
$params_tmp1['folder'] = $params['msg_folder'];
$return_tmp1 = $this->delete_msg($params_tmp1);
$return['msg_number_deleted'] = $return_tmp1;
return $return;
}
function automatic_trash_cleanness($params)
{
$before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
$criteria = 'BEFORE "'.$before_date.'"';
$mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
$messages = imap_search($mbox_stream, $criteria, SE_UID);
if (is_array($messages)){
foreach ($messages as $msg_number){
imap_delete($mbox_stream, $msg_number, FT_UID);
}
}
if($mbox_stream)
imap_close($mbox_stream, CL_EXPUNGE);
return $messages;
}
// Fix the search problem with special characters!!!!
function remove_accents($string) {
return strtr($string,
"?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
"SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
}
function search_msg($params = ''){
$retorno = "";
$mbox_stream = "";
if(strpos($params['condition'],"#")===false) { //local messages
$search=false;
}
else {
$search = explode(",",$params['condition']);
}
if($search){
$search_criteria = '';
foreach($search as $tmp)
{
$tmp1 = explode("##",$tmp);
$name_box = $tmp1[0];
unset($filter);
foreach($tmp1 as $index => $criteria)
{
if ($index != 0 && strlen($criteria) != 0)
{
$filter_array = explode("<=>",rawurldecode($criteria));
$filter .= " ".$filter_array[0];
$filter .= '"'.$filter_array[1].'"';
}
}
$name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
$filter = $this->remove_accents($filter);
//Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
$folder_name = explode($this->imap_delimiter,$name_box);
if (is_numeric($folder_name[1])) {
$this->ldap = new ldap_functions();
if ($cn = $this->ldap->uid2cn($folder_name[1])) {
$folder_name[1] = $cn;
}
}
$folder_name = implode($this->imap_delimiter,$folder_name);
if(!is_resource($mbox_stream))
$mbox_stream = $this->open_mbox($name_box);
else
imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search
$all_criterias = array ("TO","SUBJECT","FROM","CC");
foreach($all_criterias as $criteria_fixed)
{
$_filter = $criteria_fixed . substr($filter,4);
$search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
if($search_criteria && count($search_criteria) < 50)
{
foreach($search_criteria as $new_search){
$m_token = trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--".$new_search."##"."\n");
if(!@strstr($retorno,$m_token))
$retorno .= $m_token;
}
}
else if(count($search_criteria) >= 50)
return "many results";
}
}
else {
$search_criteria = imap_search($mbox_stream, $filter, SE_UID);
if( is_array( $search_criteria) )
{
foreach($search_criteria as $new_search)
$retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
}
}
}
}
if($mbox_stream)
imap_close($mbox_stream);
return $retorno ? $retorno : "none";
}
function get_msg($uid_msg,$name_box, $mbox_stream )
{
$header = $this->get_header($uid_msg);
$flag = $header->Unseen.$header->Recent.$header->Flagged.$header->Draft;
$subject = $this->decode_string($header->fetchsubject);
$from = $header->from[0]->mailbox;
if($header->from[0]->personal != "")
$from = $header->from[0]->personal;
$ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size) ."--". $flag;
return $ret_msg;
}
function size_msg($size){
$var = floor($size/1024);
if($var >= 1){
return $var." kb";
}else{
return $size ." b";
}
}
function ob_array($the_object)
{
$the_array=array();
if(!is_scalar($the_object))
{
foreach($the_object as $id => $object)
{
if(is_scalar($object))
{
$the_array[$id]=$object;
}
else
{
$the_array[$id]=$this->ob_array($object);
}
}
return $the_array;
}
else
{
return $the_object;
}
}
function getacl()
{
$this->ldap = new ldap_functions();
$return = array();
$mbox_stream = $this->open_mbox();
$mbox_acl = imap_getacl($mbox_stream, 'INBOX');
$i = 0;
foreach ($mbox_acl as $user => $acl)
{
if ($user != $this->username)
{
$return[$i]['uid'] = $user;
$return[$i]['cn'] = $this->ldap->uid2cn($user);
}
$i++;
}
return $return;
}
function setacl($params)
{
$old_users = $this->getacl();
if (!count($old_users))
$old_users = array();
$tmp_array = array();
foreach ($old_users as $index => $user_info)
{
$tmp_array[$index] = $user_info['uid'];
}
$old_users = $tmp_array;
$users = unserialize($params['users']);
if (!count($users))
$users = array();
//$add_share = array_diff($users, $old_users);
$remove_share = array_diff($old_users, $users);
$mbox_stream = $this->open_mbox();
$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
$mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
/*if (count($add_share))
{
foreach ($add_share as $index=>$uid)
{
if (is_array($mailboxes_list))
{
foreach ($mailboxes_list as $key => $val)
{
$folder = str_replace($serverString, "", imap_utf7_decode($val->name));
imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
}
}
}
}*/
if (count($remove_share))
{
foreach ($remove_share as $index=>$uid)
{
if (is_array($mailboxes_list))
{
foreach ($mailboxes_list as $key => $val)
{
$folder = str_replace($serverString, "", imap_utf7_decode($val->name));
imap_setacl ($mbox_stream, $folder, "$uid", "");
}
}
}
}
return true;
}
function getaclfromuser($params)
{
$useracl = $params['user'];
$return = array();
$return[$useracl] = 'false';
$mbox_stream = $this->open_mbox();
$mbox_acl = imap_getacl($mbox_stream, 'INBOX');
foreach ($mbox_acl as $user => $acl)
{
if (($user != $this->username) && ($user == $useracl))
{
$return[$user] = $acl;
}
}
return $return;
}
function getacltouser($user)
{
$return = array();
$mbox_stream = $this->open_mbox();
//Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
//Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
//No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
if(substr($user,0,4) != 'user')
$mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
else
$mbox_acl = imap_getacl($mbox_stream, $user);
return $mbox_acl[$this->username];
}
function setaclfromuser($params)
{
$user = $params['user'];
$acl = $params['acl'];
$mbox_stream = $this->open_mbox();
$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
$mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
if (is_array($mailboxes_list))
{
foreach ($mailboxes_list as $key => $val)
{
$folder = str_replace($serverString, "", imap_utf7_encode($val->name));
$folder = str_replace("&-", "&", $folder);
if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
{
$return = imap_last_error();
}
}
}
if (isset($return))
return $return;
else
return true;
}
function download_attachment($msg,$msgno)
{
$array_parts_attachments = array();
$array_parts_attachments['names'] = '';
include_once("class.imap_attachment.inc.php");
$imap_attachment = new imap_attachment();
if (count($msg->fname[$msgno]) > 0)
{
$i = 0;
foreach ($msg->fname[$msgno] as $index=>$fname)
{
$array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
$array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($fname);
$array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
$array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
$array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
$i++;
}
}
$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
return $array_parts_attachments;
}
function spam($params)
{
$is_spam = $params['spam'];
$folder = $params['folder'];
$mbox_stream = $this->open_mbox($folder);
$msgs_number = explode(',',$params['msgs_number']);
foreach($msgs_number as $msg_number) {
$header = imap_fetchheader($mbox_stream, imap_msgno($mbox_stream, $msg_number));
$body = imap_body($mbox_stream, imap_msgno($mbox_stream, $msg_number));
$msg = $header . $body;
$email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
$username = $this->username;
strtok($email, '@');
$domain = strtok('@');
//Encontrar a assinatura do dspam no cabecalho
$v = explode("\r\n", $header);
foreach ($v as $linha){
if (eregi("^X-DSPAM-Signature", $linha)) {
$args = explode(" ",$linha);
$signature = $args[1];
}
}
// feed dspam
switch($is_spam){
case 'true': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
}
$tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##');
$cmd = str_replace($tags,array($email,$username,$domain,$signature),$cmd);
system($cmd);
}
imap_close($mbox_stream);
return false;
}
function get_header($msg_number){
$header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
if (!is_object($header))
return false;
// Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
$pdate = date_parse($header->MailDate);
$header->udate += $pdate['zone']*(-60);
if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
$flag = preg_match('/importance *: *(.*)\r/i',
imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
,$importance);
$header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
}
return $header;
}
}
?>