source: trunk/expressoMail1_2/inc/class.imap_functions.inc.php @ 605

Revision 605, 86.8 KB checked in by niltonneto, 15 years ago (diff)

Resolve #398

  • Property svn:eol-style set to native
  • Property svn:executable set to *
RevLine 
[2]1<?php
2include_once("class.functions.inc.php");
3include_once("class.ldap_functions.inc.php");
[91]4include_once("class.exporteml.inc.php");
5
[2]6class imap_functions
7{
8        var $public_functions = array
[449]9        (       
[2]10                'get_range_msgs'                                => True,
11                'get_info_msg'                                  => True,
12                'get_folders_list'                              => True
13        );
14
15        var $ldap;
16        var $mbox;
17        var $imap_port;
18        var $has_cid;
19        var $imap_options = '';
20        var $functions;
21
22        function imap_functions (){
23                $this->username           = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
24                $this->password           = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
25                $this->imap_server        = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
26                $this->imap_port          = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
27                $this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
[449]28                $this->functions          = new functions();           
[2]29                $this->has_cid = false;
[449]30               
[2]31                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
32                {
33                        $this->imap_options = '/tls/novalidate-cert';
34                }
35                else
36                {
37                        $this->imap_options = '/notls/novalidate-cert';
38                }
39        }
40        // BEGIN of functions.
41        function open_mbox($folder = False)
42        {
[51]43                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
[504]44                $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()))));
[2]45                return $this->mbox;
46         }
47
[504]48        function parse_error($error){
49                // This error is returned from Imap.
50                if(strstr($error,'Connection refused')) {
51                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
52                }
53                // This error is returned from Postfix.
54                elseif(strstr($error,'message file too big')) {
55                        return str_replace("%1", ini_get('upload_max_filesize'),$this->functions->getLang('The size of this message has exceeded  the limit (%1B).'));                 
56                }
57                // This condition verifies if SESSION is expired.
58                elseif(!count($_SESSION))                       
59                        return "nosession";
60
61                return $error;
62        }
63       
[2]64        function get_range_msgs2($params)
65        {
66                include("class.imap_attachment.inc.php");
67                $imap_attachment = new imap_attachment();
[53]68                $folder = $params['folder'];
[2]69                $msg_range_begin = $params['msg_range_begin'];
70                $msg_range_end = $params['msg_range_end'];
[449]71                $sort_box_type = $params['sort_box_type'];             
[53]72                $sort_box_reverse = $params['sort_box_reverse'];
[51]73                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[449]74                $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);                               
75               
[2]76                $return = array();
77                $i = 0;
[46]78                $num_msgs = (is_array($sort_array_msg) ? count($sort_array_msg) : 0);
[449]79                if($num_msgs) {
[46]80                        for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= $num_msgs)); $msg_range_begin++)
[2]81                {
82                        $msg_number = $sort_array_msg[$msg_range_begin-1];
83
[535]84                        $header = $this->get_header($msg_number);
[2]85                        if (!is_object($header))
[449]86                                return false;                   
87                       
[2]88                        $return[$i]['Recent'] = $header->Recent;
89                        $return[$i]['Unseen'] = $header->Unseen;
90                        if($header->Answered =='A' && $header->Draft == 'X'){
91                                $return[$i]['Forwarded'] = 'F';
92                        }
93                        else {
94                                $return[$i]['Answered'] = $header->Answered;
[449]95                                $return[$i]['Draft']    = $header->Draft;       
[2]96                        }
97                        $return[$i]['Deleted'] = $header->Deleted;
98                        $return[$i]['Flagged'] = $header->Flagged;
[449]99                       
[2]100                        $return[$i]['msg_number'] = $msg_number;
101                        //$return[$i]['msg_folder'] = $folder;
[449]102                       
[535]103                        $date_msg = gmdate("d/m/Y",$header->udate);
104                        if (gmdate("d/m/Y") == $date_msg)
105                                $return[$i]['udate'] = gmdate("H:i",$header->udate);
[2]106                        else
107                                $return[$i]['udate'] = $date_msg;
[449]108                       
[2]109                        $from = $header->from;
110                        $return[$i]['from'] = array();
111                        $tmp = imap_mime_header_decode($from[0]->personal);
[37]112                        $return[$i]['from']['name'] = $this->decode_string($tmp[0]->text);
[2]113                        $return[$i]['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
114                        if(!$return[$i]['from']['name'])
115                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
116                        $to = $header->to;
117                        $return[$i]['to'] = array();
118                        $tmp = imap_mime_header_decode($to[0]->personal);
[37]119                        $return[$i]['to']['name'] = $this->decode_string($this->decode_string($tmp[0]->text));
120                        $return[$i]['to']['email'] = $this->decode_string($to[0]->mailbox) . "@" . $to[0]->host;
121                        if(!$return[$i]['to']['name'])
122                                $return[$i]['to']['name'] = $return[$i]['to']['email'];
[2]123                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
124
125                        $return[$i]['Size'] = $header->Size;
[449]126                       
[2]127                        $return[$i]['attachment'] = array();
[449]128                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);                     
[2]129                        $i++;
130                }
[46]131                }
[449]132                $return['num_msgs'] = $num_msgs;               
133               
[2]134                return $return;
135        }
[449]136       
[2]137        function decode_string($string)
[449]138        {       
[2]139                if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
140                {
141                        $tmp = imap_mime_header_decode($string);
142                        foreach ($tmp as $tmp1)
143                                $return .= $this->htmlspecialchars_encode($tmp1->text);
144                        return $return;
145                }
146                else if (strpos(strtolower($string), '=?utf-8') !== false)
147                {
148                        $elements = imap_mime_header_decode($string);
149                        for($i = 0;$i < count($elements);$i++) {
150                                $charset = $elements[$i]->charset;
151                                $text =$elements[$i]->text;
152                                if(!strcasecmp($charset, "utf-8") ||
153                                !strcasecmp($charset, "utf-7")) {
154                                $text = iconv($charset, "ISO-8859-1", $text);
155                        }
156                                $decoded .= $this->htmlspecialchars_encode($text);
157                        }
158                        return $decoded;
159                }
160                else
161                        return $this->htmlspecialchars_encode($string);
162        }
[449]163       
[2]164        function get_info_msg($params)
165        {
[51]166                $return = array();
[2]167                $msg_number = $params['msg_number'];
[205]168                $msg_folder = $params['msg_folder'];
[449]169               
[411]170                if(!$this->mbox || !is_resource($this->mbox))
[449]171                        $this->mbox = $this->open_mbox($msg_folder);           
172               
[535]173                $header = $this->get_header($msg_number);
[205]174                if (!$header) {
[535]175                        $return['status_get_msg_info'] = "false";                       
[205]176                        return $return;
177                }
[535]178               
[51]179                $all_header = explode("\n", imap_fetchheader($this->mbox, $msg_number, FT_UID));
180                $return_get_body = $this->get_body_msg($msg_number, $msg_folder);
[449]181               
[603]182                //Substituição de links em email para abrir no próprio expresso
183                $body = ereg_replace("<a[^>]*href=[\'\"]mailto:([^\"\']+)[\'\"]>([^<]+)</a>","<a href=\"javascript:new_message_to('\\1')\">\\2</a>",$return_get_body['body']);
184                       
[591]185                $return['body']                 = $body;
[51]186                $return['attachments']  = $return_get_body['attachments'];
[91]187                $return['thumbs']               = $return_get_body['thumbs'];
188                $return['signature']    = $return_get_body['signature'];
[449]189               
[2]190                foreach($all_header as $line) {
191                        if (eregi("^Disposition-Notification-To", $line)) {
192                                eregi("^([^:]*): (.*)", $line, &$arg);
193                                $return['DispositionNotificationTo'] = $arg[2];
194                        }
195                }
196                $return['Recent']       = $header->Recent;
197                $return['Unseen']       = $header->Unseen;
[449]198                $return['Deleted']      = $header->Deleted;             
[2]199                $return['Flagged']      = $header->Flagged;
200
201                if($header->Answered =='A' && $header->Draft == 'X'){
202                        $return['Forwarded'] = 'F';
203                }
[535]204 
[2]205                else {
206                        $return['Answered']     = $header->Answered;
[449]207                        $return['Draft']        = $header->Draft;       
[2]208                }
209
210                $return['msg_number'] = $msg_number;
211                $return['msg_folder'] = $msg_folder;
[449]212       
[535]213                $date_msg = gmdate("d/m/Y",$header->udate);
[2]214                if (date("d/m/Y") == $date_msg)
[535]215                        $return['udate'] = gmdate("H:i",$header->udate);
[2]216                else
217                        $return['udate'] = $date_msg;
[449]218               
219                $return['msg_day'] = $date_msg;
[535]220                $return['msg_hour'] = gmdate("H:i",$header->udate);
[449]221               
[2]222                if (date("d/m/Y") == $date_msg) //no dia
223                {
[535]224                        $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
225                        $return['smalldate'] = gmdate("H:i",$header->udate);
[605]226
[535]227                        $timestamp_now = strtotime("now");                     
[605]228                        $timestamp_msg_time = $header->udate;
[535]229                        // $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ.
230                        // The variable $timestamp_diff is calculated without MailDate TZ.
231                        $pdate = date_parse($header->MailDate);
232                        $timestamp_diff = $timestamp_now - $timestamp_msg_time  + ($pdate['zone']*(-60));
[449]233                       
[2]234                        if (gmdate("H",$timestamp_diff) > 0)
235                        {
[197]236                                $return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
[2]237                        }
238                        else
239                        {
240                                if (gmdate("i",$timestamp_diff) == 0){
[197]241                                        $return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
[2]242                                }
243                                elseif (gmdate("i",$timestamp_diff) == 1){
[197]244                                        $return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
[2]245                                }
246                                else{
[197]247                                        $return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
[2]248                                }
249                        }
250                }
251                else{
[535]252                        $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
253                        $return['smalldate'] = gmdate("d/m/Y",$header->udate);
[2]254                }
[449]255               
[2]256                $from = $header->from;
257                $return['from'] = array();
258                $tmp = imap_mime_header_decode($from[0]->personal);
259                $return['from']['name'] = $this->decode_string($tmp[0]->text);
260                $return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
261                if ($return['from']['name'])
262                {
263                        if (substr($return['from']['name'], 0, 1) == '"')
264                                $return['from']['full'] = $return['from']['name'] . ' ' . '&lt;' . $return['from']['email'] . '&gt;';
265                        else
266                                $return['from']['full'] = '"' . $return['from']['name'] . '" ' . '&lt;' . $return['from']['email'] . '&gt;';
267                }
268                else
269                        $return['from']['full'] = $return['from']['email'];
[449]270               
[2]271                // Sender attribute
272                $sender = $header->sender;
273                $return['sender'] = array();
274                $tmp = imap_mime_header_decode($sender[0]->personal);
275                $return['sender']['name'] = $this->decode_string($tmp[0]->text);
276                $return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
277                if ($return['sender']['name'])
278                {
279                        if (substr($return['sender']['name'], 0, 1) == '"')
280                                $return['sender']['full'] = $return['sender']['name'] . ' ' . '&lt;' . $return['sender']['email'] . '&gt;';
281                        else
282                                $return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '&lt;' . $return['sender']['email'] . '&gt;';
283                }
284                else
285                        $return['sender']['full'] = $return['sender']['email'];
286
287                if($return['from']['full'] == $return['sender']['full'])
288                        $return['sender'] = null;
289                $to = $header->to;
290                $return['toaddress2'] = "";
291                if (!empty($to))
292                {
293                        foreach ($to as $tmp)
294                        {
295                                if (!empty($tmp->personal))
296                                {
297                                        $personal_tmp = imap_mime_header_decode($tmp->personal);
298                                        $return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
299                                        $return['toaddress2'] .= " ";
300                                        $return['toaddress2'] .= "&lt;";
[320]301                                        if ($tmp->host != 'unspecified-domain')
302                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
303                                        else
304                                                $return['toaddress2'] .= $tmp->mailbox;
[2]305                                        $return['toaddress2'] .= "&gt;";
306                                        $return['toaddress2'] .= ", ";
307                                }
308                                else
309                                {
[320]310                                        if ($tmp->host != 'unspecified-domain')
311                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
312                                        else
313                                                $return['toaddress2'] .= $tmp->mailbox;
[2]314                                        $return['toaddress2'] .= ", ";
315                                }
316                        }
317                        $return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
318                }
319                else
320                {
321                        $return['toaddress2'] = "&lt;Empty&gt;";
[449]322                }       
323               
[2]324                $cc = $header->cc;
325                $return['cc'] = "";
326                if (!empty($cc))
327                {
328                        foreach ($cc as $tmp_cc)
329                        {
330                                if (!empty($tmp_cc->personal))
331                                {
332                                        $personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
333                                        $return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
334                                        $return['cc'] .= " ";
335                                        $return['cc'] .= "&lt;";
336                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
337                                        $return['cc'] .= "&gt;";
338                                        $return['cc'] .= ", ";
339                                }
340                                else
341                                {
342                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
343                                        $return['cc'] .= ", ";
344                                }
345                        }
346                        $return['cc'] = $this->del_last_two_caracters($return['cc']);
347                }
348                else
349                {
350                        $return['cc'] = "";
[449]351                }       
352
353                ##
354                # @AUTHOR Rodrigo Souza dos Santos
355                # @DATE 2008/09/12
356                # @BRIEF Adding the BCC field.
357                ##
358                $bcc = $header->bcc;
359                $return['bcc'] = "";
360                if (!empty($bcc))
361                {
362                        foreach ($bcc as $tmp_bcc)
363                        {
364                                if (!empty($tmp_bcc->personal))
365                                {
366                                        $personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
367                                        $return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
368                                        $return['bcc'] .= " ";
369                                        $return['bcc'] .= "&lt;";
370                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
371                                        $return['bcc'] .= "&gt;";
372                                        $return['bcc'] .= ", ";
373                                }
374                                else
375                                {
376                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
377                                        $return['bcc'] .= ", ";
378                                }
379                        }
380                        $return['bcc'] = $this->del_last_two_caracters($return['bcc']);
[426]381                }
[449]382                else
383                {
384                        $return['bcc'] = "";
385                }       
[426]386
[2]387                $reply_to = $header->reply_to;
388                $return['reply_to'] = "";
389                if (is_object($reply_to[0]))
390                {
391                        if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
392                        {
393                                if (!empty($reply_to[0]->personal))
394                                {
395                                        $personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
[41]396                                        if(!empty($personal_reply_to[0]->text)) {
397                                                $return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
398                                                $return['reply_to'] .= " ";
399                                                $return['reply_to'] .= "&lt;";
400                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
401                                                $return['reply_to'] .= "&gt;";
402                                        }
403                                        else {
404                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
405                                        }
[2]406                                }
407                                else
408                                {
409                                        $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
410                                }
411                        }
412                }
413                $return['reply_to'] = $this->decode_string($return['reply_to']);
414                $return['subject'] = $this->decode_string($header->fetchsubject);
415                $return['Size'] = $header->Size;
[605]416                $return['reply_toaddress'] = $header->reply_toaddress;         
[2]417                return $return;
418        }
[449]419       
[2]420        function get_body_msg($msg_number, $msg_folder)
421        {
422                include_once("class.message_components.inc.php");
[51]423                $msg = &new message_components($this->mbox);
[2]424                $msg->fetch_structure($msg_number);
[51]425                $return = array();
[449]426                $return['attachments'] = $this-> download_attachment($msg,$msg_number);         
[51]427                if(!$this->has_cid)
[91]428                {
[178]429                        $return['thumbs']  = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
[91]430                        $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
[449]431                }                       
432               
[2]433                if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
434                {
435                        $attachment = array(); //No attachments
[449]436                       
[2]437                        $content = '';
438                        if (strtolower($msg->structure[$msg_number]->subtype) == "plain")
439                        {
[51]440                                $content .= nl2br($this->decodeBody((imap_body($this->mbox, $msg_number, FT_UID)), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]));
[2]441                        }
442                        else if (strtolower($msg->structure[$msg_number]->subtype) == "html")
443                        {
[51]444                                $content .= $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
[2]445                        }
446                }
[449]447                else
[2]448                { //Complicated message, multiple parts
449                        $html_body = '';
450                        $content = '';
451                        $has_multipart = true;
452                        $this->has_cid = false;
[449]453                       
[2]454                        if (strtolower($msg->structure[$msg_number]->subtype) == "related")
455                                $this->has_cid = true;
[449]456                       
[469]457                        if (strtolower($msg->structure[$msg_number]->subtype) == "alternative") {
458                                $show_only_html = false;
459                                foreach($msg->pid[$msg_number] as $values => $msg_part) {
[432]460                                        $file_type = strtolower($msg->file_type[$msg_number][$values]);
461                                        if($file_type == "text/html")
[469]462                                                $show_only_html = true;                 
[432]463                                }
[469]464                        }
[2]465                        else
466                                $show_only_html = false;
467
468                        foreach($msg->pid[$msg_number] as $values => $msg_part)
469                        {
[449]470                               
[2]471                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
472                                if($file_type == "message/rfc822")
473                                        $has_multipart = false;
[449]474       
[2]475                                if($file_type == "multipart/alternative")
476                                        $has_multipart = false;
[449]477       
478                                if(($file_type == "text/plain"
[2]479                                        || $file_type == "text/html")
480                                        && $file_type != 'attachment')
481                                {
482                                        if($file_type == "text/plain" && !$show_only_html && $has_multipart)
483                                        {
484                                                // if TXT file size > 100kb, then it will not expand.
485                                                if(!($file_type == "text/plain" && $msg->fsize[$msg_number][$values] > 102400)) {
[449]486                                                        $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])));                                                     
[2]487                                                }
488                                        }
489                                        // if HTML attachment file size > 300kb, then it will not expand.
[449]490                                        else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < 307200)
[2]491                                        {
[51]492                                                $content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
[2]493                                                $show_only_html = true;
494                                        }
495                                }
496                                else if($file_type == "message/delivery-status"){
497                                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
[449]498                                        $content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));                                           
[2]499
500                                }
[65]501                                else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
[449]502                                       
[2]503                                        include_once("class.imap_attachment.inc.php");
504                                        $att = new imap_attachment();
[51]505                                        $attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
[449]506                                        if($attachments['number_attachments'] > 0) {                                                                                           
[2]507                                                foreach($attachments ['attachment'] as $index => $attachment){
508                                                        if(strtolower($attachment['type']) == "delivery-status" ||
[449]509                                                                strtolower($attachment['type']) == "rfc822" ||                                                         
[65]510                                                                strtolower($attachment['type']) == "rfc822-headers" ||
[2]511                                                                strtolower($attachment['type']) == "plain"
512                                                        ){
[449]513                                                                $obj = imap_rfc822_parse_headers(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values]);                                   
514                                                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";                                   
[2]515                                                                $content .= "<br><table  style='margin:2px;border:1px solid black;background:#EAEAEA'>";
516                                                                $content .= "<tr><td><b>".$this->functions->getLang("Subject").":</b></td><td>".$this->decode_string($obj->subject)."</td></tr>";
517                                                                $content .= "<tr><td><b>".$this->functions->getLang("From").":</b></td><td>".$this->decode_string($obj->from[0]->mailbox."@".$obj->from[0]->host)."</td></tr>";
518                                                                $content .= "<tr><td><b>".$this->functions->getLang("Date").":</b></td><td>".$obj->date."</td></tr>";
519                                                                $content .= "<tr><td><b>".$this->functions->getLang("TO").":</b></td><td>".$this->decode_string($obj->to[0]->mailbox."@".$obj->to[0]->host)."</td></tr>";
[449]520                                                                $content .= !$obj->cc ? "</table><br>" :"<tr><td><b>".$this->functions->getLang("CC").":</b></td><td>".$this->decode_string($obj->cc[0]->mailbox."@".$obj->cc[0]->host)."</td></tr></table><br>";                                                               
[2]521                                                                $ix_part =      strtolower($attachment['type']) == "delivery-status" ? 1 : 0;
[449]522                                                                $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]));                                                         
523                                                                break;                 
[2]524                                                        }
525                                                }
526                                        }
527                                }
528                        }
529                        if($file_type == "text/plain" && ($show_only_html &&  $msg_part == 1) ||  (!$show_only_html &&  $msg_part == 3)){
530                                if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" &&  $msg_part == 1)
[51]531                                        $content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
[25]532                                else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
[449]533                                        $content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));                         
[2]534                        }
[449]535                }
[2]536                // Force message with flag Seen (imap_fetchbody not works correctly)
[449]537                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");                               
[2]538                $this->set_messages_flag($params);
[205]539                $content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
[2]540                $content = $this->replace_special_characters($content);
[51]541                $return['body'] = $content;
542                return $return;
[2]543        }
[449]544       
[2]545        function htmlfilter($body)
546        {
547                require_once('htmlfilter.inc');
[449]548               
[2]549                $tag_list = Array(
550                                false,
551                                'blink',
552                                'object',
553                                'meta',
554                                'html',
555                                'link',
556                                'frame',
557                                'iframe',
558                                'layer',
559                                'ilayer',
560                                'plaintext'
561                );
562
563                /**
564                * A very exclusive set:
565                */
566                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
567                $rm_tags_with_content = Array(
568                                'script',
569                                'style',
570                                'applet',
571                                'embed',
572                                'head',
573                                'frameset',
574                                'xml',
575                                'xmp'
576                );
577
578                $self_closing_tags =  Array(
579                                'img',
580                                'br',
581                                'hr',
582                                'input'
583                );
584
585                $force_tag_closing = true;
586
587                $rm_attnames = Array(
588                        '/.*/' =>
589                                Array(
590                                        '/target/i',
591                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
592                                        '/^dynsrc/i',
593                                        '/^datasrc/i',
594                                        '/^data.*/i',
595                                        '/^lowsrc/i'
596                                )
597                );
598
599                /**
600                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
601                 * some idea of what's going on here. :)
602                 */
603
604                $bad_attvals = Array(
605                '/.*/' =>
606                Array(
607                      '/.*/' =>
608                              Array(
609                                Array(
610                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
611                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
612                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
613                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
614                                      ),
615                            Array(
616                                              '\\1oddjob:\\2\\1',
617                                          //'\\1uucp:\\2\\1', -> doclinks notes
618                                      '\\1amaretto:\\2\\1',
619                                          '\\1round:\\2\\1'
620                                        )
[449]621                                    ),     
622         
[2]623                          '/^style/i' =>
624                              Array(
625                                        Array(
626                                          '/expression/i',
627                                              '/behaviou*r/i',
628                                          '/binding/i',
629                                              '/include-source/i',
630                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
631                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
632                                         ),
633                                        Array(
634                                          'idiocy',
635                                              'idiocy',
636                                          'idiocy',
637                                              'idiocy',
638                                          'url(\\1http://securityfocus.com/\\1)',
639                                          'url(\\1http://securityfocus.com/\\1)'
640                                         )
641                                )
642                          )
643                    );
644
645                $add_attr_to_tag = Array(
646                                '/^a$/i' => Array('target' => '"_new"')
647                );
[449]648       
649       
[2]650                $trusted_body = sanitize($body,
651                                $tag_list,
652                                $rm_tags_with_content,
653                                $self_closing_tags,
654                                $force_tag_closing,
655                                $rm_attnames,
656                                $bad_attvals,
657                                $add_attr_to_tag
658                );
[449]659       
[2]660            return $trusted_body;
661        }
[449]662       
[2]663        function decodeBody($body, $encoding, $charset=null)
664        {
665                /**
666                * replace e-mail by anchor.
667                */
668                // HTML Filter
[13]669                //$body = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=# onclick=\"javascript:new_message('new_by_message', '\\2@\\3')\">\\2@\\3</a>", $body);
[2]670        $body = str_replace("\r\n", "\n", $body);
671                if ($encoding == 'quoted-printable')
672            {
[449]673                       
[2]674                        for($i=0;$i<256;$i++) {
675                                $c1=dechex($i);
676                                if(strlen($c1)==1){$c1="0".$c1;}
677                                $c1="=".$c1;
678                                $myqprinta[]=$c1;
679                                $myqprintb[]=chr($i);
[449]680                        }               
[2]681                        $body = str_replace($myqprinta,$myqprintb,($body));
682                        $body = quoted_printable_decode($body);
[449]683                while (ereg("=\n", $body))
[2]684                {
685                        $body = ereg_replace ("=\n", '', $body);
686                }
687        }
[449]688        else if ($encoding == 'base64')
[2]689        {
690                $body = base64_decode($body);
691        }
[449]692        /*else if ($encoding == '7bit')
[12]693        {
[449]694                $body = quoted_printable_decode($body);                                         
[13]695        }*/
[2]696                // All other encodings are returned raw.
697                if (strtolower($charset) == "utf-8")
698                        return utf8_decode($body);
699        else
700                        return $body;
701        }
[449]702       
[205]703        function process_embedded_images($msg, $msgno, $body, $msg_folder)
[2]704        {
705                if (count($msg->inline_id[$msgno]) > 0)
706                {
707                        foreach ($msg->inline_id[$msgno] as $index => $cid)
708                        {
709                                $cid = eregi_replace("<", "", $cid);
710                                $cid = eregi_replace(">", "", $cid);
711                                $msg_part = $msg->pid[$msgno][$index];
712                                //$body = eregi_replace("alt=\"\"", "", $body);
713                                $body = eregi_replace("<br/>", "", $body);
714                                $body = str_replace("src=\"cid:".$cid."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
715                                $body = str_replace("src='cid:".$cid."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
716                                $body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
717                        }
718                }
[449]719               
[2]720                return $body;
721        }
[449]722       
[2]723        function replace_special_characters($body)
724        {
725                // Suspected TAGS!
[449]726                /*$tag_list = Array(   
[2]727                        'blink','object','meta',
728                        'html','link','frame',
729                        'iframe','layer','ilayer',
730                        'plaintext','script','style','img',
731                        'applet','embed','head',
732                        'frameset','xml','xmp');
733                */
734
[449]735                // Layout problem: Change html elements
736                // with absolute position to relate position, CASE INSENSITIVE.
[6]737                $body = @eregi_replace("POSITION: ABSOLUTE;","",$body);
738
[2]739                $tag_list = Array('head','blink','object','frame',
740                        'iframe','layer','ilayer','plaintext','script',
[63]741                        'applet','embed','frameset','xml','xmp','style');
[2]742
743                $body = $this-> replace_links($body);
[449]744                $blocked_tags = array();               
[2]745                foreach($tag_list as $index => $tag) {
746                        $new_body = eregi_replace("<$tag", "<!--$tag", $body);
747                        if($body != $new_body) {
748                                $blocked_tags[] = $tag;
749                        }
750                        $body = eregi_replace("</$tag>", "</$tag-->", $new_body);
751                }
752
753                return  "<span>".$body;
754        }
755
[449]756        function replace_links($body) {                                 
757                $matches = array();
[2]758                // Verify exception.
[449]759                @preg_match("/<a href=\"notes:\/\/\//",$body,$matches);
[2]760                // It no has exception,then open the link in new window.
[449]761                if(count($matches))
762                        return $body;
763       
764                $pattern = '/(?<=[\s|(<br>)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[:\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\:\/\w.\-~&=?%;@+]*))/i';
765                $replacement = '<a href="http$3://$4$5" target="_blank">$1</a>';
766                return preg_replace($pattern, $replacement, $body);
767               
768                // Original
769                //return preg_replace('/(?<=[\s|(<br>)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\/\w.\-~&=?%;@+]*))/i', '<a href="http$3://$4$5" target="_blank">http$3://$4$5</a>', $body);
[2]770        }
771
[91]772        function get_signature($msg, $msg_number, $msg_folder)
[449]773        {
[91]774                foreach ($msg->file_type[$msg_number] as $index => $file_type)
775                {
776                        $file_type = strtolower($file_type);
[449]777                        if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
[91]778                        {
[449]779                                if ($file_type == 'application/x-pkcs7-signature')
[91]780                                {
781                                        $export_mail = new ExportEml();
782                                        $params['folder'] = $msg_folder;
783                                        $params['msgs_to_export'] = $msg_number;
[109]784                                    $tempDir = ini_get("session.save_path");
[449]785                                        $cert_file = $tempDir."/certificate_".base_convert(microtime(), 10, 36).".crt";                                 
[109]786                                        $result = openssl_pkcs7_verify($export_mail->export_msg($params),PKCS7_NOVERIFY,$cert_file);
787                                        if (file_exists($cert_file))
788                                        {
789                                                $handle = fopen ($cert_file,"r");
790                                                $pemout = fread($handle,filesize($cert_file));
791                                                fclose($handle);
792                                                $cert=openssl_x509_parse($pemout);
793                                                $temp = "\\nSigned by: ".$cert[subject][CN];
794                                                $temp .= "\\nEmail Address: ".$cert[subject][emailAddress];
795                                                $temp .= "\\nCertificate issued by: ".$cert[issuer][CN]."\\n";
796                                        }
[91]797                                    /* Message verified */
798                                    if ($result === true)
[109]799                                            $sign = $temp;
[91]800                                     else
801                                            $sign = "void";
802                                }
803                        }
804                }
[449]805                return $sign;   
[91]806        }
807
[51]808        function get_thumbs($msg, $msg_number, $msg_folder)
[2]809        {
810                $thumbs_array = array();
811                $i = 0;
812        foreach ($msg->file_type[$msg_number] as $index => $file_type)
813        {
814                $file_type = strtolower($file_type);
815                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
816                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
817                                $img = "<IMG id='".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' style='border:2px solid #fde7bc;padding:5px' title='".$this->functions->getLang("Click here do view (+)")."'src=./inc/show_thumbs.php?file_type=".$file_type."&msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index].">";
818                                $href = "<a onMouseDown='save_image(event,this)' href='#".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' onClick=\"window.open('./inc/show_img.php?msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index]."','mywindow','width=700,height=600,scrollbars=yes');\">". $img ."</a>";
819                                        $thumbs_array[] = $href;
820                        }
821                        $i++;
822                }
823        }
824        return $thumbs_array;
825        }
[449]826               
[2]827        /*function delete_msg($params)
828        {
829                $folder = $params['folder'];
830                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
[449]831               
[2]832                $mbox_stream = $this->open_mbox($folder);
[449]833               
[2]834                foreach ($msgs_to_delete as $msg_number){
835                        imap_delete($mbox_stream, $msg_number, FT_UID);
836                }
837                imap_close($mbox_stream, CL_EXPUNGE);
838                return $params['msgs_to_delete'];
839        }*/
840
841        // Novo
842        function delete_msgs($params)
843        {
[449]844               
[2]845                $folder = $params['folder'];
[51]846                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
[2]847                $msgs_number = explode(",",$params['msgs_number']);
848                $border_ID = $params['border_ID'];
[449]849               
[2]850                $return = array();
[449]851               
852                if ($params['get_previous_msg']){
[2]853                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]854                        // Fix problem in unserialize function JS.
855                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
856                }
[2]857
[504]858                //$mbox_stream = $this->open_mbox($folder);             
859                $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()))));
[449]860               
[2]861                foreach ($msgs_number as $msg_number)
862                {
863                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
864                                $return['msgs_number'][] = $msg_number;
865                }
[449]866               
[2]867                $return['folder'] = $folder;
868                $return['border_ID'] = $border_ID;
[449]869               
[51]870                if($mbox_stream)
871                        imap_close($mbox_stream, CL_EXPUNGE);
[2]872                return $return;
873        }
874
[449]875               
[2]876        function refresh($params)
877        {
878                include("class.imap_attachment.inc.php");
[449]879                $imap_attachment = new imap_attachment();               
[2]880                $folder = $params['folder'];
881                $msg_range_begin = $params['msg_range_begin'];
882                $msg_range_end = $params['msg_range_end'];
883                $msgs_existent = $params['msgs_existent'];
[449]884                $sort_box_type = $params['sort_box_type'];             
[2]885                $sort_box_reverse = $params['sort_box_reverse'];
886                $msgs_in_the_server = array();
[53]887                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
888                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
[51]889
890                if(!count($sort_array_msg))
891                        return array();
[449]892                       
[51]893                $num_msgs = (count($sort_array_msg) - imap_num_recent($this->mbox));
894                $msgs_in_the_client = explode(",", $msgs_existent);
895
[449]896               
[2]897                for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= count($sort_array_msg))); $msg_range_begin++)
898                {
899                        $msgs_in_the_server[] = $sort_array_msg[$msg_range_begin-1];
900                }
901                if ((count($msgs_in_the_server) < 1) && ($msg_range_begin != 0))
902                {
903                        $range = $msg_range_end - $msg_range_begin;
904                        $msg_range_begin = $msg_range_begin - $range;
905                        $msg_range_end = $msg_range_end - $range;
906                        for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= count($sort_array_msg))); $msg_range_begin++)
907                        {
908                                $msgs_in_the_server[] = $sort_array_msg[$msg_range_begin-1];
909                        }
910                }
[449]911               
[2]912                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
[271]913                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
[449]914               
[2]915                $msgs_to_exec = array();
916                if ((count($msg_to_insert)) && ($msgs_existent))
917                {
918                        foreach($msg_to_insert as $index => $msg_number)
919                        {
920                                if ($msgs_in_the_server[$index+1])
921                                {
922                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
923                                        $msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
924                                }
925                                else
926                                {
927                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
928                                        $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
929                                }
930                        }
931                        ksort($msgs_to_exec);
932                }
933                elseif(!$msgs_existent)
934                {
935                        foreach($msgs_in_the_server as $index => $msg_number)
936                        {
937                                $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
938                        }
939                }
[449]940               
[2]941                $return = array();
942                $i = 0;
943                foreach($msgs_to_exec as $msg_number => $command)
944                {
[535]945                        $header = $this->get_header($msg_number);
[2]946                        if (!is_object($header))
947                                return false;
[449]948                       
[2]949                        $return[$i]['msg_number']       = $msg_number;
950                        $return[$i]['command']          = $command;
[449]951                       
[2]952                        $return[$i]['msg_folder']       = $folder;
953                        $return[$i]['Recent']           = $header->Recent;
954                        $return[$i]['Unseen']           = $header->Unseen;
955                        $return[$i]['Answered']         = $header->Answered;
956                        $return[$i]['Deleted']          = $header->Deleted;
957                        $return[$i]['Draft']            = $header->Draft;
958                        $return[$i]['Flagged']          = $header->Flagged;
959
[535]960                        $date_msg = gmdate("d/m/Y",$header->udate);
961                        if (gmdate("d/m/Y") == $date_msg)
962                                $return[$i]['udate'] = gmdate("H:i",$header->udate);
[2]963                        else
964                                $return[$i]['udate'] = $date_msg;
[449]965                       
[2]966                        $from = $header->from;
967                        $return[$i]['from'] = array();
968                        $tmp = imap_mime_header_decode($from[0]->personal);
969                        $return[$i]['from']['name'] = $tmp[0]->text;
970                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[449]971                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
[2]972                        if(!$return[$i]['from']['name'])
973                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
[449]974                       
[2]975                        /*$toaddress = imap_mime_header_decode($header->toaddress);
976                        $return[$i]['toaddress'] = '';
977                        foreach ($toaddress as $tmp)
978                                $return[$i]['toaddress'] .= $tmp->text;*/
979                        $to = $header->to;
980                        $return[$i]['to'] = array();
981                        $tmp = imap_mime_header_decode($to[0]->personal);
982                        $return[$i]['to']['name'] = $tmp[0]->text;
983                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
984                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[449]985                       
[2]986                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
987
988                        $return[$i]['Size'] = $header->Size;
989                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
[449]990                       
[2]991                        $return[$i]['attachment'] = array();
[51]992                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[2]993                        $i++;
994                }
[51]995                $return['new_msgs'] = imap_num_recent($this->mbox);
[271]996                $return['msgs_to_delete'] = $msg_to_delete;
[411]997                if($this->mbox && is_resource($this->mbox))
[51]998                        imap_close($this->mbox);
[2]999                return $return;
1000        }
1001
[449]1002        function get_folders_list($params = null)
[2]1003        {
[449]1004                $mbox_stream = $this->open_mbox();             
[115]1005                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
[2]1006                $folders_list = imap_getmailboxes($mbox_stream, $serverString, "*");
1007                $tmp = array();
1008                $result = array();
[449]1009               
[2]1010                if (is_array($folders_list)) {
1011                        reset($folders_list);
[449]1012                       
[2]1013                        $i = 0;
1014                        while (list($key, $val) = each($folders_list)) {
1015                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
1016                                $result[$i]['folder_unseen'] = $status->unseen;
[449]1017                       
[2]1018                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1019                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
1020                                $folder_id = $tmp_folder_id[1];
1021                                $result[$i]['folder_id'] = $folder_id;
[449]1022                               
[2]1023                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1024                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
[96]1025                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
[325]1026                                if (is_numeric($result[$i]['folder_name']))     {
[469]1027                                        $this->ldap = new ldap_functions();
[432]1028                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])){
[325]1029                                                $result[$i]['folder_name'] = $cn;
1030                                        }
1031                                }
[449]1032                               
[2]1033                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1034                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
[449]1035                                       
[96]1036                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
[2]1037                                        $result[$i]['folder_hasChildren'] = 1;
1038                                else
1039                                        $result[$i]['folder_hasChildren'] = 0;
1040
[449]1041                                $i++;                           
[2]1042                        }
1043                }
[449]1044               
[2]1045                foreach ($result as $folder_info)
1046                {
1047                        $array_tmp[] = $folder_info['folder_id'];
1048                }
[449]1049               
[2]1050                natcasesort($array_tmp);
[449]1051               
[2]1052                foreach ($array_tmp as $key => $folder_id)
1053                {
1054                        $result2[] = $result[$key];
1055                }
[449]1056               
1057                $current_folder = "INBOX";
1058                if($params && $params['folder'])
1059                        $current_folder = $params['folder'];
1060                return array_merge($result2, $this->get_quota(array(folder_id => $current_folder)));
[2]1061        }
[449]1062       
[2]1063        function create_mailbox($arr)
1064        {
1065                $namebox        = $arr['newp'];
1066                $mbox_stream = $this->open_mbox();
1067                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[51]1068                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
[449]1069               
[2]1070                $result = "Ok";
[51]1071                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
[2]1072                {
1073                        $result = implode("<br />\n", imap_errors());
[449]1074                }       
1075               
[51]1076                if($mbox_stream)
1077                        imap_close($mbox_stream);
[449]1078                                       
[2]1079                return $result;
[449]1080               
[2]1081        }
[449]1082       
[2]1083        function create_extra_mailbox($arr)
1084        {
1085                $nameboxs = explode(";",$arr['nw_folders']);
1086                $result = "";
1087                $mbox_stream = $this->open_mbox();
1088                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[449]1089                foreach($nameboxs as $key=>$tmp){                       
[2]1090                        if($tmp != ""){
1091                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1092                                        $result = implode("<br />\n", imap_errors());
[51]1093                                        if($mbox_stream)
[449]1094                                                imap_close($mbox_stream);                                       
[2]1095                                        return $result;
1096                                }
1097                        }
1098                }
[51]1099                if($mbox_stream)
1100                        imap_close($mbox_stream);
[2]1101                return true;
1102        }
[449]1103       
[2]1104        function delete_mailbox($arr)
1105        {
1106                $namebox = $arr['del_past'];
1107                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1108                $mbox_stream = $this->open_mbox();
1109                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
[449]1110               
[2]1111                $result = "Ok";
1112                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1113                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1114                {
1115                        $result = implode("<br />\n", imap_errors());
1116                }
[51]1117                if($mbox_stream)
1118                        imap_close($mbox_stream);
[2]1119                return $result;
1120        }
[449]1121       
[2]1122        function ren_mailbox($arr)
1123        {
1124                $namebox = $arr['current'];
1125                $new_box = $arr['rename'];
1126                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1127                $mbox_stream = $this->open_mbox();
1128                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
[449]1129               
[2]1130                $result = "Ok";
1131                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
[51]1132                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
[449]1133               
[2]1134                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1135                {
[449]1136                        $result = imap_errors();                       
[2]1137                }
[51]1138                if($mbox_stream)
1139                        imap_close($mbox_stream);
[2]1140                return $result;
[449]1141               
[2]1142        }
[449]1143       
[2]1144        function get_num_msgs($params)
1145        {
1146                $folder = $params['folder'];
[411]1147                if(!$this->mbox || !is_resource($this->mbox)) {
[2]1148                        $this->mbox = $this->open_mbox($folder);
[411]1149                        if(!$this->mbox || !is_resource($this->mbox))
[2]1150                        return imap_last_error();
[449]1151                }               
[2]1152                $num_msgs = imap_num_msg($this->mbox);
[432]1153                if($this->mbox && is_resource($this->mbox))
[51]1154                        imap_close($this->mbox);
[449]1155               
[2]1156                return $num_msgs;
1157        }
[449]1158       
[2]1159        function send_mail($params)
1160        {
1161                include_once("class.phpmailer.php");
1162                $mail = new PHPMailer();
1163                include_once("class.db_functions.inc.php");
1164                $db = new db_functions();
1165                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
[449]1166                ##
1167                # @AUTHOR Rodrigo Souza dos Santos
1168                # @DATE 2008/09/17
1169                # @BRIEF Checks if the user has permission to send an email with the email address used.
1170                ##
1171                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
1172                {
1173                        $deny = true;
1174                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
1175                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
1176                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
1177
1178                        if ( $deny )
1179                                return "The server denied your request to send a mail, you cannot use this mail address.";
1180                }
[2]1181                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1182                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1183                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1184                $subject = $params['input_subject'];
[271]1185                $msg_uid = $params['msg_id'];
[2]1186                $return_receipt = $params['input_return_receipt'];
1187                $body = $params['body'];
1188                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
1189                $attachments = $params['FILES'];
1190                $forwarding_attachments = $params['forwarding_attachments'];
[449]1191                 
[51]1192                $folder =$params['folder'];
[449]1193                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
1194                $folder_name = $params['folder_name'];         
[6]1195                // Fix problem with cyrus delimiter changes.
[449]1196                // Dots in names: enabled/disabled.                             
[6]1197                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1198                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1199                // End Fix.
[449]1200                if ($folder != 'null'){                 
[2]1201                        $mail->SaveMessageInFolder = $folder;
1202                }
1203////////////////////////////////////////////////////////////////////////////////////////////////////
1204                $mail->SMTPDebug = false;
[449]1205                               
[2]1206                $mail->IsSMTP();
1207                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1208                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1209                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1210                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1211                if($fromaddress){
1212                        $mail->Sender = $mail->From;
1213                        $mail->SenderName = $mail->FromName;
1214                        $mail->FromName = $fromaddress[0];
1215                        $mail->From = $fromaddress[1];
1216                }
[449]1217                               
[2]1218                $this->add_recipients("to", $toaddress, &$mail);
1219                $this->add_recipients("cc", $ccaddress, &$mail);
1220                $this->add_recipients("cco", $ccoaddress, &$mail);
1221                $mail->Subject = $subject;
1222                $mail->IsHTML(true);
1223                $mail->Body = $params['body'];
[271]1224
[2]1225////////////////////////////////////////////////////////////////////////////////////////////////////
[271]1226                //      Build CID for embedded Images!!!
[449]1227                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
[271]1228                $cid_imgs = '';
1229                $name_cid_files = array();
1230                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1231                $cid_array = array();
[449]1232                foreach($cid_imgs[6] as $j => $val){
1233                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
[271]1234                        {
[449]1235                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
[271]1236                        }
[449]1237                        $cid = $cid_array[$cid_imgs[4][$j].$val];
[271]1238                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
[449]1239                       
1240                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
[271]1241                                {
[449]1242                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
[271]1243                                        $fileName = "image_".($j).".jpg";
1244                                        $fileCode = "base64";
1245                                        $fileType = "image/jpg";
1246                                }
1247                                else
1248                                {
[449]1249                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
[271]1250                                        $file_description = unserialize(rawurldecode($attach_img));
1251
[449]1252                                        foreach($file_description as $i => $descriptor){                               
[271]1253                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
1254                                        }
1255                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
1256                                        $fileName = $file_description[2];
1257                                        $fileCode = $file_description[4];
1258                                        $fileType = $this->get_file_type($file_description[2]);
[449]1259                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
[271]1260                                }
1261                                $tempDir = ini_get("session.save_path");
[449]1262                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
[271]1263                                $f = fopen($tempDir.'/'.$file,"w");
1264                                fputs($f,$fileContent);
1265                                fclose($f);
1266                                if ($fileContent)
1267                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
1268                                //else
[449]1269                                //      return "Error loading image attachment content";                                               
[271]1270
1271                }
1272////////////////////////////////////////////////////////////////////////////////////////////////////
[2]1273                //      Build Uploading Attachments!!!
1274                if (count($attachments))
1275                {
1276                        $total_uploaded_size = 0;
1277                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
1278                        foreach ($attachments as $attach)
1279                        {
1280                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
1281                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
1282                        }
1283                        if( $total_uploaded_size > $upload_max_filesize)
[504]1284                                return $this->parse_error("message file too big");                     
[449]1285                }                       
[2]1286////////////////////////////////////////////////////////////////////////////////////////////////////
[271]1287                //      Build Forwarding Attachments!!!
[2]1288                if (count($forwarding_attachments) > 0)
1289                {
1290                        // Bug fixed for array_search function
1291                        if(count($name_cid_files) > 0) {
1292                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
1293                                $name_cid_files[0] = null;
[449]1294                        }                       
1295                       
[2]1296                        foreach($forwarding_attachments as $forwarding_attachment)
1297                        {
[271]1298                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
1299                                        $tmp = array_values($file_description);
[449]1300                                        foreach($file_description as $i => $descriptor){                               
[271]1301                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1302                                        }
[449]1303                                        $file_description = $tmp;                                       
[271]1304                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
1305                                        $fileName = $file_description[2];
1306                                        if(!array_search(trim($fileName),$name_cid_files)) {
1307                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
[63]1308                                }
[2]1309                        }
1310                }
[37]1311
[2]1312////////////////////////////////////////////////////////////////////////////////////////////////////
1313                // Disposition-Notification-To
1314                if ($return_receipt)
1315                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1316////////////////////////////////////////////////////////////////////////////////////////////////////
[504]1317
[117]1318                $sent = $mail->Send();
[504]1319               
[117]1320                if(!$sent)
[2]1321                {
[504]1322                        return $this->parse_error($mail->ErrorInfo);
[2]1323                }
1324                else
1325                {
[449]1326                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
[117]1327                        {
1328                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
1329                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
1330                                $now = date("d/m/y H:i:s");
1331                                $addrs = $toaddress.$ccaddress.$ccoaddress;
[449]1332                                $sent = trim($sent);                                                                                           
[117]1333                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
1334                        }
[485]1335                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
1336                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
[469]1337                                $contacts = new dynamic_contacts();
[485]1338                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
1339                                return array("success" => true, "new_contacts" => $new_contacts);
[413]1340                        }
[485]1341                        return array("success" => true);
[2]1342                }
1343        }
1344
1345        function add_recipients($recipient_type, $full_address, $mail)
1346        {
[449]1347                $parse_address = imap_rfc822_parse_adrlist($full_address, "");         
1348                foreach ($parse_address as $val)
[2]1349                {
1350                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
1351                        if ($val->mailbox == "INVALID_ADDRESS")
1352                                continue;
[449]1353                       
[2]1354                        if (empty($val->personal))
1355                        {
1356                                switch($recipient_type)
1357                                {
1358                                        case "to":
1359                                                $mail->AddAddress($val->mailbox."@".$val->host);
1360                                                break;
1361                                        case "cc":
1362                                                $mail->AddCC($val->mailbox."@".$val->host);
1363                                                break;
1364                                        case "cco":
1365                                                $mail->AddBCC($val->mailbox."@".$val->host);
1366                                                break;
1367                                }
1368                        }
1369                        else
1370                        {
1371                                switch($recipient_type)
1372                                {
1373                                        case "to":
1374                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
1375                                                break;
1376                                        case "cc":
1377                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
1378                                                break;
1379                                        case "cco":
1380                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
1381                                                break;
1382                                }
1383                        }
1384                }
1385                return true;
1386        }
[449]1387       
[2]1388        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
1389        {
[449]1390                $mbox_stream = $this->open_mbox($msg_folder);                   
1391                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);           
[2]1392                if($encoding == 'base64')
[449]1393                        # The function imap_base64 adds a new line
1394                        # at ASCII text, with CRLF line terminators.
1395                        # So is being exchanged for base64_decode.
1396                        #
1397                        #$fileContent = imap_base64($fileContent);
1398                        $fileContent = base64_decode($fileContent);
[2]1399                else if($encoding == 'quoted-printable')
[449]1400                        $fileContent = quoted_printable_decode($fileContent);                           
[2]1401                return $fileContent;
1402        }
[449]1403       
[2]1404        function del_last_caracter($string)
1405        {
1406                $string = substr($string,0,(strlen($string) - 1));
[449]1407                return $string;
[2]1408        }
[449]1409       
[2]1410        function del_last_two_caracters($string)
1411        {
1412                $string = substr($string,0,(strlen($string) - 2));
[449]1413                return $string;
[2]1414        }
[449]1415       
[53]1416        function imap_sortfrom($sort_box_reverse, $search_box_type)
[2]1417        {
1418                $sortfrom = array();
1419                $sortfrom_uid = array();
[449]1420               
[51]1421                $num_msgs = imap_num_msg($this->mbox);
[2]1422                for ($i=1; $i<=$num_msgs; $i++)
1423                {
[539]1424                        $header = $this->get_header(imap_uid($this->mbox,$i));
[53]1425                        // List UNSEEN messages.
1426                        if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
1427                                continue;
1428                        }
1429                        // List SEEN messages.
1430                        elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
1431                                continue;
1432                        }
[449]1433                        // List ANSWERED messages.                     
[53]1434                        elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
[449]1435                                continue;                               
[53]1436                        }
[449]1437                        // List FLAGGED messages.                       
[53]1438                        elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
1439                                continue;
1440                        }
[449]1441                                               
1442                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])                             
[2]1443                                $from = $header->to;
1444                        else
1445                                $from = $header->from;
[449]1446                       
1447                        $tmp = imap_mime_header_decode($from[0]->personal);                     
1448                       
[2]1449                        if ($tmp[0]->text != "")
[53]1450                                $sortfrom[$i] = $tmp[0]->text;
[2]1451                        else
[53]1452                                $sortfrom[$i] = $from[0]->mailbox . "@" . $from[0]->host;
[2]1453                }
[449]1454               
[2]1455                natcasesort($sortfrom);
[449]1456               
[2]1457                foreach($sortfrom as $index => $header_msg)
[449]1458                {       
[53]1459                        $sortfrom_uid[] = imap_uid($this->mbox, $index);
[2]1460                }
[449]1461               
[2]1462                if ($sort_box_reverse)
1463                        $sortfrom_uid = array_reverse($sortfrom_uid);
[449]1464               
[2]1465                return $sortfrom_uid;
1466        }
[51]1467
[449]1468        function move_search_messages($params){         
1469                $params['selected_messages'] = urldecode($params['selected_messages']);
[163]1470                $params['new_folder'] = urldecode($params['new_folder']);
1471                $params['new_folder_name'] = urldecode($params['new_folder_name']);
1472                $sel_msgs = explode(",", $params['selected_messages']);
[449]1473                @reset($sel_msgs);     
[163]1474                $sorted_msgs = array();
1475                foreach($sel_msgs as $idx => $sel_msg) {
1476                        $sel_msg = explode(";", $sel_msg);
1477                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
1478                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
[449]1479                         }     
[163]1480                         else {
1481                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
1482                         }
1483                }
1484                @ksort($sorted_msgs);
[449]1485                $last_return = false;           
1486                foreach($sorted_msgs as $folder => $msgs_number) {                     
[163]1487                        $params['msgs_number'] = $msgs_number;
[449]1488                        $params['folder'] = $folder;   
[163]1489                        if($params['new_folder'] && $folder != $params['new_folder']){
[449]1490                                $last_return = $this -> move_messages($params);                         
[163]1491                        }
1492                        elseif(!$params['new_folder'] || $params['delete'] ){
1493                                $last_return = $this -> delete_msgs($params);
1494                                $last_return['deleted'] = true;
1495                        }
1496                }
1497                return $last_return;
1498        }
[449]1499       
[2]1500        function move_messages($params)
1501        {
[449]1502                $folder = $params['folder'];           
1503                $mbox_stream = $this->open_mbox($folder);               
[51]1504                $newmailbox = ($params['new_folder']);
1505                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
[2]1506                $new_folder_name = $params['new_folder_name'];
1507                $msgs_number = $params['msgs_number'];
1508                $return = array('msgs_number' => $msgs_number,
1509                                                'folder' => $folder,
1510                                                'new_folder_name' => $new_folder_name,
[325]1511                                                'border_ID' => $params['border_ID'],
1512                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
[449]1513               
[325]1514                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
1515        if (substr($folder,0,4) == 'user'){
1516                $acl = $this->getacltouser($folder);
1517                /*
1518                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
1519                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
1520                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
1521                 *   w - write (STORE flags other than SEEN and DELETED)
1522                 *   i - insert (perform APPEND, COPY into mailbox)
1523                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
1524                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
1525                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
1526                 *   a - administer (perform SETACL)
1527                        */
1528                        if (strpos($acl, "d") === false){
1529                                $return['status'] = false;
1530                                return $return;
1531                        }
1532        }
[432]1533        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
1534        if (substr($new_folder_name,0,4) == 'user'){
1535                $this->ldap = new ldap_functions();
1536                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
1537                        $return['new_folder_name'] = array_pop($tmp_folder_name);
1538                        if (is_numeric($return['new_folder_name']))
1539                                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
1540                                        $return['new_folder_name'] = $cn;
1541        }
[449]1542                               
1543                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.         
[51]1544                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
[449]1545                {
[2]1546                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]1547                        // Fix problem in unserialize function JS.
1548                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1549                }
1550               
1551                $mbox_stream = $this->open_mbox($folder);       
[2]1552                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1553                        imap_expunge($mbox_stream);
[51]1554                        if($mbox_stream)
1555                                imap_close($mbox_stream);
[2]1556                        return $return;
1557                }else {
[449]1558                        if(strstr(imap_last_error(),'Over quota')) {                           
[2]1559                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
[449]1560                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];                                                                       
1561                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];                                                           
[2]1562                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
[504]1563                                $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()))));
[2]1564                                if(!$mbox)
1565                                        return imap_last_error();
[449]1566                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");                           
[2]1567                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
[51]1568                                        if($mbox_stream)
1569                                                imap_close($mbox_stream);
[449]1570                                        if($mbox)                                                                       
[51]1571                                                imap_close($mbox);
[449]1572                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";                                                               
[2]1573                                }
1574                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1575                                        imap_expunge($mbox_stream);
[51]1576                                        if($mbox_stream)
1577                                                imap_close($mbox_stream);
[2]1578                                        // return to original quota limit.
1579                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]1580                                                if($mbox)
1581                                                        imap_close($mbox);
[449]1582                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
[2]1583                                        }
[449]1584                                        return $return;                                                                                                 
[2]1585                                }
1586                                else {
[51]1587                                        if($mbox_stream)
1588                                                imap_close($mbox_stream);
[2]1589                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]1590                                                if($mbox)
1591                                                        imap_close($mbox);
[449]1592                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
[2]1593                                        }
[449]1594                                        return imap_last_error();                               
[2]1595                                }
[449]1596                               
[2]1597                        }
1598                        else {
[51]1599                                if($mbox_stream)
1600                                        imap_close($mbox_stream);
1601                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
[2]1602                        }
[449]1603                }               
[2]1604        }
[449]1605       
[2]1606        function save_msg($params)
1607        {
[449]1608               
[271]1609                include_once("class.phpmailer.php");
1610                $mail = new PHPMailer();
1611                include_once("class.db_functions.inc.php");
1612                $toaddress = $params['input_to'];
1613                $ccaddress = $params['input_cc'];
1614                $subject = $params['input_subject'];
[320]1615                $msg_uid = $params['msg_id'];
[2]1616                $body = $params['body'];
1617                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
[155]1618                $body = preg_replace("/\n/"," ",$body);
[51]1619                $body = preg_replace("/\r/","",$body);
[271]1620                $forwarding_attachments = $params['forwarding_attachments'];
1621                $attachments = $params['FILES'];
1622                $return_files = $params['FILES'];
[449]1623                 
[271]1624                $folder = $params['folder'];
[449]1625                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
[271]1626                // Fix problem with cyrus delimiter changes.
[449]1627                // Dots in names: enabled/disabled.                             
[271]1628                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1629                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1630                // End Fix.
[449]1631                                       
[271]1632                $mail->SaveMessageInFolder = $folder;
1633                $mail->SMTPDebug = false;
[449]1634                                               
[271]1635                $mail->IsSMTP();
1636                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1637                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1638                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1639                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
[449]1640               
[271]1641                $mail->Sender = $mail->From;
1642                $mail->SenderName = $mail->FromName;
1643                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1644                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
[449]1645                               
[271]1646                $this->add_recipients("to", $toaddress, &$mail);
1647                $this->add_recipients("cc", $ccaddress, &$mail);
1648                $mail->Subject = $subject;
1649                $mail->IsHTML(true);
1650                $mail->Body = $body;
[449]1651               
[320]1652                //      Build CID for embedded Images!!!
[449]1653                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
[320]1654                $cid_imgs = '';
1655                $name_cid_files = array();
1656                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1657                $cid_array = array();
[449]1658                foreach($cid_imgs[6] as $j => $val){
1659                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
[320]1660                        {
[449]1661                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
[320]1662                        }
[449]1663                        $cid = $cid_array[$cid_imgs[4][$j].$val];
[320]1664                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
[449]1665                       
1666                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
[320]1667                                {
[449]1668                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
1669                                        //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
[320]1670                                        $fileName = "image_".($j).".jpg";
1671                                        $fileCode = "base64";
1672                                        $fileType = "image/jpg";
[449]1673                                        $file_attached[0] = $cid_imgs[2][$j];
1674                                        $file_attached[1] = $cid_imgs[4][$j];
1675                                        $file_attached[2] = $fileName;
1676                                        $file_attached[3] = $cid_imgs[6][$j];
1677                                        $file_attached[4] = 'base64';
1678                                        $file_attached[5] = strlen($fileContent); //Size of file
1679                                        $return_forward[] = $file_attached;
[320]1680                                }
1681                                else
1682                                {
[449]1683                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
[320]1684                                        $file_description = unserialize(rawurldecode($attach_img));
[449]1685                                        foreach($file_description as $i => $descriptor){                               
[320]1686                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
1687                                        }
1688                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
1689                                        $fileName = $file_description[2];
1690                                        $fileCode = $file_description[4];
1691                                        $fileType = $this->get_file_type($file_description[2]);
[449]1692                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
[320]1693                                        if (!empty($file_description))
1694                                        {
1695                                                $file_description[5] = strlen($fileContent); //Size of file
1696                                                $return_forward[] = $file_description;
1697                                        }
1698                                }
1699                                $tempDir = ini_get("session.save_path");
[449]1700                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
[320]1701                                $f = fopen($tempDir.'/'.$file,"w");
1702                                fputs($f,$fileContent);
1703                                fclose($f);
1704                                if ($fileContent)
1705                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
1706                                //else
[449]1707                                //      return "Error loading image attachment content";                                               
[320]1708
1709                }
[449]1710       
1711        //      Build Forwarding Attachments!!!         
[271]1712                if (count($forwarding_attachments) > 0)
1713                {
1714                        foreach($forwarding_attachments as $forwarding_attachment)
1715                        {
1716                                $file_description = unserialize(rawurldecode($forwarding_attachment));
1717                                $tmp = array_values($file_description);
[449]1718                                foreach($file_description as $i => $descriptor){                               
[271]1719                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1720                                }
1721                                $file_description = $tmp;
[449]1722                               
[271]1723                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
1724                                $fileName = $file_description[2];
[449]1725                               
[271]1726                                $file_description[5] = strlen($fileContent); //Size of file
1727                                $return_forward[] = $file_description;
[449]1728                       
[271]1729                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
1730                        }
1731                }
[449]1732               
[271]1733                if ((count($return_forward) > 0) && (count($return_files) > 0))
1734                        $return_files = array_merge_recursive($return_forward,$return_files);
1735                else
1736                        if (count($return_files) < 1)
1737                                $return_files = $return_forward;
[449]1738       
[271]1739                //      Build Uploading Attachments!!!
1740                if (count($attachments))
1741                        foreach ($attachments as $attach)
[449]1742                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name                 
1743       
1744       
1745               
[271]1746                if(!empty($mail->AltBody))
1747            $mail->ContentType = "multipart/alternative";
1748
1749        $mail->error_count = 0; // reset errors
1750        $mail->SetMessageType();
1751        $header = $mail->CreateHeader();
1752        $body = $mail->CreateBody();
[449]1753       
[271]1754        if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
1755                {
1756                        $imap_options = '/tls/novalidate-cert';
1757                }
1758                else
1759                {
1760                        $imap_options = '/notls/novalidate-cert';
1761                }
1762                $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
1763                $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
1764                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1765                $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
1766                $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
[449]1767       
[271]1768                $new_header = str_replace("\n", "\r\n", $header);
1769                $new_body = str_replace("\n", "\r\n", $body);
[449]1770               
[271]1771                $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
1772                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
1773                $return['msg_no'] = $status->uidnext - 1;
1774                $return['folder_id'] = $folder;
[449]1775               
[51]1776                if($mbox_stream)
1777                        imap_close($mbox_stream);
[449]1778                               
[271]1779                foreach ($return_files as $index => $_attachment) {
1780                        if (array_key_exists("name",$_attachment)){
1781                                unset($return_files[$index]);
1782                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
1783                        }
1784                        else
1785                        {
1786                                unset($return_files[$index]);
1787                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
1788                        }
1789                }
[449]1790               
[271]1791                $return['files'] = serialize($return_files);
[449]1792                               
[2]1793                if (!$return['append'])
1794                        $return['append'] = imap_last_error();
[449]1795               
[2]1796                return $return;
1797        }
[449]1798       
[2]1799        function set_messages_flag($params)
1800        {
1801                $folder = $params['folder'];
1802                $msgs_to_set = $params['msgs_to_set'];
1803                $flag = $params['flag'];
1804                $return = array();
1805                $return["msgs_to_set"] = $msgs_to_set;
1806                $return["flag"] = $flag;
[449]1807               
[411]1808                if(!$this->mbox && !is_resource($this->mbox))
[51]1809                        $this->mbox = $this->open_mbox($folder);
[449]1810               
[2]1811                if ($flag == "unseen")
[51]1812                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]1813                elseif ($flag == "seen")
[51]1814                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]1815                elseif ($flag == "answered"){
[51]1816                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
1817                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
[2]1818                }
1819                elseif ($flag == "forwarded")
[51]1820                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
[2]1821                elseif ($flag == "flagged")
[51]1822                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
[2]1823                elseif ($flag == "unflagged")
[51]1824                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
[449]1825               
[411]1826                if($this->mbox && is_resource($this->mbox))
[51]1827                        imap_close($this->mbox);
[2]1828                return $return;
1829        }
[449]1830       
[2]1831        function get_file_type($file_name)
1832        {
1833                $file_name = strtolower($file_name);
1834                $strFileType = strrev(substr(strrev($file_name),0,4));
[449]1835                if ($strFileType == ".asf")
[2]1836                        return "video/x-ms-asf";
1837                if ($strFileType == ".avi")
1838                        return "video/avi";
1839                if ($strFileType == ".doc")
1840                        return "application/msword";
1841                if ($strFileType == ".zip")
1842                        return "application/zip";
1843                if ($strFileType == ".xls")
1844                        return "application/vnd.ms-excel";
1845                if ($strFileType == ".gif")
1846                        return "image/gif";
1847                if ($strFileType == ".jpg" || $strFileType == "jpeg")
1848                        return "image/jpeg";
1849                if ($strFileType == ".png")
1850                        return "image/png";
1851                if ($strFileType == ".wav")
1852                        return "audio/wav";
1853                if ($strFileType == ".mp3")
1854                        return "audio/mpeg3";
1855                if ($strFileType == ".mpg" || $strFileType == "mpeg")
1856                        return "video/mpeg";
1857                if ($strFileType == ".rtf")
1858                        return "application/rtf";
1859                if ($strFileType == ".htm" || $strFileType == "html")
1860                        return "text/html";
[449]1861                if ($strFileType == ".xml")
[2]1862                        return "text/xml";
[449]1863                if ($strFileType == ".xsl")
[2]1864                        return "text/xsl";
[449]1865                if ($strFileType == ".css")
[2]1866                        return "text/css";
[449]1867                if ($strFileType == ".php")
[2]1868                        return "text/php";
[449]1869                if ($strFileType == ".asp")
[2]1870                        return "text/asp";
1871                if ($strFileType == ".pdf")
1872                        return "application/pdf";
1873                if ($strFileType == ".txt")
1874                        return "text/plain";
1875                if ($strFileType == ".wmv")
1876                        return "video/x-ms-wmv";
1877                if ($strFileType == ".sxc")
1878                        return "application/vnd.sun.xml.calc";
1879                if ($strFileType == ".stc")
1880                        return "application/vnd.sun.xml.calc.template";
1881                if ($strFileType == ".sxd")
1882                        return "application/vnd.sun.xml.draw";
1883                if ($strFileType == ".std")
1884                        return "application/vnd.sun.xml.draw.template";
1885                if ($strFileType == ".sxi")
1886                        return "application/vnd.sun.xml.impress";
1887                if ($strFileType == ".sti")
1888                        return "application/vnd.sun.xml.impress.template";
1889                if ($strFileType == ".sxm")
1890                        return "application/vnd.sun.xml.math";
1891                if ($strFileType == ".sxw")
1892                        return "application/vnd.sun.xml.writer";
1893                if ($strFileType == ".sxq")
1894                        return "application/vnd.sun.xml.writer.global";
1895                if ($strFileType == ".stw")
1896                        return "application/vnd.sun.xml.writer.template";
[449]1897               
1898               
1899                return "application/octet-stream";             
[2]1900        }
[449]1901       
[2]1902        function htmlspecialchars_encode($str)
1903        {
[449]1904                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
[2]1905        }
1906        function htmlspecialchars_decode($str)
1907        {
[449]1908                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
[2]1909        }
[449]1910       
[53]1911        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse){
[449]1912               
[411]1913                if(!$this->mbox || !is_resource($this->mbox)){
[51]1914                        $this->mbox = $this->open_mbox($folder);
[449]1915               
[411]1916                }
[432]1917
[2]1918                switch($sort_box_type){
1919                        case 'SORTFROM':
[449]1920                                return $this->imap_sortfrom($sort_box_reverse, $search_box_type);                               
[2]1921                        case 'SORTSUBJECT':
[449]1922                                return imap_sort($this->mbox, SORTSUBJECT, $sort_box_reverse, SE_UID, $search_box_type);                               
[2]1923                        case 'SORTSIZE':
[449]1924                                return imap_sort($this->mbox, SORTSIZE, $sort_box_reverse, SE_UID, $search_box_type);                           
[53]1925                        default:
[449]1926                                return imap_sort($this->mbox, SORTARRIVAL, $sort_box_reverse, SE_UID, $search_box_type);                                               
1927                }               
1928        }       
1929       
[53]1930        function get_info_next_msg($params)
1931        {
1932                $msg_number = $params['msg_number'];
1933                $folder = $params['msg_folder'];
1934                $sort_box_type = $params['sort_box_type'];
1935                $sort_box_reverse = $params['sort_box_reverse'];
1936                $reuse_border = $params['reuse_border'];
1937                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[449]1938                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);                             
1939               
[320]1940                $success = false;
1941                if (is_array($sort_array_msg))
[2]1942                {
[320]1943                        foreach ($sort_array_msg as $i => $value){
1944                                if ($value == $msg_number)
1945                                {
1946                                        $success = true;
1947                                        break;
1948                                }
1949                        }
[2]1950                }
1951
[320]1952                if (! $success || $i >= sizeof($sort_array_msg)-1)
[2]1953                {
1954                        $params['status'] = 'false';
1955                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
1956                        return $params;
1957                }
[449]1958               
[2]1959                $params = array();
1960                $params['msg_number'] = $sort_array_msg[($i+1)];
1961                $params['msg_folder'] = $folder;
[449]1962               
1963                $return = $this->get_info_msg($params);         
[2]1964                $return["reuse_border"] = $reuse_border;
1965                return $return;
1966        }
1967
1968        function get_info_previous_msg($params)
1969        {
1970                $msg_number = $params['msgs_number'];
1971                $folder = $params['folder'];
1972                $sort_box_type = $params['sort_box_type'];
1973                $sort_box_reverse = $params['sort_box_reverse'];
1974                $reuse_border = $params['reuse_border'];
[53]1975                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1976                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
[449]1977               
[320]1978                $success = false;
1979                if (is_array($sort_array_msg))
[2]1980                {
[320]1981                        foreach ($sort_array_msg as $i => $value){
1982                                if ($value == $msg_number)
1983                                {
1984                                        $success = true;
1985                                        break;
1986                                }
1987                        }
[2]1988                }
[320]1989                if (! $success || $i == 0)
1990                {
[2]1991                        $params['status'] = 'false';
1992                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
1993                        return $params;
1994                }
[449]1995               
[2]1996                $params = array();
1997                $params['msg_number'] = $sort_array_msg[($i-1)];
1998                $params['msg_folder'] = $folder;
[449]1999               
[2]2000                $return = $this->get_info_msg($params);
2001                $return["reuse_border"] = $reuse_border;
2002                return $return;
2003        }
[449]2004       
[2]2005        // This function updates the values: quota, paging and new messages menu.
2006        function get_menu_values($params){
2007                $return_array = array();
2008                $return_array = $this->get_quota($params);
[449]2009               
[2]2010                $mbox_stream = $this->open_mbox($params['folder']);
[449]2011                $return_array['num_msgs'] = imap_num_msg($mbox_stream);         
[51]2012                if($mbox_stream)
2013                        imap_close($mbox_stream);
[449]2014                               
2015                return $return_array;
[2]2016        }
[449]2017       
[325]2018        function get_quota($params){
[449]2019                // folder_id = user/{uid} for shared folders
2020                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
2021                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
2022                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];             
2023                }
2024                // folder_id = INBOX for inbox folders
2025                else
2026                        $folder_id = "INBOX";
2027               
2028                if(!$this->mbox)
[51]2029                        $this->mbox = $this->open_mbox();
[345]2030
[325]2031                $quota = imap_get_quotaroot($this->mbox, $folder_id);
[411]2032                if($this->mbox && is_resource($this->mbox))
[51]2033                        imap_close($this->mbox);
[449]2034                       
[2]2035                if (!$quota){
2036                        return array(
2037                                'quota_percent' => 0,
2038                                'quota_used' => 0,
2039                                'quota_limit' =>  0
2040                        );
2041                }
[449]2042               
[2]2043                if(count($quota) && $quota['limit']) {
2044                        $quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
2045                        $quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
2046                        if($quota_used >= $quota_limit)
2047                                $quota_used = $quota_limit;
2048                        $quotaPercent = ($quota_used / $quota_limit)*100;
2049                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
2050
2051                        return array(
2052                                'quota_percent' => floor($quotaPercent),
2053                                'quota_used' => floor($quota_used),
2054                                'quota_limit' =>  floor($quota_limit)
2055                        );
2056                }
[449]2057                else
[2]2058                        return array();
2059        }
[449]2060       
[2]2061        function send_notification($params){
2062                require_once("class.phpmailer.php");
2063                $mail = new PHPMailer();
[449]2064                 
[2]2065                $toaddress = $params['notificationto'];
[449]2066               
2067                $subject = 'Confirmação de leitura: ' . $params['subject'];
[2]2068                $body = 'Sua mensagem: ' . $params['subject'] . '<br>';
2069                $body .= 'foi lida por: ' . $_SESSION['phpgw_info']['expressomail']['user']['fullname'] . ' &lt;' . $_SESSION['phpgw_info']['expressomail']['user']['email'] . '&gt; em ' . date("d/m/Y H:i");
2070                $mail->SMTPDebug = false;
2071                $mail->IsSMTP();
2072                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2073                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2074                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2075                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2076                $mail->AddAddress($toaddress);
2077                $mail->Subject = $this->htmlspecialchars_decode($subject);
2078
2079                $mail->IsHTML(true);
2080                $mail->Body = $body;
[449]2081               
[2]2082                if(!$mail->Send()){
2083                        return $mail->ErrorInfo;
2084                }
2085                else
2086                        return true;
2087        }
[449]2088       
[2]2089        function empty_trash()
2090        {
[449]2091                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
[2]2092                $mbox_stream = $this->open_mbox($folder);
2093                $return = imap_delete($mbox_stream,'1:*');
[51]2094                if($mbox_stream)
2095                        imap_close($mbox_stream, CL_EXPUNGE);
[2]2096                return $return;
2097        }
[449]2098       
[2]2099        function search($params)
2100        {
2101                include("class.imap_attachment.inc.php");
[449]2102                $imap_attachment = new imap_attachment();                               
[2]2103                $criteria = $params['criteria'];
2104                $return = array();
2105                $folders = $this->get_folders_list();
[449]2106               
[2]2107                $j = 0;
2108                foreach($folders as $folder)
2109                {
2110                        $mbox_stream = $this->open_mbox($folder);
2111                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
[449]2112                       
[2]2113                        if ($messages == '')
2114                                continue;
[449]2115               
[2]2116                        $i = 0;
2117                        $return[$j] = array();
2118                        $return[$j]['folder_name'] = $folder['name'];
[449]2119                       
[2]2120                        foreach($messages as $msg_number)
2121                        {
[535]2122                                $header = $this->get_header($msg_number);
[2]2123                                if (!is_object($header))
2124                                        return false;
[449]2125                               
[2]2126                                $return[$j][$i]['msg_folder']   = $folder['name'];
2127                                $return[$j][$i]['msg_number']   = $msg_number;
2128                                $return[$j][$i]['Recent']               = $header->Recent;
2129                                $return[$j][$i]['Unseen']               = $header->Unseen;
2130                                $return[$j][$i]['Answered']     = $header->Answered;
2131                                $return[$j][$i]['Deleted']              = $header->Deleted;
2132                                $return[$j][$i]['Draft']                = $header->Draft;
2133                                $return[$j][$i]['Flagged']              = $header->Flagged;
[449]2134       
[535]2135                                $date_msg = gmdate("d/m/Y",$header->udate);
2136                                if (gmdate("d/m/Y") == $date_msg)
2137                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
[2]2138                                else
2139                                        $return[$j][$i]['udate'] = $date_msg;
[449]2140                       
[2]2141                                $fromaddress = imap_mime_header_decode($header->fromaddress);
2142                                $return[$j][$i]['fromaddress'] = '';
2143                                foreach ($fromaddress as $tmp)
2144                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
[449]2145                       
[2]2146                                $from = $header->from;
2147                                $return[$j][$i]['from'] = array();
2148                                $tmp = imap_mime_header_decode($from[0]->personal);
2149                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
2150                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
[449]2151                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
[2]2152
2153                                $to = $header->to;
2154                                $return[$j][$i]['to'] = array();
2155                                $tmp = imap_mime_header_decode($to[0]->personal);
2156                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
2157                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
[449]2158                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[2]2159
2160                                $subject = imap_mime_header_decode($header->fetchsubject);
2161                                $return[$j][$i]['subject'] = '';
2162                                foreach ($subject as $tmp)
2163                                        $return[$j][$i]['subject'] .= $tmp->text;
2164
2165                                $return[$j][$i]['Size'] = $header->Size;
2166                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
[449]2167                       
[2]2168                                $return[$j][$i]['attachment'] = array();
2169                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
[449]2170                                               
[2]2171                                $i++;
2172                        }
2173                        $j++;
[51]2174                        if($mbox_stream)
2175                                imap_close($mbox_stream);
[2]2176                }
[449]2177       
[2]2178                return $return;
2179        }
[449]2180       
[2]2181        function delete_and_show_previous_message($params)
2182        {
2183                $return = $this->get_info_previous_msg($params);
[449]2184               
[2]2185                $params_tmp1 = array();
2186                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
2187                $params_tmp1['folder'] = $params['msg_folder'];
2188                $return_tmp1 = $this->delete_msg($params_tmp1);
[449]2189               
[2]2190                $return['msg_number_deleted'] = $return_tmp1;
[449]2191               
[2]2192                return $return;
2193        }
[449]2194               
2195       
[2]2196        function automatic_trash_cleanness($params)
2197        {
2198                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
2199                $criteria =  'BEFORE "'.$before_date.'"';
[325]2200                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
[2]2201                $messages = imap_search($mbox_stream, $criteria, SE_UID);
2202                if (is_array($messages)){
2203                        foreach ($messages as $msg_number){
2204                                imap_delete($mbox_stream, $msg_number, FT_UID);
2205                        }
2206                }
[51]2207                if($mbox_stream)
2208                        imap_close($mbox_stream, CL_EXPUNGE);
[2]2209                return $messages;
2210        }
2211//      Fix the search problem with special characters!!!!
2212        function remove_accents($string) {
[449]2213                return strtr($string,
2214                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
[2]2215                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
2216        }
2217
[469]2218        function search_msg($params = ''){             
[2]2219                $retorno = "";
[271]2220                $mbox_stream = "";
[2]2221                $search = explode(",",$params['condition']);
2222                if($search){
2223                        $search_criteria = '';
[271]2224                        foreach($search as $tmp)
2225                        {
[2]2226                                $tmp1 = explode("##",$tmp);
2227                                $name_box = $tmp1[0];
[372]2228                                unset($filter);
2229                                foreach($tmp1 as $index => $criteria)
2230                                {
2231                                        if ($index != 0 && strlen($criteria) != 0)
2232                                        {
2233                                                $filter_array = explode("<=>",rawurldecode($criteria));
2234                                                $filter .= " ".$filter_array[0];
2235                                                $filter .= '"'.$filter_array[1].'"';
2236                                        }
[449]2237                                }               
2238                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
[372]2239                                $filter = $this->remove_accents($filter);
[469]2240                                //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
[432]2241                                $folder_name = explode($this->imap_delimiter,$name_box);
[469]2242                                if (is_numeric($folder_name[1])) {
2243                                        $this->ldap = new ldap_functions();
2244                                        if ($cn = $this->ldap->uid2cn($folder_name[1])) {
2245                                                $folder_name[1] = $cn;
[432]2246                                        }
2247                                }
2248                                $folder_name = implode($this->imap_delimiter,$folder_name);
[449]2249                               
[271]2250                                if(!is_resource($mbox_stream))
[372]2251                                        $mbox_stream = $this->open_mbox($name_box);
[271]2252                                else
2253                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
[449]2254                       
2255                                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search   
2256                               
[271]2257                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
2258                                        foreach($all_criterias as $criteria_fixed)
2259                                        {
[372]2260                                                $_filter = $criteria_fixed . substr($filter,4);
[449]2261                                       
[372]2262                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
[449]2263                                               
[271]2264                                                if($search_criteria && count($search_criteria) < 50)
2265                                                {
[2]2266                                                        foreach($search_criteria as $new_search){
[449]2267                                                                $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");
[271]2268                                                                if(!@strstr($retorno,$m_token))
[2]2269                                                                        $retorno .= $m_token;
2270                                                        }
[449]2271                                                }                                               
2272                                                else if(count($search_criteria) >= 50)                                                 
2273                                                        return "many results";                                         
[2]2274                                        }
[271]2275                                }
[2]2276                                else {
[271]2277                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
[372]2278                                        if( is_array( $search_criteria) )
2279                                        {
2280                                                foreach($search_criteria as $new_search)
[449]2281                                                        $retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
[2]2282                                        }
2283                                }
2284                        }
[271]2285                }
2286                if($mbox_stream)
[449]2287                        imap_close($mbox_stream);               
2288                                               
[2]2289                return $retorno ? $retorno : "none";
2290        }
[449]2291       
[271]2292        function get_msg($uid_msg,$name_box, $mbox_stream )
2293        {
[535]2294                $header = $this->get_header($uid_msg);         
[163]2295                $subject = $this->decode_string($header->fetchsubject);
2296                $from = $header->from[0]->mailbox;
[2]2297                if($header->from[0]->personal != "")
2298                        $from = $header->from[0]->personal;
[535]2299                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size);
[449]2300                return $ret_msg;                   
2301        }       
2302       
[2]2303        function size_msg($size){
2304                $var = floor($size/1024);
2305                if($var >= 1){
[449]2306                        return $var." kb";     
[2]2307                }else{
[449]2308                        return $size ." b";     
[2]2309                }
2310        }
2311
2312        function ob_array($the_object)
2313        {
2314           $the_array=array();
2315           if(!is_scalar($the_object))
2316           {
2317               foreach($the_object as $id => $object)
2318               {
2319                   if(is_scalar($object))
2320                   {
2321                       $the_array[$id]=$object;
2322                   }
2323                   else
2324                   {
2325                       $the_array[$id]=$this->ob_array($object);
2326                   }
2327               }
2328               return $the_array;
2329           }
2330           else
2331           {
2332               return $the_object;
2333           }
2334        }
[449]2335       
[2]2336        function getacl()
2337        {
2338                $this->ldap = new ldap_functions();
[449]2339               
[2]2340                $return = array();
[449]2341                $mbox_stream = $this->open_mbox();     
[2]2342                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[449]2343               
[2]2344                $i = 0;
2345                foreach ($mbox_acl as $user => $acl)
2346                {
2347                        if ($user != $this->username)
2348                        {
2349                                $return[$i]['uid'] = $user;
2350                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
2351                        }
2352                        $i++;
2353                }
2354                return $return;
2355        }
[449]2356       
[2]2357        function setacl($params)
2358        {
2359                $old_users = $this->getacl();
2360                if (!count($old_users))
2361                        $old_users = array();
[449]2362               
[2]2363                $tmp_array = array();
2364                foreach ($old_users as $index => $user_info)
2365                {
2366                        $tmp_array[$index] = $user_info['uid'];
2367                }
2368                $old_users = $tmp_array;
[449]2369               
[2]2370                $users = unserialize($params['users']);
2371                if (!count($users))
2372                        $users = array();
[449]2373               
[2]2374                //$add_share = array_diff($users, $old_users);
2375                $remove_share = array_diff($old_users, $users);
2376
2377                $mbox_stream = $this->open_mbox();
2378
2379                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2380                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
2381
2382                /*if (count($add_share))
2383                {
2384                        foreach ($add_share as $index=>$uid)
2385                        {
2386                        if (is_array($mailboxes_list))
2387                        {
2388                        foreach ($mailboxes_list as $key => $val)
2389                        {
2390                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
2391                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
2392                        }
2393                        }
2394                        }
2395                }*/
[449]2396               
[2]2397                if (count($remove_share))
2398                {
2399                        foreach ($remove_share as $index=>$uid)
2400                        {
2401                        if (is_array($mailboxes_list))
2402                        {
2403                        foreach ($mailboxes_list as $key => $val)
2404                        {
2405                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
2406                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
2407                        }
2408                        }
[449]2409                        }       
[2]2410                }
[449]2411               
[2]2412                return true;
2413        }
[449]2414       
[2]2415        function getaclfromuser($params)
2416        {
2417                $useracl = $params['user'];
[449]2418               
[2]2419                $return = array();
2420                $return[$useracl] = 'false';
[449]2421                $mbox_stream = $this->open_mbox();     
[2]2422                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[449]2423               
[2]2424                foreach ($mbox_acl as $user => $acl)
2425                {
2426                        if (($user != $this->username) && ($user == $useracl))
2427                        {
2428                                $return[$user] = $acl;
2429                        }
2430                }
2431                return $return;
2432        }
2433
2434        function getacltouser($user)
2435        {
2436                $return = array();
2437                $mbox_stream = $this->open_mbox();
[325]2438                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
2439                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
2440                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
2441                if(substr($user,0,4) != 'user')
[449]2442                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
[325]2443                else
2444                  $mbox_acl = imap_getacl($mbox_stream, $user);
[2]2445                return $mbox_acl[$this->username];
2446        }
[449]2447       
[2]2448
2449        function setaclfromuser($params)
2450        {
2451                $user = $params['user'];
2452                $acl = $params['acl'];
[449]2453               
[2]2454                $mbox_stream = $this->open_mbox();
2455
2456                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2457                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
2458
2459                if (is_array($mailboxes_list))
2460                {
2461                        foreach ($mailboxes_list as $key => $val)
2462                        {
[449]2463                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
2464                                $folder = str_replace("&-", "&", $folder);
[2]2465                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
2466                                {
[449]2467                                        $return = imap_last_error();
[2]2468                                }
2469                        }
2470                }
[449]2471                if (isset($return))
2472                        return $return;
2473                else
2474                        return true;
[2]2475        }
[449]2476       
[51]2477        function download_attachment($msg,$msgno)
2478        {
[449]2479                $array_parts_attachments = array();             
[51]2480                $array_parts_attachments['names'] = '';
2481                include("class.imap_attachment.inc.php");
[449]2482                $imap_attachment = new imap_attachment();               
2483               
[51]2484                if (count($msg->fname[$msgno]) > 0)
2485                {
2486                        $i = 0;
2487                        foreach ($msg->fname[$msgno] as $index=>$fname)
2488                        {
2489                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
2490                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($fname);
2491                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
2492                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
2493                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
2494                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
2495                                $i++;
2496                        }
2497                }
2498                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
2499                return $array_parts_attachments;
[449]2500        }       
[69]2501
2502        function spam($params)
2503        {
2504                $is_spam = $params['spam'];
2505                $folder = $params['folder'];
2506                $mbox_stream = $this->open_mbox($folder);
2507                $msgs_number = explode(',',$params['msgs_number']);
2508
2509                foreach($msgs_number as $msg_number) {
2510                        $header = imap_fetchheader($mbox_stream, imap_msgno($mbox_stream, $msg_number));
2511                        $body = imap_body($mbox_stream, imap_msgno($mbox_stream, $msg_number));
2512                        $msg = $header . $body;
2513                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
[449]2514                        $username = $this->username;
[69]2515                        strtok($email, '@');
2516                        $domain = strtok('@');
2517
[449]2518                        //Encontrar a assinatura do dspam no cabecalho
2519                        $v = explode("\r\n", $header);
2520                        foreach ($v as $linha){
2521                                if (eregi("^X-DSPAM-Signature", $linha)) {
2522                                       
2523                                        $args = explode(" ",$linha);
2524                                        $signature = $args[1];
2525                                }
2526                        }
2527
[69]2528                        // feed dspam
[449]2529                        switch($is_spam){
2530                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
2531                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
2532                        }
2533                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##');
2534                        $cmd = str_replace($tags,array($email,$username,$domain,$signature),$cmd);
[78]2535                        system($cmd);
[69]2536                }
2537                imap_close($mbox_stream);
2538                return false;
2539        }
[535]2540        function get_header($msg_number){
2541                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
2542                if (!is_object($header))
2543                        return false;
2544                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
2545                $pdate = date_parse($header->MailDate);
2546                $header->udate +=  $pdate['zone']*(-60);
2547                return $header;
2548        }
[2]2549}
[278]2550?>
Note: See TracBrowser for help on using the repository browser.