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

Revision 650, 94.2 KB checked in by niltonneto, 15 years ago (diff)

Resolve #278, #346 e #410.

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