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

Revision 613, 88.9 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #400

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