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

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

Resolve #398

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