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

Revision 603, 86.9 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #396

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