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

Revision 591, 87.0 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #395

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