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

Revision 504, 86.3 KB checked in by niltonneto, 16 years ago (diff)

Vide no Trac #344 - Melhorar tratamento de erros (parte 1)

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