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

Revision 539, 86.6 KB checked in by niltonneto, 16 years ago (diff)

Correção crítica, referente à ordenação de mensagens por remetente. Vide Ticket #360 do Trac.

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