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

Revision 569, 86.7 KB checked in by niltonneto, 15 years ago (diff)

Resolve #379

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