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

Revision 2684, 140.5 KB checked in by amuller, 14 years ago (diff)

Ticket #911 - desfazendo erro

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2
3/***************************************************************************
4        * Expresso Livre                                                           *
5        * http://www.expressolivre.org                                             *
6        * --------------------------------------------                             *
7        *  This program is free software; you can redistribute it and/or modify it *
8        *  under the terms of the GNU General Public License as published by the   *
9        *  Free Software Foundation; either version 2 of the License, or (at your  *
10        *  option) any later version.                                              *
11        \**************************************************************************/
12
13include_once("class.functions.inc.php");
14include_once("class.ldap_functions.inc.php");
15include_once("class.exporteml.inc.php");
16
17class imap_functions
18{
19        var $public_functions = array
20        (
21                'get_range_msgs'                                => True,
22                'get_info_msg'                                  => True,
23                'get_info_msgs'                                 => True,
24                'get_folders_list'                              => True,
25                'import_msgs'                                   => True,
26                'msgs_to_archive'                               => True
27        );
28
29        var $ldap;
30        var $mbox;
31        var $email_server;
32        var $cert;
33        var $preferences;
34        var $has_cid;
35        var $imap_options = '';
36        var $functions;
37        var $foldersLimit;
38        var $imap_sentfolder;
39        function load_session_vars(){
40                $this->foldersLimit = $_SESSION['phpgw_info']['expressomail']['max_folders_to_show']; //Limit of folders (mailboxes) user can see
41                $this->email_server = $_SESSION['phpgw_info']['expressomail']['email_server'];
42                $this->cert = $_SESSION['phpgw_info']['expressomail']['server']['certificado'];
43                $this->server_files_dir = $_SESSION['phpgw_info']['expressomail']['server']['files_dir'];
44
45                $this->username  = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
46                $this->password  = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
47                $this->account_id = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];
48                $this->email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
49                $this->fullname = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
50                $this->lang = $_SESSION['phpgw_info']['expressomail']['user']['preferences']['common']['lang'];
51                $this->session_ip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
52                $this->shared_mailboxes = $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'];
53
54                $this->command_for_ham = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham'];
55                $this->command_for_spam = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam'];
56                $this->enable_log_messages = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'];
57
58                $this->preferences = $_SESSION['phpgw_info']['user']['preferences']['expressoMail'];
59                $this->session_id = $_SESSION[ 'phpgw_session' ][ 'session_id' ];
60
61                session_write_close();
62        }
63        function imap_functions (){
64                $this->load_session_vars();
65                $this->functions          = new functions();
66                $this->imap_sentfolder = $this->email_server['imapDefaultSentFolder']  ? $this->email_server['imapDefaultSentFolder'] : str_replace("*","", $this->functions->getLang("Sent"));
67                $this->has_cid = false;
68
69                if ($this->email_server['imapTLSEncryption'] == 'yes')
70                {
71                        $this->imap_options = '/tls/novalidate-cert';
72                }
73                else
74                {
75                        $this->imap_options = '/notls/novalidate-cert';
76                }
77        }
78        // BEGIN of functions.
79        function open_mbox($folder = False)
80        {
81                if (is_resource($this->mbox))
82                        return $this->mbox;
83                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
84                $this->mbox = @imap_open("{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
85                return $this->mbox;
86         }
87
88        function parse_error($error){
89                // This error is returned from Imap.
90                if(strstr($error,'Connection refused')) {
91                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
92                }
93                // This error is returned from Postfix.
94                elseif(strstr($error,'message file too big')) {
95                        return str_replace("%1",$this->preferences['max_attachment_size'],$this->functions->getLang('The size of this message has exceeded  the limit (%1B).'));
96                }
97                elseif(strstr($error,'virus')) {
98                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
99                }
100                // This condition verifies if SESSION is expired.
101                elseif(!count( $this->email_server ))
102                        return "nosession";
103
104                return $error;
105        }
106
107        function get_range_msgs2($params)
108        {
109                $folder = $params['folder'];
110                $msg_range_begin = $params['msg_range_begin'];
111                $msg_range_end = $params['msg_range_end'];
112                $sort_box_type = $params['sort_box_type'];
113                $sort_box_reverse = $params['sort_box_reverse'];
114                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
115                $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
116
117                $return = array();
118                $i = 0;
119                $num_msgs = imap_num_msg($this->mbox);
120                if(is_array($sort_array_msg)){
121                        foreach($sort_array_msg as $msg_number => $value)
122                        {
123                                $temp = $this->get_info_head_msg($msg_number);
124                                $temp['msg_sample'] = $this->get_msg_sample($msg_number);
125                                if(!$temp)
126                                {
127                                        return false;
128                                }
129
130                                $return[$i] = $temp;
131                                $i++;
132                        }
133                }
134                $return['num_msgs'] = $num_msgs;
135
136                return $return;
137        }
138
139        function get_info_head_msg($msg_number) {
140                $head_array = array();
141                include_once("class.imap_attachment.inc.php");
142                $imap_attachment = new imap_attachment();
143
144
145
146                /*Como eu preciso do atributo Importance para saber se o email é
147                 * importante ou não, uso abaixo a função imap_fetchheader e busco
148                 * o atributo importance nela. Isso faz com que eu acesse o cabeçalho
149                 * duas vezes e de duas formas diferentes, mas em contrapartida, eu
150                 * não preciso reimplementar o método utilizando o fetchheader.
151                 * Como as mensagens são renderizadas em um número pequeno por vez,
152                 * não parece ter perda considerável de performance.
153                 */
154
155                $tempHeader = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
156                $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
157
158                // Reimplemenatado código para identificação dos e-mails assinados e cifrados
159                // no método getMessageType(). Mário César Kolling <mario.kolling@serpro.gov.br>
160                $head_array['ContentType'] = $this->getMessageType($msg_number, $tempHeader);
161                $head_array['Importance'] = $flag==0?"Normal":$importance[1];
162
163
164                $header = $this->get_header($msg_number);
165                if (!is_object($header))
166                        return false;
167                $head_array['Recent'] = $header->Recent;
168                $head_array['Unseen'] = $header->Unseen;
169                if($header->Answered =='A' && $header->Draft == 'X'){
170                        $head_array['Forwarded'] = 'F';
171                }
172                else {
173                        $head_array['Answered'] = $header->Answered;
174                        $head_array['Draft']    = $header->Draft;
175                }
176                $head_array['Deleted'] = $header->Deleted;
177                $head_array['Flagged'] = $header->Flagged;
178
179                $head_array['msg_number'] = $msg_number;
180                //$head_array['msg_folder'] = $folder;
181
182                $date_msg = gmdate("d/m/Y",$header->udate);
183                if ( date("d/m/Y") == $date_msg)
184                        $head_array['udate'] = gmdate("H:i",$header->udate);
185                else
186                {
187                        $head_array['udate'] = $date_msg;
188                        if ( date("d/m/Y", time() - 86400) == gmdate("d/m/Y",$header->udate) )
189                                $head_array['udate'] = $this -> functions -> getLang( 'Yesterday' );
190                        if ( date("d/m/Y", time() - 172800) == gmdate("d/m/Y",$header->udate) )
191                                $head_array['udate'] = $this -> functions -> getLang( gmdate("l",$header->udate) );
192                        if ( date("d/m/Y", time() - 259200) == gmdate("d/m/Y",$header->udate) )
193                                $head_array['udate'] = $this -> functions -> getLang( gmdate("l",$header->udate) );
194                }
195
196                $head_array['aux_date'] = $date_msg; //Auxiliar apenas para mensagens locais.
197
198                $from = $header->from;
199                $head_array['from'] = array();
200                $head_array['from']['name'] = ( isset( $from[0]->personal ) ) ? $this->decode_string($from[0]->personal) : NULL;
201                $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
202                if(!$head_array['from']['name'])
203                        $head_array['from']['name'] = $head_array['from']['email'];
204                $to = $header->to;
205                $head_array['to'] = array();
206                $tmp = ( isset( $to[0]->personal ) ) ? imap_mime_header_decode($to[0]->personal) : NULL;
207                $head_array['to']['name'] = ( isset( $tmp[0]->text ) ) ? $this->decode_string($this->decode_string($tmp[0]->text)) : NULL;
208                $head_array['to']['email'] = ( isset( $to[0]->mailbox ) ) ? ( $this->decode_string($to[0]->mailbox) . "@" . ( ( isset( $to[0]->host ) ) ? $to[0]->host : '' ) ) : NULL;
209                if(!$head_array['to']['name'])
210                        $head_array['to']['name'] = $head_array['to']['email'];
211                $head_array['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
212
213                $head_array['Size'] = $header->Size;
214
215                $head_array['attachment'] = array();
216                $head_array['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
217
218                return $head_array;
219        }
220
221        function decode_string($string)
222        {
223
224                if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
225                {
226                        $return = '';
227                        $tmp = imap_mime_header_decode($string);
228                        foreach ($tmp as $tmp1)
229                                $return .= $this->htmlspecialchars_encode($tmp1->text);
230
231                        return $return;
232                }
233                else if (strpos(strtolower($string), '=?utf-8') !== false)
234                {
235                        $elements = imap_mime_header_decode($string);
236
237                        for($i = 0;$i < count($elements);$i++)
238                        {
239                                $charset = strtolower($elements[$i]->charset);
240                                $text = $elements[$i]->text;
241
242                                if(!strcasecmp($charset, "utf-8") || !strcasecmp($charset, "utf-7"))
243                                {
244                                $decoded .= $this->functions->utf8_to_ncr($text);
245                        }
246                                else
247                                {
248                                        if( strcasecmp($charset,"default") )
249                                                $decoded .= $this->htmlspecialchars_encode(iconv($charset, "iso-8859-1", $text));
250                                        else
251                                                $decoded .= $this->htmlspecialchars_encode($text);
252                                }
253                        }
254                        return $decoded;
255                }
256                else
257                        return $this->htmlspecialchars_encode($string);
258        }
259        /**
260        * Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
261        * com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
262        */
263        function import_msgs($params) {
264                if(!$this->mbox)
265                        $this->mbox = $this->open_mbox();
266
267                if( preg_match('/local_/',$params["folder"]) )
268                {
269                        // PLEASE, BE CAREFULL!!! YOU SHOULD USE EMAIL CONFIGURATION VALUES (EMAILADMIN MODULE)
270                        $tmp_box = mb_convert_encoding('INBOX'.$this->email_server['imapDelimiter'].$this->email_server['imapDefaultTrashFolder'].$this->email_server['imapDelimiter'].'tmpMoveToLocal', "UTF7-IMAP", "UTF-8");
271                        if ( ! imap_createmailbox( $this -> mbox,"{".$this -> imap_server."}$tmp_box" ) )
272                                return $this->functions->getLang( 'Import to Local : fail...' );
273                        imap_reopen($this->mbox, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}".$tmp_box);
274                        $params["folder"] = $tmp_box;
275                }
276                $errors = array();
277                $invalid_format = false;
278                $filename = $params['FILES'][0]['name'];
279                $params["folder"] = mb_convert_encoding($params["folder"], "UTF7-IMAP","ISO_8859-1");
280                $quota = imap_get_quotaroot($this->mbox, $params["folder"]);
281                if((($quota['limit'] - $quota['usage'])*1024) <= $params['FILES'][0]['size']){
282                        return array( 'error' => $this->functions->getLang("fail in import:").
283                                                        " ".$this->functions->getLang("Over quota"));
284                }
285                if(substr($filename,strlen($filename)-4)==".zip") {
286                        $zip = zip_open($params['FILES'][0]['tmp_name']);
287
288                        if ($zip) {
289                                while ($zip_entry = zip_read($zip)) {
290
291                                        if (zip_entry_open($zip, $zip_entry, "r")) {
292                                                $email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
293                                                $status = @imap_append($this->mbox,
294                                                                "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}".$params["folder"],
295                                                                        $email
296                                                                        );
297                                                if(!$status)
298                                                        array_push($errors,zip_entry_name($zip_entry));
299                                                zip_entry_close($zip_entry);
300                                        }
301                                }
302                                zip_close($zip);
303                        }
304
305                        if ( isset( $tmp_box ) && ! sizeof( $errors ) )
306                        {
307
308                                $mc = imap_check($this->mbox);
309
310                                $result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 );
311
312                                $ids = array( );
313                                foreach ($result as $overview)
314                                        $ids[ ] = $overview -> uid;
315
316                                return implode( ',', $ids );
317                        }
318                        }
319                else if(substr($filename,strlen($filename)-4)==".eml") {
320                        $email = implode("",file($params['FILES'][0]['tmp_name']));
321                        $status = @imap_append($this->mbox,
322                                                                "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}".$params["folder"],
323                                                                        $email
324                                                                        );
325                        if(!$status){
326                                array_push($errors,zip_entry_name($zip_entry));
327                                zip_entry_close($zip_entry);
328                        }
329                }
330                else
331                {
332                        if ( isset( $tmp_box ) )
333                                imap_deletemailbox( $this->mbox,"{".$this -> imap_server."}$tmp_box" );
334
335                        return array("error" => $this->functions->getLang("wrong file format"));
336                        $invalid_format = true;
337                }
338
339                if(!$invalid_format) {
340                        if(count($errors)>0) {
341                                $message = $this->functions->getLang("fail in import:")."\n";
342                                foreach($errors as $arquivo) {
343                                        $message.=$arquivo."\n";
344                                }
345                                return array("error" => $message);
346                        }
347                        else
348                                return $this->functions->getLang("The import was executed successfully.");
349                }
350        }
351        /*
352                Remove os anexos de uma mensagem. A estratégia para isso é criar uma mensagem nova sem os anexos, mantendo apenas
353                a primeira parte do e-mail, que é o texto, sem anexos.
354                O método considera que o email é multpart.
355        */
356        function remove_attachments($params) {
357                include_once("class.message_components.inc.php");
358                if(!$this->mbox || !is_resource($this->mbox))
359                        $this->mbox = $this->open_mbox($params["folder"]);
360                $return["status"] = true;
361                $header = "";
362
363                $headertemp = explode("\n",imap_fetchheader($this->mbox, imap_msgno($this->mbox, $params["msg_num"])));
364                foreach($headertemp as $head) {//Se eu colocar todo o header do email dá pau no append, então procuro apenas o que interessa.
365                        $head1 = explode(":",$head);
366                        if ( (strtoupper($head1[0]) == "TO") ||
367                                        (strtoupper($head1[0]) == "FROM") ||
368                                        (strtoupper($head1[0]) == "SUBJECT") ||
369                                        (strtoupper($head1[0]) == "DATE") )
370                                $header .= $head."\r\n";
371                }
372
373                $msg = &new message_components($this->mbox);
374                $msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
375                                                             Então uso essa classe para verificar a codificação e o charset,
376                                                             para que o método decodeBody do expresso possa trazer tudo certinho*/
377
378                $status = imap_append($this->mbox,
379                                "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}".$params["folder"],
380                                        $header.
381                                        "\r\n".
382                                        str_replace("\n","\r\n",$this->decodeBody(
383                                                        imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),"1"),
384                                                        $msg->encoding[$params["msg_num"]][0], $msg->charset[$params["msg_num"]][0]
385                                                        )
386                                        ), "\\Seen"); //Append do novo email, só com header e conteúdo sem anexos.
387
388                if(!$status)
389                {
390                        $return["status"] = false;
391                        $return["msg"] = lang("error appending mail on delete attachments");
392                }
393                else
394                {
395                        $status = imap_status($this->mbox, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort']."}".$params['folder'], SA_UIDNEXT);
396                        $return['msg_no'] = $status->uidnext - 1;
397                        imap_delete($this->mbox, imap_msgno($this->mbox, $params["msg_num"]));
398                        imap_expunge($this->mbox);
399                }
400
401                return $return;
402
403        }
404       
405        function msgs_to_archive($params) {
406               
407                $folder = $params['folder'];
408                $all_ids = $this-> get_msgs($folder, 'SORTARRIVAL', false, 0,-1,-1);
409
410                $messages_not_to_copy = explode(",",$params['mails']);
411                $ids = array();
412               
413                $cont = 0;
414               
415                foreach($all_ids as $each_id=>$value) {
416                        if(!in_array($each_id,$messages_not_to_copy)) {
417                                array_push($ids,$each_id);
418                                $cont++;
419                        }
420                        if($cont>=100)
421                                break;
422                }
423
424                if (empty($ids))
425                        return array();
426
427                $params = array("folder"=>$folder,"msgs_number"=>implode(",",$ids));
428               
429               
430                return $this->get_info_msgs($params);
431               
432               
433        }
434
435/**
436         *
437         * @return
438         * @param $params Object
439         */
440        function get_info_msgs($params) {
441                include_once("class.exporteml.inc.php");
442                $return = array();
443                $new_params = array();
444                $attach_params = array();
445                $new_params["msg_folder"]=$params["folder"];
446                $attach_params["folder"] = $params["folder"];
447                $msgs = explode(",",$params["msgs_number"]);
448                $exporteml = new ExportEml();
449                $unseen_msgs = array();
450                foreach($msgs as $msg_number) {
451                        $new_params["msg_number"] = $msg_number;
452                        //ini_set("display_errors","1");
453                        $msg_info = $this->get_info_msg($new_params);
454
455                        $this->mbox = $this->open_mbox($params['folder']); //Não sei porque, mas se não abrir de novo a caixa dá erro.
456                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
457
458                        $attach_params["num_msg"] = $msg_number;
459                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
460                        $msg_info['url_export_file'] = $exporteml->export_to_archive($msg_number,$params["folder"]);
461                        imap_close($this->mbox);
462                        $this->mbox=false;
463                        array_push($return,$msg_info);
464
465                        if($msg_info['Unseen'] == "U" || $msg_info['Recent'] == "N"){
466                                        array_push($unseen_msgs,$msg_number);
467                        }
468                }
469                if($unseen_msgs){
470                        $msgs_list = implode(",",$unseen_msgs);
471                        $array_msgs = array('folder' => $new_params["msg_folder"], "msgs_to_set" => $msgs_list, "flag" => "unseen");
472                        $this->set_messages_flag($array_msgs);
473                }
474
475                return $return;
476        }
477
478        function get_info_msg($params)
479        {
480                $return = array();
481                $msg_number = $params['msg_number'];
482                if(@preg_match('(.+)(_[a-zA-Z0-9]+)',$msg_number,$matches)) { //Verifies if it comes from a tab diferent of the main one.
483                        $msg_number = $matches[1];
484                        $plus_id = $matches[2];
485                }
486                else {
487                        $plus_id = '';
488                }
489                $msg_folder = urldecode($params['msg_folder']);
490
491                if(!$this->mbox || !is_resource($this->mbox))
492                        $this->mbox = $this->open_mbox($msg_folder);
493
494                $header = $this->get_header($msg_number);
495                if (!$header) {
496                        $return['status_get_msg_info'] = "false";
497                        return $return;
498                }
499
500                $header_ = imap_fetchheader($this->mbox, $msg_number, FT_UID);
501
502                $return_get_body = $this->get_body_msg($msg_number, $msg_folder);
503               
504                $body = $return_get_body['body'];
505                //Remoção de tags <span></span> para correção de erro no firefox
506                $body = mb_eregi_replace("<span><span>","",$body);
507                $body = mb_eregi_replace("</span></span>","",$body);
508
509                if($return_get_body['body']=='isCripted'){
510                        $exporteml = new ExportEml();
511                        $return['source']=$exporteml->export_msg_data($msg_number,$msg_folder);
512                        $return['body']                 = "";
513                        $return['attachments']  =  "";
514                        $return['thumbs']               =  "";
515                        $return['signature']    =  "";
516                        //return $return;
517                }else{
518            $return['body']             = $body;
519            $return['attachments']      = $return_get_body['attachments'];
520            $return['thumbs']           = $return_get_body['thumbs'];
521            $return['signature']        = $return_get_body['signature'];
522                }
523
524                $pattern = '/^[ \t]*Disposition-Notification-To(^:)*:(.+)*@(.+)*$/isUm';
525                if (preg_match($pattern, $header_, $fields))
526                {
527                        preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches);
528                        $return['DispositionNotificationTo'] = "<".$matches[0].">";
529                }
530
531                $return['Recent']       = $header->Recent;
532                $return['Unseen']       = $header->Unseen;
533                $return['Deleted']      = $header->Deleted;
534                $return['Flagged']      = $header->Flagged;
535
536                if($header->Answered =='A' && $header->Draft == 'X'){
537                        $return['Forwarded'] = 'F';
538                }
539
540                else {
541                        $return['Answered']     = $header->Answered;
542                        $return['Draft']        = $header->Draft;
543                }
544
545                $return['msg_number'] = $msg_number.$plus_id;
546                $return['msg_folder'] = $msg_folder;
547
548                $date_msg = gmdate("d/m/Y",$header->udate);
549                if (date("d/m/Y") == $date_msg)
550                        $return['udate'] = gmdate("H:i",$header->udate);
551                else
552                        $return['udate'] = $date_msg;
553
554                $return['msg_day'] = $date_msg;
555                $return['msg_hour'] = gmdate("H:i",$header->udate);
556
557                if (date("d/m/Y") == $date_msg) //no dia
558                {
559                        $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
560                        $return['smalldate'] = gmdate("H:i",$header->udate);
561
562                        $timestamp_now = strtotime("now");
563                        $timestamp_msg_time = $header->udate;
564                        // $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ.
565                        // The variable $timestamp_diff is calculated without MailDate TZ.
566                        $pdate = date_parse($header->MailDate);
567                        $timestamp_diff = $timestamp_now - $timestamp_msg_time  + ($pdate['zone']*(-60));
568
569                        if (gmdate("H",$timestamp_diff) > 0)
570                        {
571                                $return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
572                        }
573                        else
574                        {
575                                if (gmdate("i",$timestamp_diff) == 0){
576                                        $return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
577                                }
578                                elseif (gmdate("i",$timestamp_diff) == 1){
579                                        $return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
580                                }
581                                else{
582                                        $return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
583                                }
584                        }
585                }
586                else{
587                        $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
588                        $return['smalldate'] = gmdate("d/m/Y",$header->udate);
589                }
590
591                $from = $header->from;
592                $return['from'] = array();
593                $return['from']['name'] = $this->decode_string($from[0]->personal);
594                $return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
595                if ($return['from']['name'])
596                {
597                        if (substr($return['from']['name'], 0, 1) == '"')
598                                $return['from']['full'] = $return['from']['name'] . ' ' . '&lt;' . $return['from']['email'] . '&gt;';
599                        else
600                                $return['from']['full'] = '"' . $return['from']['name'] . '" ' . '&lt;' . $return['from']['email'] . '&gt;';
601                }
602                else
603                        $return['from']['full'] = $return['from']['email'];
604
605                // Sender attribute
606                $sender = $header->sender;
607                $return['sender'] = array();
608                $return['sender']['name'] = $this->decode_string($sender[0]->personal);
609                $return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
610                if ($return['sender']['name'])
611                {
612                        if (substr($return['sender']['name'], 0, 1) == '"')
613                                $return['sender']['full'] = $return['sender']['name'] . ' ' . '&lt;' . $return['sender']['email'] . '&gt;';
614                        else
615                                $return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '&lt;' . $return['sender']['email'] . '&gt;';
616                }
617                else
618                        $return['sender']['full'] = $return['sender']['email'];
619
620                if($return['from']['full'] == $return['sender']['full'])
621                        $return['sender'] = null;
622                $to = $header->to;
623                $return['toaddress2'] = "";
624                if (!empty($to))
625                {
626                        foreach ($to as $tmp)
627                        {
628                                if (!empty($tmp->personal))
629                                {
630                                        $personal_tmp = imap_mime_header_decode($tmp->personal);
631                                        $return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
632                                        $return['toaddress2'] .= " ";
633                                        $return['toaddress2'] .= "&lt;";
634                                        if ($tmp->host != 'unspecified-domain')
635                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
636                                        else
637                                                $return['toaddress2'] .= $tmp->mailbox;
638                                        $return['toaddress2'] .= "&gt;";
639                                        $return['toaddress2'] .= ", ";
640                                }
641                                else
642                                {
643                                        if ($tmp->host != 'unspecified-domain')
644                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
645                                        else
646                                                $return['toaddress2'] .= $tmp->mailbox;
647                                        $return['toaddress2'] .= ", ";
648                                }
649                        }
650                        $return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
651                }
652                else
653                {
654                        $return['toaddress2'] = "&lt;Empty&gt;";
655                }
656
657                $cc = $header->cc;
658                $return['cc'] = "";
659                if (!empty($cc))
660                {
661                        foreach ($cc as $tmp_cc)
662                        {
663                                if (!empty($tmp_cc->personal))
664                                {
665                                        $personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
666                                        $return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
667                                        $return['cc'] .= " ";
668                                        $return['cc'] .= "&lt;";
669                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
670                                        $return['cc'] .= "&gt;";
671                                        $return['cc'] .= ", ";
672                                }
673                                else
674                                {
675                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
676                                        $return['cc'] .= ", ";
677                                }
678                        }
679                        $return['cc'] = $this->del_last_two_caracters($return['cc']);
680                }
681                else
682                {
683                        $return['cc'] = "";
684                }
685
686                ##
687                # @AUTHOR Rodrigo Souza dos Santos
688                # @DATE 2008/09/12
689                # @BRIEF Adding the BCC field.
690                ##
691                $bcc = $header->bcc;
692                $return['bcc'] = "";
693                if (!empty($bcc))
694                {
695                        foreach ($bcc as $tmp_bcc)
696                        {
697                                if (!empty($tmp_bcc->personal))
698                                {
699                                        $personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
700                                        $return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
701                                        $return['bcc'] .= " ";
702                                        $return['bcc'] .= "&lt;";
703                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
704                                        $return['bcc'] .= "&gt;";
705                                        $return['bcc'] .= ", ";
706                                }
707                                else
708                                {
709                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
710                                        $return['bcc'] .= ", ";
711                                }
712                        }
713                        $return['bcc'] = $this->del_last_two_caracters($return['bcc']);
714                }
715                else
716                {
717                        $return['bcc'] = "";
718                }
719
720                $reply_to = $header->reply_to;
721                $return['reply_to'] = "";
722                if (is_object($reply_to[0]))
723                {
724                        if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
725                        {
726                                if (!empty($reply_to[0]->personal))
727                                {
728                                        $personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
729                                        if(!empty($personal_reply_to[0]->text)) {
730                                                $return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
731                                                $return['reply_to'] .= " ";
732                                                $return['reply_to'] .= "&lt;";
733                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
734                                                $return['reply_to'] .= "&gt;";
735                                        }
736                                        else {
737                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
738                                        }
739                                }
740                                else
741                                {
742                                        $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
743                                }
744                        }
745                }
746                $return['reply_to'] = $this->decode_string($return['reply_to']);
747                $return['subject'] = $this->decode_string($header->fetchsubject);
748                $return['Size'] = $header->Size;
749                $return['reply_toaddress'] = $header->reply_toaddress;
750
751                //All this is to help in local messages
752                $return['timestamp'] = $header->udate_original;
753                $return['login'] = $this->account_id;
754                $return['reply_toaddress'] = $header->reply_toaddress;
755                return $return;
756        }
757
758        function get_msg_sample($msg_number)
759        {
760                $return = "";
761                if( (!isset($this->preferences['preview_msg_subject']) || ($this->preferences['preview_msg_subject'] != "1")) &&
762                    (!isset($this->preferences['preview_msg_tip']    ) || ($this->preferences['preview_msg_tip']     != "1")) )
763                {
764                        $return['body'] = "";
765                        return $return;
766                }
767
768                include_once("class.message_components.inc.php");
769                $msg = &new message_components($this->mbox);
770                $msg->fetch_structure($msg_number);     
771
772
773                if(!$msg->structure[$msg_number]->parts)
774                {
775                        $content = '';
776                        if (strtolower($msg->structure[$msg_number]->subtype) == "plain" || strtolower($msg->structure[$msg_number]->subtype) == "html")
777                        {
778                                $content = $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID|FT_PEEK), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
779                        }
780                }
781                else
782                {
783                        foreach($msg->pid[$msg_number] as $values => $msg_part)
784                        {
785
786                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
787                                if($file_type == "text/plain" || $file_type == "text/html") {
788                                        $content = $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID|FT_PEEK), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
789                                        break;
790                                }
791                        }
792                }
793                $content = $this->replace_special_characters($content);
794                $tags_replace = array("<br>","<br/>","<br />");
795                $content = str_replace($tags_replace," ", $content);
796                $content = strip_tags($content);
797                $content = str_replace(array("{","}","&nbsp;"), " ", $content);
798                $content = trim($content);
799                $content = substr($content,0,300);
800                $content != "" ? $return['body'] = " - " . $content: $return['body'] = "";
801                return $return;
802        }
803
804        function get_body_msg($msg_number, $msg_folder)
805        {
806                include_once("class.message_components.inc.php");
807                $msg = &new message_components($this->mbox);
808                $msg->fetch_structure($msg_number);
809                $return = array();
810                $return['attachments'] = $this-> download_attachment($msg,$msg_number);
811                if(!$this->has_cid)
812                {
813                        $return['thumbs']  = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
814                        $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
815                }
816
817                if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
818                {
819                        if(strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime'){
820                                $return['body']='isCripted';
821                                return $return;
822                        }
823
824                        $attachment = array(); //No attachments
825
826                        if(strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime'){
827                                $return['body']='isCripted';
828                                return $return;
829                        }
830
831                        $content = $this->decodeBody(
832                                imap_body( $this -> mbox, $msg_number, FT_UID ),
833                                $msg -> encoding[ $msg_number ][ 0 ],
834                                $msg -> charset[ $msg_number ][ 0 ]
835                        );
836
837                        if ( strtolower( $msg -> structure[ $msg_number ] -> subtype ) == 'plain' )
838                        {
839                                $content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content );
840                                $content = nl2br( htmlentities( $content ) );
841                                $content = $this -> replace_links( $content );
842                                $content = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $content );
843                                $content = '<span style="font-family: monospace">' . $content . '</span>';
844
845                                $return[ 'body' ] = $content;
846
847                                return $return;
848                        }
849                }
850                else
851                { //Complicated message, multiple parts
852                        $html_body = '';
853                        $content = '';
854                        $has_multipart = true;
855                        $this->has_cid = false;
856
857                        if (strtolower($msg->structure[$msg_number]->subtype) == "related")
858                                $this->has_cid = true;
859
860                        if (strtolower($msg->structure[$msg_number]->subtype) == "alternative") {
861                                $show_only_html = false;
862                                foreach($msg->pid[$msg_number] as $values => $msg_part) {
863                                        $file_type = strtolower($msg->file_type[$msg_number][$values]);
864                                        if($file_type == "text/html")
865                                                $show_only_html = true;
866                                }
867                        }
868                        else
869                                $show_only_html = false;
870
871                        foreach($msg->pid[$msg_number] as $values => $msg_part)
872                        {
873
874                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
875                                if($file_type == "message/rfc822")
876                                        $has_multipart = false;
877
878                                if($file_type == "multipart/alternative")
879                                        $has_multipart = false;
880
881                                if(($file_type == "text/plain"
882                                        || $file_type == "text/html")
883                                        && $file_type != 'attachment')
884                                {
885                                        if($file_type == "text/plain" && !$show_only_html && $has_multipart)
886                                        {
887                                                // if TXT file size > 100kb, then it will not expand.
888                                                if(!($file_type == "text/plain" && $msg->fsize[$msg_number][$values] > 102400)) {
889                                                        $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])));
890                                                }
891                                        }
892                                        // if HTML attachment file size > 300kb, then it will not expand.
893                                        else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < 307200)
894                                        {
895                                                $content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
896                                                $show_only_html = true;
897                                        }
898                                }
899                                else if($file_type == "message/delivery-status"){
900                                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
901                                        $content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));
902
903                                }
904                                else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
905
906                                        include_once("class.imap_attachment.inc.php");
907                                        $att = new imap_attachment();
908                                        $attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
909                                        if($attachments['number_attachments'] > 0) {
910                                                foreach($attachments ['attachment'] as $index => $attachment)
911                                                {
912                                                        if ( in_array( strtolower( $attachment[ 'type' ] ), array( 'delivery-status', 'rfc822', 'rfc822-headers', 'plain' ) ) )
913                                                        {
914                                                                $obj = imap_rfc822_parse_headers( imap_fetchbody( $this -> mbox, $msg_number, $msg_part, FT_UID ), $msg -> encoding[ $msg_number ][ $values ] );
915
916                                                                $content .= '<hr align="left" width="95%" style="border:1px solid #DCDCDC">';
917                                                                $content .= '<br><table  style="margin:2px;border:1px solid black;background:#EAEAEA">';
918
919                                                                $content .= '<tr><td><b>' . $this->functions->getLang("Subject")
920                                                                        . ':</b></td><td>' .$this->decode_string($obj->subject) . '</td></tr>';
921
922                                                                $content .= '<tr><td><b>' . $this -> functions -> getLang( 'From' ) . ':</b></td><td>'
923                                                                        . $this -> replace_links( $this -> decode_string( $obj -> from[ 0 ] -> mailbox . '@' . $obj -> from[ 0 ] -> host) )
924                                                                        . '</td></tr>';
925
926                                                                $content .= '<tr><td><b>' . $this->functions->getLang("Date") . ':</b></td><td>' . $obj->date . '</td></tr>';
927
928                                                                $content .= '<tr><td><b>' . $this -> functions -> getLang( 'TO' ) . ':</b></td><td>'
929                                                                        . $this -> replace_links( $this -> decode_string( $obj -> to[ 0 ] -> mailbox . '@' . $obj -> to[ 0 ] -> host ) )
930                                                                        . '</td></tr>';
931
932                                                                if ( $obj->cc )
933                                                                        $content .= '<tr><td><b>' . $this -> functions -> getLang( 'CC' ) . ':</b></td><td>'
934                                                                                . $this -> replace_links( $this -> decode_string( $obj -> cc[ 0 ] -> mailbox . '@' . $obj -> cc[ 0 ] -> host ) )
935                                                                                . '</td></tr>';
936
937                                                                $content .= '</table><br>';
938
939
940                                                                $id = ( ( strtolower( $attachment[ 'type' ] ) == 'delivery-status' ) ? false : true );
941                                                                if ( strtolower( $msg->structure[$msg_number]->parts[1]->parts[0]->subtype ) == 'plain' )
942                                                                {
943                                                                        $id = !$id;
944                                                                        if ( $msg->structure[$msg_number]->parts[1]->parts[0]->encoding == 4 )
945                                                                                $msg->encoding[ $msg_number ][ $values ] = 'quoted-printable';
946                                                                }
947
948                                                                $body = $this->decodeBody(
949                                                                        imap_fetchbody(
950                                                                                $this->mbox,
951                                                                                $msg_number,
952                                                                                ( $attachment['part_in_msg'] + ( ( int ) $id ) ) . ".1",
953                                                                                FT_UID
954                                                                        ),
955                                                                        $msg->encoding[ $msg_number ][ $values ],
956                                                                        $msg->charset[ $msg_number ][ $values ]
957                                                                );
958
959                                                                if ( strtolower( $msg->structure[$msg_number]->parts[1]->parts[0]->subtype ) == 'plain' )
960                                                                {
961                                                                        $body = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $body );
962                                                                        $body = nl2br( htmlentities( $body ) );
963                                                                        $body = $this -> replace_links( $body );
964                                                                        $body = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $body );
965                                                                        $body = '<span style="font-family: monospace">' . $body . '</span>';
966                                                                }
967
968                                                                $content .= $body;
969                                                                break;
970                                                        }
971                                                }
972                                        }
973                                }
974                        }
975                        if($file_type == "text/plain" && ($show_only_html &&  $msg_part == 1) ||  (!$show_only_html &&  $msg_part == 3)){
976                                if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" &&  $msg_part == 1)
977                                        $content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
978                                else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
979                                        $content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));
980                        }
981                }
982                // Force message with flag Seen (imap_fetchbody not works correctly)
983                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");
984                $this->set_messages_flag($params);
985
986                $content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
987                $content = $this->replace_special_characters($content);
988                $return['body'] = $content;
989
990                return $return;
991        }
992
993        function htmlfilter($body)
994        {
995                require_once('htmlfilter.inc');
996
997                $tag_list = Array(
998                                false,
999                                'blink',
1000                                'object',
1001                                'meta',
1002                                'html',
1003                                'link',
1004                                'frame',
1005                                'iframe',
1006                                'layer',
1007                                'ilayer',
1008                                'plaintext'
1009                );
1010
1011                /**
1012                * A very exclusive set:
1013                */
1014                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
1015                $rm_tags_with_content = Array(
1016                                'script',
1017                                'style',
1018                                'applet',
1019                                'embed',
1020                                'head',
1021                                'frameset',
1022                                'xml',
1023                                'xmp'
1024                );
1025
1026                $self_closing_tags =  Array(
1027                                'img',
1028                                'br',
1029                                'hr',
1030                                'input'
1031                );
1032
1033                $force_tag_closing = true;
1034
1035                $rm_attnames = Array(
1036                        '/.*/' =>
1037                                Array(
1038                                        '/target/i',
1039                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
1040                                        '/^dynsrc/i',
1041                                        '/^datasrc/i',
1042                                        '/^data.*/i',
1043                                        '/^lowsrc/i'
1044                                )
1045                );
1046
1047                /**
1048                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
1049                 * some idea of what's going on here. :)
1050                 */
1051
1052                $bad_attvals = Array(
1053                '/.*/' =>
1054                Array(
1055                      '/.*/' =>
1056                              Array(
1057                                Array(
1058                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
1059                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
1060                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
1061                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
1062                                      ),
1063                            Array(
1064                                              '\\1oddjob:\\2\\1',
1065                                          //'\\1uucp:\\2\\1', -> doclinks notes
1066                                      '\\1amaretto:\\2\\1',
1067                                          '\\1round:\\2\\1'
1068                                        )
1069                                    ),
1070
1071                          '/^style/i' =>
1072                              Array(
1073                                        Array(
1074                                          '/expression/i',
1075                                              '/behaviou*r/i',
1076                                          '/binding/i',
1077                                              '/include-source/i',
1078                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
1079                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
1080                                         ),
1081                                        Array(
1082                                          'idiocy',
1083                                              'idiocy',
1084                                          'idiocy',
1085                                              'idiocy',
1086                                          'url(\\1http://securityfocus.com/\\1)',
1087                                          'url(\\1http://securityfocus.com/\\1)'
1088                                         )
1089                                )
1090                          )
1091                    );
1092
1093                $add_attr_to_tag = Array(
1094                                '/^a$/i' => Array('target' => '"_new"')
1095                );
1096
1097
1098                $trusted_body = sanitize($body,
1099                                $tag_list,
1100                                $rm_tags_with_content,
1101                                $self_closing_tags,
1102                                $force_tag_closing,
1103                                $rm_attnames,
1104                                $bad_attvals,
1105                                $add_attr_to_tag
1106                );
1107
1108            return $trusted_body;
1109        }
1110
1111        function decodeBody($body, $encoding, $charset=null)
1112        {
1113                /**
1114                * replace e-mail by anchor.
1115                */
1116                // HTML Filter
1117                //$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);
1118        //$body = str_replace("\r\n", "\n", $body);
1119                if ($encoding == 'quoted-printable')
1120                {
1121                        /*
1122
1123                        for($i=0;$i<256;$i++) {
1124                                $c1=dechex($i);
1125                                if(strlen($c1)==1){$c1="0".$c1;}
1126                                $c1="=".$c1;
1127                                $myqprinta[]=$c1;
1128                                $myqprintb[]=chr($i);
1129                        }
1130                         */
1131                        $body = str_replace($myqprinta,$myqprintb,($body));
1132                        $body = quoted_printable_decode($body);
1133                while (ereg("=\n", $body))
1134                {
1135                        $body = ereg_replace ("=\n", '', $body);
1136                }
1137        }
1138        else if ($encoding == 'base64')
1139        {
1140                $body = base64_decode($body);
1141        }
1142
1143                // All other encodings are returned raw.
1144                if (strtolower($charset) == "utf-8")
1145                        return utf8_decode($body);
1146        else
1147                        return $body;
1148        }
1149
1150        function process_embedded_images($msg, $msgno, $body, $msg_folder)
1151        {
1152                if (count($msg->inline_id[$msgno]) > 0)
1153                {
1154                        foreach ($msg->inline_id[$msgno] as $index => $cid)
1155                        {
1156                                $cid = eregi_replace("<", "", $cid);
1157                                $cid = eregi_replace(">", "", $cid);
1158                                $msg_part = $msg->pid[$msgno][$index];
1159                                //$body = eregi_replace("alt=\"\"", "", $body);
1160                                $body = eregi_replace("<br/>", "", $body);
1161                                $body = str_replace("src=\"cid:".$cid."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1162                                $body = str_replace("src='cid:".$cid."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1163                                $body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1164                        }
1165                }
1166
1167                return $body;
1168        }
1169
1170        function replace_special_characters($body)
1171        {
1172                // Suspected TAGS!
1173                /*$tag_list = Array(
1174                        'blink','object','meta',
1175                        'html','link','frame',
1176                        'iframe','layer','ilayer',
1177                        'plaintext','script','style','img',
1178                        'applet','embed','head',
1179                        'frameset','xml','xmp');
1180                */
1181
1182                // Layout problem: Change html elements
1183                // with absolute position to relate position, CASE INSENSITIVE.
1184                $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
1185
1186                $tag_list = Array('head','blink','object','frame',
1187                        'iframe','layer','ilayer','plaintext','script',
1188                        'applet','embed','frameset','xml','xmp','style');
1189
1190                $blocked_tags = array();
1191                foreach($tag_list as $index => $tag) {
1192                        $new_body = @mb_eregi_replace("<$tag", "<!--$tag", $body);
1193                        if($body != $new_body) {
1194                                $blocked_tags[] = $tag;
1195                        }
1196                        $body = @mb_eregi_replace("</$tag>", "</$tag-->", $new_body);
1197                }
1198                // Malicious Code Remove
1199                $dirtyCodePattern = "/(<([\w]+[\w0-9]*)(.*)on(mouse(move|over|down|up)|load|blur|change|error|click|dblclick|focus|key(down|up|press)|select)([\n\ ]*)=([\n\ ]*)[\"'][^>\"']*[\"']([^>]*)>)(.*)(<\/\\2>)?/misU";
1200                preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
1201                foreach($rest[0] as $i => $val)
1202                        if (!(preg_match("/javascript:window\.open\(\"([^'\"]*)\/index\.php\?menuaction=calendar\.uicalendar\.set_action\&cal_id=([^;'\"]+);?['\"]/i",$rest[1][$i]) && strtoupper($rest[4][$i]) == "CLICK" )) //Calendar events
1203                        $body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
1204
1205                return  "<span>".$this-> replace_links($body);
1206        }
1207
1208        function replace_links( $body )
1209        {
1210                // Domains and IPs addresses found in the text and which is not a link yet should be replaced by one.
1211                // See more informations in www.iana.org
1212                $octets = array(
1213                        'first' => '(2[0-3][0-9]|1[0-9]{2}|[1-9][0-9]?)',
1214                        'middle' => '(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})',
1215                        'last' => '(25[0-4]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)'
1216                );
1217
1218                $ip = "\b{$octets[ 'first' ]}\.({$octets[ 'middle' ]}\.){2}{$octets[ 'last' ]}\b";
1219
1220                $top_level_domains = '(\.(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|as|asia|at|au|aw|ax|az|'
1221                        . 'ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bl|bm|bn|bo|br|bs|bt|bv|bw|by|bz|'
1222                        . 'ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|'
1223                        . 'de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|'
1224                        . 'ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|'
1225                        . 'hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|'
1226                        . 'ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|'
1227                        . 'ma|mc|md|me|mf|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|'
1228                        . 'mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|'
1229                        . 'pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|'
1230                        . 'sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|'
1231                        . 'tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|'
1232                        . 'ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))+\b';
1233
1234                $path = '(?>\/[\w\d\/\.\'\(\)\-\+~?!&#@$%|:;,*=_]+)?';
1235                $port = '(?>:\d{2,5})?';
1236                $domain = '(?>[\w\d_\-]+)';
1237                $subdomain = "(?>{$domain}\.)*";
1238                $protocol = '(?>(http|ftp)(s)?:\/\/)?';
1239                $url = "(?>{$protocol}((?>{$subdomain}{$domain}{$top_level_domains}|{$ip}){$port}{$path}))";
1240
1241                $pattern = "/(<\w[^>]+|[\/\"'@=])?{$url}/";
1242
1243                ini_set( 'pcre.backtrack_limit', 300000 );
1244                /*
1245                // PHP 5.3
1246                $replace = function( $matches )
1247                {
1248                        if ( $matches[ 1 ] )
1249                                return $matches[ 0 ];
1250
1251                        $url = ( $matches[ 2 ] ) ? $matches[ 2 ] : 'http';
1252                        $url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";
1253                        return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";
1254                };
1255                $body = preg_replace_callback( $pattern, $replace, $body );
1256                */
1257
1258                // PHP 5.2.x - Remover assim que possível
1259                $body = preg_replace_callback( $pattern,
1260                        create_function(
1261                                '$matches',
1262                                'if ( $matches[ 1 ] ) return $matches[ 0 ];'
1263                                        . '$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : "http";'
1264                                        . '$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";'
1265                                        . 'return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";'
1266                        ), $body
1267                );
1268                ini_set( 'pcre.backtrack_limit', 100000 );
1269
1270                // E-mail address in the text should create a new e-mail on ExpressoMail
1271                $pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im';
1272                $replacement = '$1<a href="mailto:$2">$2</a>$3';
1273                $body = preg_replace( $pattern, $replacement, $body );
1274
1275                return $body;
1276        }
1277
1278        function get_signature($msg, $msg_number, $msg_folder)
1279        {
1280            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1281                include_once("class.db_functions.inc.php");
1282                foreach ($msg->file_type[$msg_number] as $index => $file_type)
1283                {
1284            $sign = array();
1285                        $temp = $this->get_info_head_msg($msg_number);
1286                        if($temp['ContentType'] =='normal') return $sign;
1287                        $file_type = strtolower($file_type);
1288                        if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
1289                        {
1290                                if ($file_type == 'application/x-pkcs7-signature' || $file_type == 'application/pkcs7-signature')
1291                                {
1292                                        if(!$this->mbox || !is_resource($this->mbox))
1293                                        $this->mbox = $this->open_mbox($msg_folder);
1294
1295                                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
1296
1297                                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1298                                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
1299
1300                                        $certificado = new certificadoB();
1301                                        $validade = $certificado->verificar($imap_msg);
1302
1303                                        if ($certificado->apresentado)
1304                                        {
1305                                                $from = $header->from;
1306                                                foreach ($from as $id => $object) {
1307                                                        $fromname = $object->personal;
1308                                                    $fromaddress = $object->mailbox . "@" . $object->host;
1309                                        }
1310                                                $sign_alert = '';
1311                                                foreach ($certificado->erros_ssl as $item)
1312                                                {
1313                                                        $check_error_msg = $this->functions->getLang($item);
1314                                                        /*
1315                                                         * Desabilite o teste abaixo para mostrar todas as mensagem
1316                                                         * de erro.
1317                                                         */
1318                                                        //if (!strpos($check_error_msg,'*',strlen($check_error_msg-1)))
1319                                                        //{
1320                                                        $sign[] = "<span style=color:red>" . $check_error_msg . " </span>";
1321                                                        //}
1322                                                }
1323                                                if (count($certificado->erros_ssl) < 1)
1324                                                {
1325                                                        $check_msg = $this->functions->getLang('Message untouched') . " ";
1326                                                        if(strtoupper($fromaddress) != strtoupper($certificado->dados['EMAIL']))
1327                                                        {
1328                                                                $check_msg .= $this->functions->getLang('and') . " ";
1329                                                                $check_msg .= $this->functions->getLang('authentic');
1330                                                        }
1331                                                        $sign[] = "<strong>".$check_msg."</strong>";
1332                                                }
1333                                                if(strtoupper($fromaddress) != strtoupper($certificado->dados['EMAIL']))
1334                                                {
1335                                                        $sign[] =       "<span style=color:red>" .
1336                                                                                $this->functions->getLang('message') . " " .
1337                                                                        $this->functions->getLang('with signer different from sender') .
1338                                                                        " </span>";
1339                                                }
1340                                                $sign[] = "<strong>" . $this->functions->getLang('Message signed by: ') . "</strong>" . $certificado->dados['NOME'];
1341                                                $sign[] = "<strong>" . $this->functions->getLang('Certificate email: ') . "</strong>" . $certificado->dados['EMAIL'];
1342                                                $sign[] = "<strong>" . $this->functions->getLang('Mail from: ') . "</strong>" . $fromaddress;
1343                                                $sign[] = "<strong>" . $this->functions->getLang('Certificate Authority: ') . "</strong>" . $certificado->dados['EMISSOR'];
1344                                                $sign[] = "<strong>" . $this->functions->getLang('Validity of certificate: ') . "</strong>" . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
1345                                                $sign[] = "<strong>" . $this->functions->getLang('Message date: ') . "</strong>" . $header->Date;
1346
1347                                            $cert = openssl_x509_parse($certificado->cert_assinante);
1348                                                /*
1349                                                $sign[] = '<table>';
1350                                                $sign[] = '<tr><td colspan=1><b>Expedido para:</b></td></tr>';
1351                                                $sign[] = '<tr><td>Nome Comum (CN) </td><td>' . $cert[subject]['CN'] .  '</td></tr>';
1352                                                $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1353                                                $sign[] = '<tr><td>Data de nascimento </td><td>' . $certificado->dados['NASCIMENTO'] .  '</td></tr>';
1354                                                $sign[] = '<tr><td>CPF </td><td>' . $certificado->dados['CPF'] .  '</td></tr>';
1355                                                $sign[] = '<tr><td>Documento identidade </td><td>' . $certificado->dados['RG'] .  '</td></tr>';
1356                                                $sign[] = '<tr><td>Empresa (O) </td><td>' . $cert[subject]['O'] .  '</td></tr>';
1357                                                $sign[] = '<tr><td>Unidade Organizacional (OU) </td><td>' . $cert[subject]['OU'][0] .  '</td></tr>';
1358                                                //$sign[] = '<tr><td>Numero de serie </td><td>' . $cert['serialNumber'] .  '</td></tr>';
1359                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1360                                                $sign[] = '<tr><td colspan=1><b>Expedido por:</b></td></tr>';
1361                                                $sign[] = '<tr><td>Nome Comum (CN) </td><td>' . $cert[issuer]['CN'] .  '</td></tr>';
1362                                                $sign[] = '<tr><td>Empresa (O) </td><td>' . $cert[issuer]['O'] .  '</td></tr>';
1363                                                $sign[] = '<tr><td>Unidade Organizacional (OU) </td><td>' . $cert[issuer]['OU'][0] .  '</td></tr>';
1364                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1365                                                $sign[] = '<tr><td colspan=1><b>Validade:</b></td></tr>';
1366                                                $H = data_hora($cert[validFrom]);
1367                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1368                                                $sign[] = '<tr><td>Expedido em </td><td>' . $X .  '</td></tr>';
1369                                                $H = data_hora($cert[validTo]);
1370                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1371                                                $sign[] = '<tr><td>Valido ate </td><td>' . $X .  '</td></tr>';
1372                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1373                                                $sign[] = '</table>';
1374                                                */
1375                                                $sign_alert .= 'Expedido para:\n';
1376                                                $sign_alert .= 'Nome Comum (CN)  ' . $cert[subject]['CN'] .  '\n';
1377                                                $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1378                                                $sign_alert .= 'Data de nascimento ' . $X .  '\n';
1379                                                $sign_alert .= 'CPF ' . $certificado->dados['CPF'] .  '\n';
1380                                                $sign_alert .= 'Documento identidade ' . $certificado->dados['RG'] .  '\n';
1381                                                $sign_alert .= 'Empresa (O)  ' . $cert[subject]['O'] .  '\n';
1382                                                $sign_alert .= 'Unidade Organizacional (OU) ' . $cert[subject]['OU'][0] .  '\n';
1383                                                //$sign_alert[] = '<tr><td>Numero de serie </td><td>' . $cert['serialNumber'] .  '</td></tr>';
1384                                                $sign_alert .= '\n';
1385                                                $sign_alert .= 'Expedido por:\n';
1386                                                $sign_alert .= 'Nome Comum (CN) ' . $cert[issuer]['CN'] . '\n';
1387                                                $sign_alert .= 'Empresa (O)  ' . $cert[issuer]['O'] .  '\n';
1388                                                $sign_alert .= 'Unidade Organizacional (OU) ' . $cert[issuer]['OU'][0] .  '\n';
1389                                                $sign_alert .= '\n';
1390                                                $sign_alert .= 'Validade:\n';
1391                                                $H = data_hora($cert[validFrom]);
1392                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1393                                                $sign_alert .= 'Expedido em ' . $X .  '\n';
1394                                                $H = data_hora($cert[validTo]);
1395                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1396                                                $sign_alert .= 'Valido ate ' . $X .  '\n';
1397
1398                                                $sign[] = "<a onclick=\"javascript:alert('" . $sign_alert . "')\"><b><font color=\"#0000FF\">".$this->functions->getLang("More")."...</font></b></a>";
1399                                                $this->db = new db_functions();
1400
1401                                                // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
1402                        if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
1403                            $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
1404                                        }
1405                                     else
1406                                    {
1407                                        $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
1408                                        foreach($certificado->erros_ssl as $item)
1409                                        $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
1410                    }
1411                                }
1412                        }
1413                }
1414                return $sign;
1415        }
1416
1417        function get_thumbs($msg, $msg_number, $msg_folder)
1418        {
1419                $thumbs_array = array();
1420                $i = 0;
1421        foreach ($msg->file_type[$msg_number] as $index => $file_type)
1422        {
1423                $file_type = strtolower($file_type);
1424                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
1425                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
1426                                $id = $msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index];
1427                                $img = "<IMG id='".$id."' style='border:2px solid #fde7bc;padding:5px' title='".$this->functions->getLang("Click here do view (+)")."'src=\"expressoMail1_2/inc/show_thumbs.php?file_type=".$file_type."&msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index].">";
1428                                $href = "<a onMouseDown='save_image(event,this,\"".$file_type."\")' href='#".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' onmouseover=\"zoom_in('".$id."')\" onmouseout=\"zoom_out('".$id."')\" onClick=\"window.open(URL_SERVER+'expressoMail1_2/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>";
1429                                        $thumbs_array[] = $href;
1430                        }
1431                        $i++;
1432                }
1433        }
1434        return $thumbs_array;
1435        }
1436
1437        /*function delete_msg($params)
1438        {
1439                $folder = $params['folder'];
1440                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
1441
1442                $mbox_stream = $this->open_mbox($folder);
1443
1444                foreach ($msgs_to_delete as $msg_number){
1445                        imap_delete($mbox_stream, $msg_number, FT_UID);
1446                }
1447                imap_close($mbox_stream, CL_EXPUNGE);
1448                return $params['msgs_to_delete'];
1449        }*/
1450
1451        // Novo
1452        function delete_msgs($params)
1453        {
1454
1455                $folder = $params['folder'];
1456                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
1457                $msgs_number = explode(",",$params['msgs_number']);
1458                $border_ID = $params['border_ID'];
1459
1460                $return = array();
1461
1462                if ($params['get_previous_msg']){
1463                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1464                        // Fix problem in unserialize function JS.
1465                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1466                }
1467
1468                //$mbox_stream = $this->open_mbox($folder);
1469                $mbox_stream = @imap_open("{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
1470
1471                foreach ($msgs_number as $msg_number)
1472                {
1473                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1474                                $return['msgs_number'][] = $msg_number;
1475                }
1476
1477                $return['folder'] = $folder;
1478                $return['border_ID'] = $border_ID;
1479
1480                if($mbox_stream)
1481                        imap_close($mbox_stream, CL_EXPUNGE);
1482                return $return;
1483        }
1484
1485
1486        function refresh($params)
1487        {
1488                include_once("class.imap_attachment.inc.php");
1489                $imap_attachment = new imap_attachment();
1490                $folder = $params['folder'];
1491                $msg_range_begin = $params['msg_range_begin'];
1492                $msg_range_end = $params['msg_range_end'];
1493                $msgs_existent = $params['msgs_existent'];
1494                $sort_box_type = $params['sort_box_type'];
1495                $sort_box_reverse = $params['sort_box_reverse'];
1496                $msgs_in_the_server = array();
1497                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1498                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1499                $msgs_in_the_server = array_keys($msgs_in_the_server);
1500                if(!count($msgs_in_the_server))
1501                        return array();
1502
1503                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
1504                $msgs_in_the_client = explode(",", $msgs_existent);
1505
1506                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
1507                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
1508
1509                $msgs_to_exec = array();
1510                if ((count($msg_to_insert)) && ($msgs_existent))
1511                {
1512                        foreach($msg_to_insert as $index => $msg_number)
1513                        {
1514                                if ($msgs_in_the_server[$index+1])
1515                                {
1516                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
1517                                        $msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
1518                                }
1519                                else
1520                                {
1521                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
1522                                        $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1523                                }
1524                        }
1525                        ksort($msgs_to_exec);
1526                }
1527                elseif(!$msgs_existent)
1528                {
1529                        foreach($msgs_in_the_server as $index => $msg_number)
1530                        {
1531                                $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1532                        }
1533                }
1534
1535                $return = array();
1536                $i = 0;
1537                foreach($msgs_to_exec as $msg_number => $command)
1538                {
1539                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
1540                        * atributos do cabeçalho. Como eu preciso do atributo Importance
1541                        * para saber se o email é importante ou não, uso abaixo a função
1542                        * imap_fetchheader e busco o atributo importance nela para passar
1543                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1544                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1545                        * não preciso reimplementar o método utilizando o fetchheader.
1546                        * Como na atualização são poucas as mensagens que devem ser renderizadas,
1547                        * a perda em performance é insignificante.
1548                        */
1549            $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1550                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
1551                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
1552
1553                        $msg_sample = $this->get_msg_sample($msg_number);
1554                        $return[$i]['msg_sample'] = $msg_sample;
1555
1556                        $header = $this->get_header($msg_number);
1557                        if (!is_object($header))
1558                                continue;
1559
1560                        $return[$i]['msg_number']       = $msg_number;
1561                        $return[$i]['command']          = $command;
1562
1563                        $return[$i]['msg_folder']       = $folder;
1564            // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1565            $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
1566                        $return[$i]['Recent']           = $header->Recent;
1567                        $return[$i]['Unseen']           = $header->Unseen;
1568                        $return[$i]['Answered']         = $header->Answered;
1569                        $return[$i]['Deleted']          = $header->Deleted;
1570                        $return[$i]['Draft']            = $header->Draft;
1571                        $return[$i]['Flagged']          = $header->Flagged;
1572
1573                        $date_msg = gmdate("d/m/Y",$header->udate);
1574                        if (gmdate("d/m/Y") == $date_msg)
1575                                $return[$i]['udate'] = gmdate("H:i",$header->udate);
1576                        else
1577                                $return[$i]['udate'] = $date_msg;
1578
1579                        $from = $header->from;
1580                        $return[$i]['from'] = array();
1581                        $tmp = imap_mime_header_decode($from[0]->personal);
1582                        $return[$i]['from']['name'] = $tmp[0]->text;
1583                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
1584                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
1585                        if(!$return[$i]['from']['name'])
1586                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
1587
1588                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1589                        $return[$i]['toaddress'] = '';
1590                        foreach ($toaddress as $tmp)
1591                                $return[$i]['toaddress'] .= $tmp->text;*/
1592                        $to = $header->to;
1593                        $return[$i]['to'] = array();
1594                        $tmp = imap_mime_header_decode($to[0]->personal);
1595                        $return[$i]['to']['name'] = $tmp[0]->text;
1596                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1597                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
1598
1599                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1600
1601                        $return[$i]['Size'] = $header->Size;
1602                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
1603
1604                        $return[$i]['attachment'] = array();
1605                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
1606                        $i++;
1607                }
1608                $return['new_msgs'] = imap_num_recent($this->mbox);
1609                $return['msgs_to_delete'] = $msg_to_delete;
1610                if($this->mbox && is_resource($this->mbox))
1611                        imap_close($this->mbox);
1612
1613                return $return;
1614        }
1615
1616     /**
1617     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1618     * assinado ou cifrado.
1619     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1620     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1621     * @param $msg_number O número da mesagem
1622     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1623     */
1624    function getMessageType($msg_number, $headers = false){
1625
1626            $contentType = "normal";
1627            if (!$headers){
1628                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1629            }
1630            //$header2 = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1631            if (preg_match("/Content-Type:.*pkcs7-signature/i", $headers) == 1){
1632                $contentType = "signature";
1633            } else if (preg_match("/Content-Type:.*x-pkcs7-mime/i", $headers) == 1){
1634                $contentType = "cipher";
1635            }
1636
1637            return $contentType;
1638    }
1639
1640         /**
1641     * Metodo que retorna todas as pastas do usuario logado.
1642     * @param $params array opcional para repassar os argumentos ao metodo.
1643     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
1644     * excluindo as compartilhadas para ele.
1645     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
1646     * folder_id, folder_name, folder_parent e folder_hasChildren.
1647     */
1648        function get_folders_list($params = null)
1649        {
1650                $inbox = 'INBOX';
1651                $trash = $inbox . $this->email_server['imapDelimiter ']. $this->email_server['imapDefaultTrashFolder;'];
1652                $drafts = $inbox . $this->email_server['imapDelimiter ']. $this->email_server['imapDefaultDraftsFolder'];
1653                $spam = $inbox . $this->email_server['imapDelimiter ']. $this->email_server['imapDefaultSpamFolder'];
1654                $sent = $inbox . $this->email_server['imapDelimiter ']. $this->email_server['imapDefaultSentFolder'];
1655                $uid2cn = $this->preferences['uid2cn'];
1656
1657                if(!$this->mbox || !is_resource($this->mbox))
1658                        $this->mbox = $this->open_mbox();
1659
1660                if($params && $params['onload'] && $this->cert){
1661                        $this->delete_mailbox(array("del_past" => "INBOX/decifradas"));
1662                }
1663
1664                $serverString = "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}";
1665                $folders_list = imap_getmailboxes($this->mbox, $serverString, ($params && $params['noSharedFolders']) ? "INBOX/*" : "*");
1666                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1667
1668                $tmp = array();
1669                $resultMine = array();
1670                $resultDefault = array();
1671
1672                if (is_array($folders_list)) {
1673                        reset($folders_list);
1674                        $this->ldap = new ldap_functions();
1675
1676                        $i = 0;
1677                        while (list($key, $val) = each($folders_list)) {
1678                                $status = imap_status($this->mbox, $val->name, SA_UNSEEN);
1679
1680                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1681                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
1682                                if($tmp_folder_id[1]=='INBOX'.$this->email_server['imapDelimiter'].'decifradas') {
1683                                        //error_log('passou', 3,'/tmp/imap_get_list.log');
1684                                        //imap_deletemailbox($this->mbox, imap_utf7_encode("{".$this->email_server['imapServer']."}".'INBOX/decifradas'));
1685                                        continue;
1686                                }
1687                                $result[$i]['folder_unseen'] = $status->unseen;
1688                                $folder_id = $tmp_folder_id[1];
1689                                $result[$i]['folder_id'] = $folder_id;
1690
1691                                $tmp_folder_parent = explode($this->email_server['imapDelimiter'], $folder_id);
1692                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1693                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1694                                if ($uid2cn && substr($folder_id,0,4) == 'user') {
1695                                        //$this->ldap = new ldap_functions();
1696                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
1697                                                $result[$i]['folder_name'] = $cn;
1698                                        }
1699                                }
1700
1701                                $tmp_folder_parent = implode($this->email_server['imapDelimiter'], $tmp_folder_parent);
1702                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
1703
1704                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1705                                        $result[$i]['folder_hasChildren'] = 1;
1706                                else
1707                                        $result[$i]['folder_hasChildren'] = 0;
1708
1709                                switch ($tmp_folder_id[1]) {
1710                                        case $inbox:
1711                                        case $sent:
1712                                        case $drafts:
1713                                        case $spam:
1714                                        case $trash:
1715                                                $resultDefault[]=$result[$i];
1716                                        default:
1717                                                $resultMine[]=$result[$i];
1718                                }
1719
1720                                $i++;
1721                        }
1722                }
1723
1724                // Sorting resultMine
1725                foreach ($resultMine as $folder_info)
1726                {
1727                        $array_tmp[] = $folder_info['folder_id'];
1728                }
1729
1730                natcasesort($array_tmp);
1731
1732                foreach ($array_tmp as $key => $folder_id)
1733                {
1734                        $result2[] = $resultMine[$key];
1735                }
1736               
1737                $resultDefault2=$resultDefault;
1738                // Sorting resultDefault
1739                foreach ($resultDefault as $key => $folder_id)
1740                {
1741
1742                        switch ($resultDefault[$key]['folder_id']) {
1743                                case $inbox:
1744                                        $resultDefault2[0] = $resultDefault[$key];
1745                                        break;
1746                                case $sent:
1747                                        $resultDefault2[1] = $resultDefault[$key];
1748                                        break;
1749                                case $drafts:
1750                                        $resultDefault2[2] = $resultDefault[$key];
1751                                        break;
1752                                case $spam:
1753                                        $resultDefault2[3] = $resultDefault[$key];
1754                                        break;
1755                                case $trash:
1756                                        $resultDefault2[4] = $resultDefault[$key];
1757                                        break;
1758                        }
1759                }
1760
1761                // Merge default folders and mines
1762                $result2 = array_merge($resultDefault2, $result2);
1763               
1764                $current_folder = "INBOX";
1765                if($params && $params['folder'])
1766                        $current_folder = $params['folder'];
1767                return array_merge($result2, $this->get_quota(array('folder_id' => $current_folder)));
1768        }
1769
1770        function create_mailbox($arr)
1771        {
1772                $namebox        = $arr['newp'];
1773                $mbox_stream = $this->open_mbox();
1774                $imap_server = $this->email_server['imapServer'];
1775                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
1776
1777                $result = "Ok";
1778                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
1779                {
1780                        $result = implode("<br />\n", imap_errors());
1781                }
1782
1783                if($mbox_stream)
1784                        imap_close($mbox_stream);
1785
1786                return $result;
1787
1788        }
1789
1790        function create_extra_mailbox($arr)
1791        {
1792                $nameboxs = explode(";",$arr['nw_folders']);
1793                $result = "";
1794                $mbox_stream = $this->open_mbox();
1795                $imap_server = $this->email_server['imapServer'];
1796                foreach($nameboxs as $key=>$tmp){
1797                        if($tmp != ""){
1798                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1799                                        $result = implode("<br />\n", imap_errors());
1800                                        if($mbox_stream)
1801                                                imap_close($mbox_stream);
1802                                        return $result;
1803                                }
1804                        }
1805                }
1806                if($mbox_stream)
1807                        imap_close($mbox_stream);
1808                return true;
1809        }
1810
1811        function delete_mailbox($arr)
1812        {
1813                $namebox = $arr['del_past'];
1814                $imap_server = $this->email_server['imapServer'];
1815                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
1816                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
1817
1818                $result = "Ok";
1819                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1820                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1821                {
1822                        $result = implode("<br />\n", imap_errors());
1823                }
1824                /*
1825                if($mbox_stream)
1826                        imap_close($mbox_stream);
1827                */
1828                return $result;
1829        }
1830
1831        function ren_mailbox($arr)
1832        {
1833                $namebox = $arr['current'];
1834                $new_box = $arr['rename'];
1835                $imap_server = $this->email_server['imapServer'];
1836                $mbox_stream = $this->open_mbox();
1837                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
1838
1839                $result = "Ok";
1840                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1841                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
1842                if(!$this->folder_exists($new_box))
1843                {
1844                        if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1845                        {
1846                                $result = imap_errors();
1847                        }
1848                }
1849                else{
1850                        $result = "Mailbox already exists";
1851                }
1852                if($mbox_stream)
1853                        imap_close($mbox_stream);
1854                return $result;
1855
1856        }
1857
1858        function get_num_msgs($params)
1859        {
1860                $folder = $params['folder'];
1861                if(!$this->mbox || !is_resource($this->mbox)) {
1862                        $this->mbox = $this->open_mbox($folder);
1863                        if(!$this->mbox || !is_resource($this->mbox))
1864                        return imap_last_error();
1865                }
1866                $num_msgs = imap_num_msg($this->mbox);
1867                if($this->mbox && is_resource($this->mbox))
1868                        imap_close($this->mbox);
1869
1870                return $num_msgs;
1871        }
1872
1873        function folder_exists($folder){
1874                $mbox =  $this->open_mbox();
1875                $serverString = "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}";             
1876                $list = imap_getmailboxes($mbox,$serverString, $folder);
1877                $return = is_array($list);             
1878                imap_close($mbox);
1879                return $return;
1880        }
1881       
1882        function send_mail($params)
1883        {
1884                include_once("class.phpmailer.php");
1885                $mail = new PHPMailer();
1886                $mail->email_server = $this->email_server;
1887                $mail->username = $this->username;
1888                $mail->password = $this->password;
1889                $mail->session_id = $this->session_id;
1890
1891                // Set lang for PHPMailer using user prefs.
1892                list($prefix,$userlang) = explode('-',$this->lang);
1893                $mail->SetLanguage($userlang,dirname( __FILE__ )."/../setup/");
1894                include_once("class.db_functions.inc.php");
1895                $db = new db_functions();
1896                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
1897                ##
1898                # @AUTHOR Rodrigo Souza dos Santos
1899                # @DATE 2008/09/17
1900                # @BRIEF Checks if the user has permission to send an email with the email address used.
1901                ##
1902                if ( is_array($fromaddress) && ($fromaddress[1] != $this->email) )
1903                {
1904                        $deny = true;
1905                        foreach( $this->shared_mailboxes as $key => $val )
1906                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
1907                                        $deny = false and end($this->shared_mailboxes);
1908
1909                        if ( $deny )
1910                                return "The server denied your request to send a mail, you cannot use this mail address.";
1911                }
1912
1913                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1914                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1915                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1916                $subject = $params['input_subject'];
1917                $msg_uid = $params['msg_id'];
1918                $return_receipt = $params['input_return_receipt'];
1919                $is_important = $params['input_important_message'];
1920        $encrypt = $params['input_return_cripto'];
1921                $signed = $params['input_return_digital'];
1922
1923                if($params['smime'])
1924        {
1925            $body = $params['smime'];
1926            $mail->SMIME = true;
1927            // A MSG assinada deve ser testada neste ponto.
1928            // Testar o certificado e a integridade da msg....
1929            include_once(dirname( __FILE__ )."/../../security/classes/CertificadoB.php");
1930            $erros_acumulados = '';
1931            $certificado = new certificadoB();
1932            $validade = $certificado->verificar($body);
1933            if(!$validade)
1934            {
1935                foreach($certificado->erros_ssl as $linha_erro)
1936                {
1937                    $erros_acumulados .= $linha_erro;
1938                }
1939            }
1940            else
1941            {
1942                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
1943                if ($certificado->apresentado)
1944                {
1945                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
1946                    if($certificado->dados['CPF'] != $this->username) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
1947                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
1948                }
1949                else
1950                {
1951                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
1952                }
1953            }
1954            if(!$erros_acumulados =='')
1955            {
1956                return $erros_acumulados;
1957            }
1958        }
1959        else
1960        {
1961            $body = $params['body'];
1962        }
1963                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
1964                $attachments = $params['FILES'];
1965                $forwarding_attachments = $params['forwarding_attachments'];
1966                $local_attachments = $params['local_attachments'];
1967               
1968                //Test if must be saved in shared folder and change if necessary
1969                if( $fromaddress[2] == 'y' ){
1970                        //build shared folder path
1971                        $newfolder = "user".$this->email_server['imapDelimiter'].$fromaddress[3].$this->email_server['imapDelimiter'].$this->imap_sentfolder;
1972                        if( $this->folder_exists($newfolder) ) $folder = $newfolder;
1973                        else $folder =  $params['folder'];                     
1974                } else  {
1975                        $folder = $params['folder'];                   
1976                }
1977               
1978                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
1979                $folder_name = $params['folder_name'];
1980                // Fix problem with cyrus delimiter changes.
1981                // Dots in names: enabled/disabled.
1982                $folder = @eregi_replace("INBOX/", "INBOX".$this->email_server['imapDelimiter'], $folder);
1983                $folder = @eregi_replace("INBOX.", "INBOX".$this->email_server['imapDelimiter'], $folder);
1984                // End Fix.
1985                if ($folder != 'null'){
1986                        $mail->SaveMessageInFolder = $folder;
1987                }
1988////////////////////////////////////////////////////////////////////////////////////////////////////
1989                $mail->SMTPDebug = false;
1990
1991                if($signed && !$params['smime'])
1992                {
1993            $mail->Mailer = "smime";
1994                        $mail->SignedBody = true;
1995                }
1996                else
1997            $mail->IsSMTP();
1998
1999                $mail->Host = $this->email_server['smtpServer'];
2000                $mail->Port = $this->email_server['smtpPort'];
2001                $mail->From = $this->email;
2002                $mail->FromName = $this->fullname;
2003                if($fromaddress){
2004                        $mail->Sender = $mail->From;
2005                        $mail->SenderName = $mail->FromName;
2006                        $mail->FromName = $fromaddress[0];
2007                        $mail->From = $fromaddress[1];
2008                }
2009
2010                $this->add_recipients("to", $toaddress, &$mail);
2011                $this->add_recipients("cc", $ccaddress, &$mail);
2012                $this->add_recipients("cco", $ccoaddress, &$mail);
2013                $mail->Subject = $subject;
2014                $mail->IsHTML(true);
2015                $mail->Body = $body;
2016
2017        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
2018                {
2019                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2020            $email = explode(",",$email);
2021            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2022            // Deve ser verificado um numero limite de destinatarios.
2023            // Deve ser verificado se os certificados sao validos.
2024            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2025            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2026            $numero_maximo = $this->preferences['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2027            $erros_acumulados = "";
2028            $aux_mails = array();
2029            $mail_list = array();
2030            if(count($email) > $numero_maximo)
2031            {
2032                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2033                return $erros_acumulados;
2034            }
2035            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2036            $email[] = $this->email;
2037            foreach($email as $item)
2038            {
2039                $certificate = $db->get_certificate(strtolower($item));
2040                if(!$certificate)
2041                {
2042                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2043                    return $erros_acumulados;
2044                }
2045
2046                if (array_key_exists("dberr1", $certificate))
2047                {
2048
2049                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2050                    return $erros_acumulados;
2051                                }
2052                if (array_key_exists("dberr2", $certificate))
2053                {
2054                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2055                    //continue;
2056                }
2057                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2058                if (!array_key_exists("certs", $certificate))
2059                {
2060                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2061                    continue;
2062                }
2063            */
2064                include_once("../security/classes/CertificadoB.php");
2065
2066                foreach ($certificate['certs'] as $registro)
2067                {
2068                    $c1 = new certificadoB();
2069                    $c1->certificado($registro['chave_publica']);
2070                    if ($c1->apresentado)
2071                    {
2072                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2073                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2074                        {
2075                            $aux_mails[] = $registro['chave_publica'];
2076                            $mail_list[] = strtolower($item);
2077                        }
2078                        else
2079                        {
2080                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2081                            {
2082                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2083                                    $c1->dados['EXPIRADO'],$c2->revogado);
2084                            }
2085
2086                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2087                            foreach($c2->erros_ssl as $linha)
2088                            {
2089                                $erros_acumulados .=  $linha . chr(0x0A);
2090                            }
2091                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2092                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2093                        }
2094                    }
2095                    else
2096                    {
2097                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2098                    }
2099                }
2100                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2101                                {
2102                                        return $erros_acumulados;
2103                        }
2104            }
2105
2106            $mail->Certs_crypt = $aux_mails;
2107        }
2108
2109////////////////////////////////////////////////////////////////////////////////////////////////////
2110                //      Build CID for embedded Images!!!
2111                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2112                $cid_imgs = '';
2113                $name_cid_files = array();
2114                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2115                $cid_array = array();
2116                foreach($cid_imgs[6] as $j => $val){
2117                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2118                        {
2119                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2120                        }
2121                        $cid = $cid_array[$cid_imgs[4][$j].$val];
2122                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2123
2124                                if (!$forwarding_attachments[$cid_imgs[6][$j]-2]) // The image isn't in the same mail?
2125                                {
2126                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2127                                        $fileName = "image_".($j).".jpg";
2128                                        $fileCode = "base64";
2129                                        $fileType = "image/jpg";
2130                                }
2131                                else
2132                                {
2133                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2134                                        $file_description = unserialize(rawurldecode($attach_img));
2135
2136                                        foreach($file_description as $i => $descriptor){
2137                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2138                                        }
2139                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $cid_imgs[4][$j], $file_description[3], 'base64');
2140                                        $fileName = $file_description[2];
2141                                        $fileCode = $file_description[4];
2142                                        $fileType = $this->get_file_type($file_description[2]);
2143                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2144                                }
2145                                $tempDir = ini_get("session.save_path");
2146                                $file = "cidimage_".$this->session_id.$cid_imgs[6][$j].".dat";
2147                                $f = fopen($tempDir.'/'.$file,"w");
2148                                fputs($f,$fileContent);
2149                                fclose($f);
2150                                if ($fileContent)
2151                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2152                                //else
2153                                //      return "Error loading image attachment content";
2154
2155                }
2156////////////////////////////////////////////////////////////////////////////////////////////////////
2157                //      Build Uploading Attachments!!!
2158                if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
2159                {
2160                        $total_uploaded_size = 0;
2161                        $upload_max_filesize = str_replace("M","",$this->preferences['max_attachment_size']) * 1024 * 1024;
2162                        foreach ($attachments as $attach)
2163                        {
2164                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2165                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2166                        }
2167                        if( $total_uploaded_size > $upload_max_filesize)
2168                                return $this->parse_error("message file too big");
2169                }
2170                else if(($params['is_local_forward']=="1") && (count($local_attachments))) { //Caso seja forward de mensagens locais
2171
2172                        $total_uploaded_size = 0;
2173                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
2174                        foreach($local_attachments as $local_attachment) {
2175                                $file_description = unserialize(rawurldecode($local_attachment));
2176                                $tmp = array_values($file_description);
2177                                foreach($file_description as $i => $descriptor){
2178                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2179                                }
2180                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2181                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2182                        }
2183                        if( $total_uploaded_size > $upload_max_filesize)
2184                                return 'false';
2185                }
2186////////////////////////////////////////////////////////////////////////////////////////////////////
2187                //      Build Forwarding Attachments!!!
2188                if (count($forwarding_attachments) > 0)
2189                {
2190                        // Bug fixed for array_search function
2191                        if(count($name_cid_files) > 0) {
2192                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2193                                $name_cid_files[0] = null;
2194                        }
2195
2196                        foreach($forwarding_attachments as $forwarding_attachment)
2197                        {
2198                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2199                                        $tmp = array_values($file_description);
2200                                        foreach($file_description as $i => $descriptor){
2201                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2202                                        }
2203                                        $file_description = $tmp;
2204                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2205                                        $fileName = $file_description[2];
2206                                        if(!array_search(trim($fileName),$name_cid_files)) {
2207                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2208                                }
2209                        }
2210                }
2211
2212////////////////////////////////////////////////////////////////////////////////////////////////////
2213                // Important message
2214                if($is_important)
2215                        $mail->isImportant();
2216
2217////////////////////////////////////////////////////////////////////////////////////////////////////
2218                // Disposition-Notification-To
2219                if ($return_receipt)
2220                        $mail->ConfirmReadingTo = $this->email;
2221////////////////////////////////////////////////////////////////////////////////////////////////////
2222
2223                $sent = $mail->Send();
2224
2225                if(!$sent)
2226                {
2227                        return $this->parse_error($mail->ErrorInfo);
2228                }
2229                else
2230                {
2231            if ($signed && !$params['smime'])
2232                        {
2233                                return $sent;
2234                        }
2235                        if($this->enable_log_messages == "True")
2236                        {
2237                                $userid = $this->username;
2238                                $userip = $this->session_ip;
2239                                $now = date("d/m/y H:i:s");
2240                                $addrs = $toaddress.$ccaddress.$ccoaddress;
2241                                $sent = trim($sent);
2242                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2243                        }
2244                        if($this->preferences['number_of_contacts'] &&
2245                           $this->preferences['use_dynamic_contacts']) {
2246                                $contacts = new dynamic_contacts();
2247                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2248                                return array("success" => true, "new_contacts" => $new_contacts);
2249                        }
2250                        return array("success" => true);
2251                }
2252        }
2253
2254    function add_recipients_cert($full_address)
2255        {
2256                $result = "";
2257                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2258                foreach ($parse_address as $val)
2259                {
2260                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2261                        if ($val->mailbox == "INVALID_ADDRESS")
2262                                continue;
2263                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2264                                continue;
2265                        if (empty($val->personal))
2266                                $result .= $val->mailbox."@".$val->host . ",";
2267                        else
2268                                $result .= $val->mailbox."@".$val->host . ",";
2269                }
2270
2271                return substr($result,0,-1);
2272        }
2273
2274        function add_recipients($recipient_type, $full_address, $mail)
2275        {
2276                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2277                foreach ($parse_address as $val)
2278                {
2279                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2280                        if ($val->mailbox == "INVALID_ADDRESS")
2281                                continue;
2282
2283                        if (empty($val->personal))
2284                        {
2285                                switch($recipient_type)
2286                                {
2287                                        case "to":
2288                                                $mail->AddAddress($val->mailbox."@".$val->host);
2289                                                break;
2290                                        case "cc":
2291                                                $mail->AddCC($val->mailbox."@".$val->host);
2292                                                break;
2293                                        case "cco":
2294                                                $mail->AddBCC($val->mailbox."@".$val->host);
2295                                                break;
2296                                }
2297                        }
2298                        else
2299                        {
2300                                switch($recipient_type)
2301                                {
2302                                        case "to":
2303                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2304                                                break;
2305                                        case "cc":
2306                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2307                                                break;
2308                                        case "cco":
2309                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2310                                                break;
2311                                }
2312                        }
2313                }
2314                return true;
2315        }
2316
2317        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2318        {
2319                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
2320                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
2321                if($encoding == 'base64')
2322                        # The function imap_base64 adds a new line
2323                        # at ASCII text, with CRLF line terminators.
2324                        # So is being exchanged for base64_decode.
2325                        #
2326                        #$fileContent = imap_base64($fileContent);
2327                        $fileContent = base64_decode($fileContent);
2328                else if($encoding == 'quoted-printable')
2329                        $fileContent = quoted_printable_decode($fileContent);
2330                return $fileContent;
2331        }
2332
2333        function del_last_caracter($string)
2334        {
2335                $string = substr($string,0,(strlen($string) - 1));
2336                return $string;
2337        }
2338
2339        function del_last_two_caracters($string)
2340        {
2341                $string = substr($string,0,(strlen($string) - 2));
2342                return $string;
2343        }
2344
2345        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
2346        {
2347                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
2348                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2349                        foreach($imapsort as $iuid)
2350                                $sort[$iuid] = "";
2351                       
2352                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2353                                $slice_array = false;
2354                        else
2355                                $slice_array = true;
2356                }
2357                else
2358                {
2359                        $sort = array();
2360                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2361                        $num_msgs = imap_num_msg($this->mbox);
2362                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
2363                        $slice_array = true;
2364
2365                        for ($i=$num_msgs; $i>0; $i--)
2366                        {
2367                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2368                                        break;
2369                                $iuid = @imap_uid($this->mbox,$i);
2370                                $header = $this->get_header($iuid);
2371                                // List UNSEEN messages.
2372                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2373                                        continue;
2374                                }
2375                                // List SEEN messages.
2376                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2377                                        continue;
2378                                }
2379                                // List ANSWERED messages.
2380                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2381                                        continue;
2382                                }
2383                                // List FLAGGED messages.
2384                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2385                                        continue;
2386                                }
2387
2388                                if($sort_box_type=='SORTFROM') {
2389                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $this->email)
2390                                                $from = $header->to;
2391                                        else
2392                                                $from = $header->from;
2393
2394                                        $tmp = imap_mime_header_decode($from[0]->personal);
2395
2396                                        if ($tmp[0]->text != "")
2397                                                $sort[$iuid] = $tmp[0]->text;
2398                                        else
2399                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2400                                }
2401                                else if($sort_box_type=='SORTSUBJECT') {
2402                                        $sort[$iuid] = $header->subject;
2403                                }
2404                                else if($sort_box_type=='SORTSIZE') {
2405                                        $sort[$iuid] = $header->Size;
2406                                }
2407                                else {
2408                                        $sort[$iuid] = $header->udate;
2409                                }
2410
2411                        }
2412                        natcasesort($sort);
2413
2414                        if ($sort_box_reverse)
2415                                $sort = array_reverse($sort,true);
2416                }
2417
2418                if(!is_array($sort))
2419                        $sort = array();
2420
2421
2422                if ($slice_array)
2423                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
2424
2425
2426                return $sort;
2427
2428        }
2429
2430
2431        function move_search_messages($params){
2432                $params['selected_messages'] = urldecode($params['selected_messages']);
2433                $params['new_folder'] = urldecode($params['new_folder']);
2434                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2435                $sel_msgs = explode(",", $params['selected_messages']);
2436                @reset($sel_msgs);
2437                $sorted_msgs = array();
2438                foreach($sel_msgs as $idx => $sel_msg) {
2439                        $sel_msg = explode(";", $sel_msg);
2440                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2441                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
2442                         }
2443                         else {
2444                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2445                         }
2446                }
2447                @ksort($sorted_msgs);
2448                $last_return = false;
2449                foreach($sorted_msgs as $folder => $msgs_number) {
2450                        $params['msgs_number'] = $msgs_number;
2451                        $params['folder'] = $folder;
2452                        if($params['new_folder'] && $folder != $params['new_folder']){
2453                                $last_return = $this -> move_messages($params);
2454                        }
2455                        elseif(!$params['new_folder'] || $params['delete'] ){
2456                                $last_return = $this -> delete_msgs($params);
2457                                $last_return['deleted'] = true;
2458                        }
2459                }
2460                return $last_return;
2461        }
2462
2463        function move_messages($params)
2464        {
2465                $folder = $params['folder'];
2466                $mbox_stream = $this->open_mbox($folder);
2467                $newmailbox = ($params['new_folder']);
2468                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
2469                $new_folder_name = $params['new_folder_name'];
2470                $msgs_number = $params['msgs_number'];
2471                $return = array('msgs_number' => $msgs_number,
2472                                                'folder' => $folder,
2473                                                'new_folder_name' => $new_folder_name,
2474                                                'border_ID' => $params['border_ID'],
2475                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
2476
2477                $error_log_file=$this->server_files_dir."/expressoMail.log";
2478                if($this->enable_log_messages == "True" &&
2479                strpos($msgs_number,',') != False)
2480                        error_log(date("D M j G:i:s T Y").": expressoMail, move_messages: "
2481                                .$this->username." ".$folder."=>".$new_folder_name.
2482                                " ".$msgs_number."\n", 3, $error_log_file);
2483
2484                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2485        if (substr($folder,0,4) == 'user'){
2486                $acl = $this->getacltouser($folder);
2487                /*
2488                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2489                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2490                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2491                 *   w - write (STORE flags other than SEEN and DELETED)
2492                 *   i - insert (perform APPEND, COPY into mailbox)
2493                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2494                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2495                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2496                 *   a - administer (perform SETACL)
2497                        */
2498                        if (strpos($acl, "d") === false){
2499                                $return['status'] = false;
2500                                return $return;
2501                        }
2502        }
2503        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
2504        if ($this->preferences['uid2cn']){
2505            if (substr($new_folder_name,0,4) == 'user'){
2506                $this->ldap = new ldap_functions();
2507                $tmp_folder_name = explode($this->email_server['imapDelimiter'], $new_folder_name);
2508                $return['new_folder_name'] = array_pop($tmp_folder_name);
2509                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2510                {
2511                    $return['new_folder_name'] = $cn;
2512                }
2513            }
2514        }
2515
2516                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
2517                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
2518                {
2519                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2520                        // Fix problem in unserialize function JS.
2521                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2522                }
2523
2524                $mbox_stream = $this->open_mbox($folder);
2525                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2526                        imap_expunge($mbox_stream);
2527                        if($mbox_stream)
2528                                imap_close($mbox_stream);
2529                        return $return;
2530                }else {
2531                        if(strstr(imap_last_error(),'Over quota')) {
2532                                $accountID      = $this->email_server['imapAdminUsername'];
2533                                $pass           = $this->email_server['imapAdminPW'];
2534                                $userID         = $this->username;
2535                                $server         = $this->email_server['imapServer'];
2536                                $mbox           = @imap_open("{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}INBOX", $accountID, $pass) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
2537                                if(!$mbox)
2538                                        return imap_last_error();
2539                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
2540                                if(! imap_set_quota($mbox, "user".$this->email_server['imapDelimiter'].$userID, 2.1 * $quota['usage'])) {
2541                                        if($mbox_stream)
2542                                                imap_close($mbox_stream);
2543                                        if($mbox)
2544                                                imap_close($mbox);
2545                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->email_server['imapDelimiter'].$userID." line ".__LINE__."\n";
2546                                }
2547                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2548                                        imap_expunge($mbox_stream);
2549                                        if($mbox_stream)
2550                                                imap_close($mbox_stream);
2551                                        // return to original quota limit.
2552                                        if(!imap_set_quota($mbox, "user".$this->email_server['imapDelimiter'].$userID, $quota['limit'])) {
2553                                                if($mbox)
2554                                                        imap_close($mbox);
2555                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2556                                        }
2557                                        return $return;
2558                                }
2559                                else {
2560                                        if($mbox_stream)
2561                                                imap_close($mbox_stream);
2562                                        if(!imap_set_quota($mbox, "user".$this->email_server['imapDelimiter'].$userID, $quota['limit'])) {
2563                                                if($mbox)
2564                                                        imap_close($mbox);
2565                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2566                                        }
2567                                        return imap_last_error();
2568                                }
2569
2570                        }
2571                        else {
2572                                if($mbox_stream)
2573                                        imap_close($mbox_stream);
2574                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
2575                        }
2576                }
2577        }
2578
2579        function save_msg($params)
2580        {
2581
2582                include_once("class.phpmailer.php");
2583                $mail = new PHPMailer();
2584                // Set lang for PHPMailer using user prefs.
2585                list($prefix,$userlang) = explode('-',$this->lang);             
2586                $mail->SetLanguage($userlang,dirname( __FILE__ )."/../setup/");         
2587                include_once("class.db_functions.inc.php");
2588                $toaddress = $params['input_to'];
2589                $ccaddress = $params['input_cc'];
2590                $ccoaddress = $params['input_cco'];
2591                $subject = $params['input_subject'];
2592                $msg_uid = $params['msg_id'];
2593                $body = $params['body'];
2594                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
2595                $body = preg_replace("/\n/"," ",$body);
2596                $body = preg_replace("/\r/","",$body);
2597                $forwarding_attachments = $params['forwarding_attachments'];
2598                $attachments = $params['FILES'];
2599                $return_files = $params['FILES'];
2600
2601                $folder = $params['folder'];
2602                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2603                // Fix problem with cyrus delimiter changes.
2604                // Dots in names: enabled/disabled.
2605                $folder = @eregi_replace("INBOX/", "INBOX".$this->email_server['imapDelimiter'], $folder);
2606                $folder = @eregi_replace("INBOX.", "INBOX".$this->email_server['imapDelimiter'], $folder);
2607                // End Fix.
2608                if(strtoupper($folder) == 'INBOX/DRAFTS')
2609                    {
2610                        $mail->SaveMessageAsDraft = $folder;
2611                    }
2612                $mail->SaveMessageInFolder = $folder;
2613                $mail->SMTPDebug = false;
2614
2615                $mail->IsSMTP();
2616                $mail->Host = $this->email_server['smtpServer'];
2617                $mail->Port = $this->email_server['smtpPort'];
2618                $mail->From = $this->email;
2619                $mail->FromName = $this->fullname;
2620
2621                $mail->Sender = $mail->From;
2622                $mail->SenderName = $mail->FromName;
2623                $mail->FromName = $this->fullname;
2624                $mail->From =  $this->email;
2625                $session_id = $this->session_id;
2626                $max_resolution = $this->preferences['image_size'];
2627
2628                $this->add_recipients("to", $toaddress, &$mail);
2629                $this->add_recipients("cc", $ccaddress, &$mail);
2630                $this->add_recipients("cco", $ccoaddress, &$mail);
2631                $mail->Subject = $subject;
2632                $mail->IsHTML(true);
2633                $mail->Body = $body;
2634
2635                //      Build CID for embedded Images!!!
2636                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2637                $cid_imgs = '';
2638                $name_cid_files = array();
2639                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2640                $cid_array = array();
2641                foreach($cid_imgs[6] as $j => $val){
2642                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2643                        {
2644                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2645                        }
2646                        $cid = $cid_array[$cid_imgs[4][$j].$val];
2647                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2648
2649                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
2650                                {
2651                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2652                                        //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
2653                                        $fileName = "image_".($j).".jpg";
2654                                        $fileCode = "base64";
2655                                        $fileType = "image/jpg";
2656                                        $file_attached[0] = $cid_imgs[2][$j];
2657                                        $file_attached[1] = $cid_imgs[4][$j];
2658                                        $file_attached[2] = $fileName;
2659                                        $file_attached[3] = $cid_imgs[6][$j];
2660                                        $file_attached[4] = 'base64';
2661                                        $file_attached[5] = strlen($fileContent); //Size of file
2662                                        $return_forward[] = $file_attached;
2663                                }
2664                                else
2665                                {
2666                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2667                                        $file_description = unserialize(rawurldecode($attach_img));
2668                                        foreach($file_description as $i => $descriptor){
2669                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2670                                        }
2671                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2672                                        $fileName = $file_description[2];
2673                                        $fileCode = $file_description[4];
2674                                        $fileType = $this->get_file_type($file_description[2]);
2675                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2676                                        if (!empty($file_description))
2677                                        {
2678                                                $file_description[5] = strlen($fileContent); //Size of file
2679                                                $return_forward[] = $file_description;
2680                                        }
2681                                }
2682                                $tempDir = ini_get("session.save_path");
2683                                $file = "cidimage_".$session_id.$cid_imgs[6][$j].".dat";
2684                                $f = fopen($tempDir.'/'.$file,"w");
2685                                fputs($f,$fileContent);
2686                                fclose($f);
2687                                if ($fileContent)
2688                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2689                                //else
2690                                //      return "Error loading image attachment content";
2691
2692                }
2693
2694        //      Build Forwarding Attachments!!!
2695                if (count($forwarding_attachments) > 0)
2696                {
2697                        foreach($forwarding_attachments as $forwarding_attachment)
2698                        {
2699                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2700                                $tmp = array_values($file_description);
2701                                foreach($file_description as $i => $descriptor){
2702                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2703                                }
2704                                $file_description = $tmp;
2705
2706                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2707                                $fileName = $file_description[2];
2708
2709                                $file_description[5] = strlen($fileContent); //Size of file
2710                                $return_forward[] = $file_description;
2711
2712                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2713                        }
2714                }
2715
2716                if ((count($return_forward) > 0) && (count($return_files) > 0))
2717                        $return_files = array_merge_recursive($return_forward,$return_files);
2718                else
2719                        if (count($return_files) < 1)
2720                                $return_files = $return_forward;
2721
2722                //      Build Uploading Attachments!!!
2723                $sizeof_attachments = count($attachments);
2724                if ($sizeof_attachments)
2725                        foreach ($attachments as $numb => $attach){
2726                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2727                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2728                                        switch ($image_type)
2729                                        {
2730                                        // Do not corrupt animated gif
2731                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
2732                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2733                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2734                                        case 6:
2735                                                require_once("gd_functions.php");
2736                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2737                                        default:
2738                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2739                                                break;
2740                                        }
2741                                        header('Content-type: image/jpeg');
2742                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2743                                        if ($width < $max_resolution && $height < $max_resolution){
2744                                                $new_width = $width;
2745                                                $new_height = $height;
2746                                        }
2747                                        else if ($width > $max_resolution){
2748                                                $new_width = $max_resolution;
2749                                                $new_height = $height*($new_width/$width);
2750                                        }
2751                                        else {
2752                                                $new_height = $max_resolution;
2753                                                $new_width = $width*($new_height/$height);
2754                                        }
2755                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2756                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2757                                        $tmpDir = ini_get("session.save_path");
2758                                        $_file = "/cidimage_".$session_id.".dat";
2759                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2760                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2761                                }
2762                                else
2763                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2764                                // optional name
2765                                }
2766
2767
2768
2769
2770                if(!empty($mail->AltBody))
2771            $mail->ContentType = "multipart/alternative";
2772
2773                $mail->error_count = 0; // reset errors
2774                $mail->SetMessageType();
2775                $header = $mail->CreateHeader();
2776                $body = $mail->CreateBody();
2777
2778                $mbox_stream = $this->open_mbox($folder);
2779                $new_header = str_replace("\n", "\r\n", $header);
2780                $new_body = str_replace("\n", "\r\n", $body);
2781                $return['append'] = imap_append($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort']."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2782                $status = imap_status($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort']."}".$folder, SA_UIDNEXT);
2783                $return['msg_no'] = $status->uidnext - 1;
2784                $return['folder_id'] = $folder;
2785
2786                if($mbox_stream)
2787                        imap_close($mbox_stream);
2788                if (is_array($return_files))
2789                        foreach ($return_files as $index => $_attachment) {
2790                                if (array_key_exists("name",$_attachment)){
2791                                unset($return_files[$index]);
2792                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2793                        }
2794                        else
2795                        {
2796                                unset($return_files[$index]);
2797                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2798                        }
2799                }
2800
2801                $return['files'] = serialize($return_files);
2802                $return["subject"] = $subject;
2803
2804                if (!$return['append'])
2805                        $return['append'] = imap_last_error();
2806       
2807                return $return;
2808        }
2809
2810        function set_messages_flag($params)
2811        {
2812                $folder = $params['folder'];
2813                $msgs_to_set = $params['msgs_to_set'];
2814                $flag = $params['flag'];
2815                $return = array();
2816                $return["msgs_to_set"] = $msgs_to_set;
2817                $return["flag"] = $flag;
2818
2819                if(!$this->mbox && !is_resource($this->mbox))
2820                        $this->mbox = $this->open_mbox($folder);
2821
2822                if ($flag == "unseen")
2823                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2824                elseif ($flag == "seen")
2825                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2826                elseif ($flag == "answered"){
2827                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2828                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2829                }
2830                elseif ($flag == "forwarded")
2831                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2832                elseif ($flag == "flagged")
2833                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2834                elseif ($flag == "unflagged") {
2835                        $flag_importance = false;
2836                        $msgs_number = explode(",",$msgs_to_set);
2837                        $unflagged_msgs = "";
2838                        foreach($msgs_number as $msg_number) {
2839                                preg_match('/importance *: *(.*)\r/i',
2840                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2841                                        ,$importance);
2842                                if(strtolower($importance[1])=="high" && $this->preferences['use_important_flag']) {
2843                                        $flag_importance=true;
2844                                }
2845                                else {
2846                                        $unflagged_msgs.=$msg_number.",";
2847                                }
2848                        }
2849
2850                        if($unflagged_msgs!="") {
2851                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2852                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2853                        }
2854                        else {
2855                                $return["msgs_unflageds"] = false;
2856                        }
2857
2858                        if($flag_importance && $this->preferences['use_important_flag']) {
2859                                $return["status"] = false;
2860                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2861                        }
2862                        else {
2863                                $return["status"] = true;
2864                        }
2865                }
2866
2867                if($this->mbox && is_resource($this->mbox))
2868                        imap_close($this->mbox);
2869                return $return;
2870        }
2871
2872        function get_file_type($file_name)
2873        {
2874                $file_name = strtolower($file_name);
2875                $strFileType = strrev(substr(strrev($file_name),0,4));
2876                if ($strFileType == ".asf")
2877                        return "video/x-ms-asf";
2878                if ($strFileType == ".avi")
2879                        return "video/avi";
2880                if ($strFileType == ".doc")
2881                        return "application/msword";
2882                if ($strFileType == ".zip")
2883                        return "application/zip";
2884                if ($strFileType == ".xls")
2885                        return "application/vnd.ms-excel";
2886                if ($strFileType == ".gif")
2887                        return "image/gif";
2888                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2889                        return "image/jpeg";
2890                if ($strFileType == ".png")
2891                        return "image/png";
2892                if ($strFileType == ".wav")
2893                        return "audio/wav";
2894                if ($strFileType == ".mp3")
2895                        return "audio/mpeg3";
2896                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2897                        return "video/mpeg";
2898                if ($strFileType == ".rtf")
2899                        return "application/rtf";
2900                if ($strFileType == ".htm" || $strFileType == "html")
2901                        return "text/html";
2902                if ($strFileType == ".xml")
2903                        return "text/xml";
2904                if ($strFileType == ".xsl")
2905                        return "text/xsl";
2906                if ($strFileType == ".css")
2907                        return "text/css";
2908                if ($strFileType == ".php")
2909                        return "text/php";
2910                if ($strFileType == ".asp")
2911                        return "text/asp";
2912                if ($strFileType == ".pdf")
2913                        return "application/pdf";
2914                if ($strFileType == ".txt")
2915                        return "text/plain";
2916                if ($strFileType == ".wmv")
2917                        return "video/x-ms-wmv";
2918                if ($strFileType == ".sxc")
2919                        return "application/vnd.sun.xml.calc";
2920                if ($strFileType == ".stc")
2921                        return "application/vnd.sun.xml.calc.template";
2922                if ($strFileType == ".sxd")
2923                        return "application/vnd.sun.xml.draw";
2924                if ($strFileType == ".std")
2925                        return "application/vnd.sun.xml.draw.template";
2926                if ($strFileType == ".sxi")
2927                        return "application/vnd.sun.xml.impress";
2928                if ($strFileType == ".sti")
2929                        return "application/vnd.sun.xml.impress.template";
2930                if ($strFileType == ".sxm")
2931                        return "application/vnd.sun.xml.math";
2932                if ($strFileType == ".sxw")
2933                        return "application/vnd.sun.xml.writer";
2934                if ($strFileType == ".sxq")
2935                        return "application/vnd.sun.xml.writer.global";
2936                if ($strFileType == ".stw")
2937                        return "application/vnd.sun.xml.writer.template";
2938
2939
2940                return "application/octet-stream";
2941        }
2942
2943        function htmlspecialchars_encode($str)
2944        {
2945                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
2946        }
2947        function htmlspecialchars_decode($str)
2948        {
2949                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
2950        }
2951
2952        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2953        {
2954                if(!$this->mbox || !is_resource($this->mbox))
2955                        $this->mbox = $this->open_mbox($folder);
2956
2957                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2958        }
2959
2960        function get_info_next_msg($params)
2961        {
2962                $msg_number = $params['msg_number'];
2963                $folder = $params['msg_folder'];
2964                $sort_box_type = $params['sort_box_type'];
2965                $sort_box_reverse = $params['sort_box_reverse'];
2966                $reuse_border = $params['reuse_border'];
2967                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2968                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2969
2970                $success = false;
2971                if (is_array($sort_array_msg))
2972                {
2973                        foreach ($sort_array_msg as $i => $value){
2974                                if ($value == $msg_number)
2975                                {
2976                                        $success = true;
2977                                        break;
2978                                }
2979                        }
2980                }
2981
2982                if (! $success || $i >= sizeof($sort_array_msg)-1)
2983                {
2984                        $params['status'] = 'false';
2985                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2986                        return $params;
2987                }
2988
2989                $params = array();
2990                $params['msg_number'] = $sort_array_msg[($i+1)];
2991                $params['msg_folder'] = $folder;
2992
2993                $return = $this->get_info_msg($params);
2994                $return["reuse_border"] = $reuse_border;
2995                return $return;
2996        }
2997
2998        function get_info_previous_msg($params)
2999        {
3000                $msg_number = $params['msgs_number'];
3001                $folder = $params['folder'];
3002                $sort_box_type = $params['sort_box_type'];
3003                $sort_box_reverse = $params['sort_box_reverse'];
3004                $reuse_border = $params['reuse_border'];
3005                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
3006                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
3007
3008                $success = false;
3009                if (is_array($sort_array_msg))
3010                {
3011                        foreach ($sort_array_msg as $i => $value){
3012                                if ($value == $msg_number)
3013                                {
3014                                        $success = true;
3015                                        break;
3016                                }
3017                        }
3018                }
3019                if (! $success || $i == 0)
3020                {
3021                        $params['status'] = 'false';
3022                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3023                        return $params;
3024                }
3025
3026                $params = array();
3027                $params['msg_number'] = $sort_array_msg[($i-1)];
3028                $params['msg_folder'] = $folder;
3029
3030                $return = $this->get_info_msg($params);
3031                $return["reuse_border"] = $reuse_border;
3032                return $return;
3033        }
3034
3035        // This function updates the values: quota, paging and new messages menu.
3036        function get_menu_values($params){
3037                $return_array = array();
3038                $return_array = $this->get_quota($params);
3039
3040                $mbox_stream = $this->open_mbox($params['folder']);
3041                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
3042                if($mbox_stream)
3043                        imap_close($mbox_stream);
3044
3045                return $return_array;
3046        }
3047
3048        function get_quota($params){
3049                // folder_id = user/{uid} for shared folders
3050                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->email_server['imapDelimiter'].'/i', $params['folder_id'])){
3051                        $array_folder =  explode($this->email_server['imapDelimiter'],$params['folder_id']);
3052                        $folder_id = "user".$this->email_server['imapDelimiter'].$array_folder[1];
3053                }
3054                // folder_id = INBOX for inbox folders
3055                else
3056                        $folder_id = "INBOX";
3057
3058                if(!$this->mbox || !is_resource($this->mbox))
3059                        $this->mbox = $this->open_mbox();
3060
3061                $quota = imap_get_quotaroot($this->mbox, $folder_id);
3062                if($this->mbox && is_resource($this->mbox))
3063                        imap_close($this->mbox);
3064
3065                if (!$quota){
3066                        return array(
3067                                'quota_percent' => 0,
3068                                'quota_used' => 0,
3069                                'quota_limit' =>  0
3070                        );
3071                }
3072
3073                if(count($quota) && $quota['limit']) {
3074                        $quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
3075                        $quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
3076                        if($quota_used >= $quota_limit)
3077                        {
3078                                $quotaPercent = 100;
3079                        }
3080                        else
3081                        {
3082                        $quotaPercent = ($quota_used / $quota_limit)*100;
3083                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
3084                        }
3085                        return array(
3086                                'quota_percent' => floor($quotaPercent),
3087                                'quota_used' => floor($quota_used),
3088                                'quota_limit' =>  floor($quota_limit)
3089                        );
3090                }
3091                else
3092                        return array();
3093        }
3094
3095        function send_notification($params){
3096                require_once("class.phpmailer.php");
3097                $mail = new PHPMailer();
3098                // Set lang for PHPMailer using user prefs.
3099                list($prefix,$userlang) = explode('-',$this->lang);             
3100                $mail->SetLanguage($userlang,dirname( __FILE__ )."/../setup/");
3101
3102                $toaddress = $params['notificationto'];
3103
3104                $subject = 'Confirmação de leitura: ' . $params['subject'];
3105                $body = 'Sua mensagem: ' . $params['subject'] . '<br>';
3106                $body .= 'foi lida por: ' . $this->fullname . ' &lt;' . $this->email . '&gt; em ' . date("d/m/Y H:i");
3107                $mail->SMTPDebug = false;
3108                $mail->IsSMTP();
3109                $mail->Host = $this->email_server['smtpServer'];
3110                $mail->Port = $this->email_server['smtpPort'];
3111                $mail->From = $this->email;
3112                $mail->FromName = $this->fullname;
3113                $mail->AddAddress($toaddress);
3114                $mail->Subject = $this->htmlspecialchars_decode($subject);
3115
3116                $mail->IsHTML(true);
3117                $mail->Body = $body;
3118
3119                if(!$mail->Send()){
3120                        return $mail->ErrorInfo;
3121                }
3122                else
3123                        return true;
3124        }
3125
3126        function empty_folder($params)
3127        {
3128                $folder = 'INBOX' . $this->email_server['imapDelimiter ']. $this->email_server[$params['clean_folder']];
3129                $mbox_stream = $this->open_mbox($folder);
3130                $return = imap_delete($mbox_stream,'1:*');
3131                if($mbox_stream)
3132                        imap_close($mbox_stream, CL_EXPUNGE);
3133                return $return;
3134        }
3135
3136        function search($params)
3137        {
3138                include("class.imap_attachment.inc.php");
3139                $imap_attachment = new imap_attachment();
3140                $criteria = $params['criteria'];
3141                $return = array();
3142                $folders = $this->get_folders_list();
3143
3144                $j = 0;
3145                foreach($folders as $folder)
3146                {
3147                        $mbox_stream = $this->open_mbox($folder);
3148                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
3149
3150                        if ($messages == '')
3151                                continue;
3152
3153                        $i = 0;
3154                        $return[$j] = array();
3155                        $return[$j]['folder_name'] = $folder['name'];
3156
3157                        foreach($messages as $msg_number)
3158                        {
3159                                $header = $this->get_header($msg_number);
3160                                if (!is_object($header))
3161                                        return false;
3162
3163                                $return[$j][$i]['msg_folder']   = $folder['name'];
3164                                $return[$j][$i]['msg_number']   = $msg_number;
3165                                $return[$j][$i]['Recent']               = $header->Recent;
3166                                $return[$j][$i]['Unseen']               = $header->Unseen;
3167                                $return[$j][$i]['Answered']     = $header->Answered;
3168                                $return[$j][$i]['Deleted']              = $header->Deleted;
3169                                $return[$j][$i]['Draft']                = $header->Draft;
3170                                $return[$j][$i]['Flagged']              = $header->Flagged;
3171
3172                                $date_msg = gmdate("d/m/Y",$header->udate);
3173                                if (gmdate("d/m/Y") == $date_msg)
3174                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
3175                                else
3176                                        $return[$j][$i]['udate'] = $date_msg;
3177
3178                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3179                                $return[$j][$i]['fromaddress'] = '';
3180                                foreach ($fromaddress as $tmp)
3181                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
3182
3183                                $from = $header->from;
3184                                $return[$j][$i]['from'] = array();
3185                                $tmp = imap_mime_header_decode($from[0]->personal);
3186                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3187                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
3188                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
3189
3190                                $to = $header->to;
3191                                $return[$j][$i]['to'] = array();
3192                                $tmp = imap_mime_header_decode($to[0]->personal);
3193                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3194                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
3195                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
3196
3197                                $subject = imap_mime_header_decode($header->fetchsubject);
3198                                $return[$j][$i]['subject'] = '';
3199                                foreach ($subject as $tmp)
3200                                        $return[$j][$i]['subject'] .= $tmp->text;
3201
3202                                $return[$j][$i]['Size'] = $header->Size;
3203                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
3204
3205                                $return[$j][$i]['attachment'] = array();
3206                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
3207
3208                                $i++;
3209                        }
3210                        $j++;
3211                        if($mbox_stream)
3212                                imap_close($mbox_stream);
3213                }
3214
3215                return $return;
3216        }
3217       
3218       
3219        function mobile_search($params)
3220        {
3221                include("class.imap_attachment.inc.php");
3222                $imap_attachment = new imap_attachment();
3223                $criterias = array ("TO","SUBJECT","FROM","CC");
3224                $return = array();
3225                $folders = $this->get_folders_list();
3226                $num_msgs = 0;
3227                                         
3228                foreach($folders as $id =>$folder)
3229                {
3230                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3231                                foreach($criterias as $criteria_fixed)
3232                    {
3233                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3234                                        $mbox_stream = $this->open_mbox($folder['folder_name']);
3235       
3236                                        $messages = imap_search($mbox_stream, $_filter, SE_UID);
3237                                       
3238                                        if ($messages == ''){
3239                                                if($mbox_stream)
3240                                                        imap_close($mbox_stream);
3241                                                continue;       
3242                                        }
3243                                                                       
3244                                        foreach($messages as $msg_number)
3245                                        {                                       
3246                                                $temp = $this->get_info_head_msg($msg_number);
3247                                                if(!$temp)
3248                                                        return false;
3249               
3250                                                $return[$num_msgs] = $temp;
3251                                                $num_msgs++;
3252                                        }
3253                                        $return['num_msgs'] = $num_msgs;
3254                                       
3255                                        if($mbox_stream)
3256                                                imap_close($mbox_stream);
3257                                }
3258                        }
3259                               
3260                }
3261                return $return;
3262        }
3263
3264        function delete_and_show_previous_message($params)
3265        {
3266                $return = $this->get_info_previous_msg($params);
3267
3268                $params_tmp1 = array();
3269                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3270                $params_tmp1['folder'] = $params['msg_folder'];
3271                $return_tmp1 = $this->delete_msg($params_tmp1);
3272
3273                $return['msg_number_deleted'] = $return_tmp1;
3274
3275                return $return;
3276        }
3277
3278
3279        function automatic_trash_cleanness($params)
3280        {
3281                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3282                $criteria =  'BEFORE "'.$before_date.'"';
3283                $trash_folder = $this->email_server['imapDefaultTrashFolder'];
3284
3285                $mbox_stream = $this->open_mbox('INBOX'.$this->email_server['imapDelimiter'].$trash_folder);
3286
3287                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3288
3289                if (is_array($messages)){
3290                        foreach ($messages as $msg_number){
3291                                imap_delete($mbox_stream, $msg_number, FT_UID);
3292                        }
3293                }
3294                if($mbox_stream)
3295                        imap_close($mbox_stream, CL_EXPUNGE);
3296                return $messages;
3297        }
3298//      Fix the search problem with special characters!!!!
3299        function remove_accents($string) {
3300                return strtr($string,
3301                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
3302                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3303        }
3304
3305        function make_search_date($date){
3306
3307            $months = array(
3308                1   => 'jan',
3309                2   => 'feb',
3310                3   => 'mar',
3311                4   => 'apr',
3312                5   => 'may',
3313                6   => 'jun',
3314                7   => 'jul',
3315                8   => 'aug',
3316                9   => 'sep',
3317                10  => 'oct',
3318                11  => 'nov',
3319                12  => 'dec'
3320            );
3321
3322            //TODO: Adaptar a data de acordo com o locale do sistema.
3323            list($day,$month,$year) = explode("/", $date);
3324            $search_date = $day."-".$months[intval($month)]."-".$year;
3325            return $search_date;
3326
3327        }
3328
3329        function search_msg($params = ''){
3330            $retorno = "";
3331            $mbox_stream = "";
3332            if(strpos($params['condition'],"#")===false) { //local messages
3333                    $search=false;
3334            }
3335            else {
3336                    $search = explode(",",$params['condition']);
3337            }
3338
3339            if($search){
3340                $search_criteria = '';
3341                $search_result_number = $this->preferences['search_result_number'];
3342                foreach($search as $tmp)
3343                {
3344                    $tmp1 = explode("##",$tmp);
3345                    $sum = 0;
3346                    $name_box = $tmp1[0];
3347                    unset($filter);
3348                    foreach($tmp1 as $index => $criteria)
3349                    {
3350                        if ($index != 0 && strlen($criteria) != 0)
3351                        {
3352                            $filter_array = explode("<=>",rawurldecode($criteria));
3353                            $filter .= " ".$filter_array[0];
3354                            if (strlen($filter_array[1]) != 0){
3355                                if (trim($filter_array[0]) != 'BEFORE' &&
3356                                    trim($filter_array[0]) != 'SINCE' &&
3357                                    trim($filter_array[0]) != 'ON')
3358                                {
3359                                    $filter .= '"'.$filter_array[1].'"';
3360                                }
3361                                else
3362                                    {
3363                                        $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3364                                    }
3365                            }
3366                        }
3367                    }
3368                    $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3369                    $filter = $this->remove_accents($filter);
3370                    //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
3371                    if ($this->preferences['uid2cn'] && substr($name_box,0,4) == 'user')
3372                    {
3373                        $folder_name = explode($this->email_server['imapDelimiter'],$name_box);
3374                        $this->ldap = new ldap_functions();
3375                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3376                        {
3377                            $folder_name[1] = $cn;
3378                        }
3379                        $folder_name = implode($this->email_server['imapDelimiter'],$folder_name);
3380                    }
3381                    else
3382                    {
3383                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3384                    }
3385
3386                    if(!is_resource($mbox_stream))
3387                    {
3388                        $mbox_stream = $this->open_mbox($name_box);
3389                    }
3390                    else
3391                        {
3392                            imap_reopen($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}".$name_box);
3393                        }
3394
3395                    if (preg_match("/^.?\bALL\b/", $filter))
3396                    { // Quick Search, note: this ALL isn't the same ALL from imap_search
3397
3398                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3399                        foreach($all_criterias as $criteria_fixed)
3400                        {
3401                            $_filter = $criteria_fixed . substr($filter,4);
3402
3403                            $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
3404
3405                            if($search_criteria) //&& count($search_criteria) < 50)
3406                            {
3407                                foreach($search_criteria as $new_search)
3408                                {
3409                                    if ($search_result_number != '65536' && $sum == $search_result_number)
3410                                    {
3411                                        return $retorno ? $sum . "=sumResults=" . $retorno : "none";
3412                                    }
3413
3414                                    $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");
3415                                    if(!@strstr($retorno,$m_token))
3416                                    {
3417                                        $retorno .= $m_token;
3418                                        $sum ++;
3419                                    }
3420                                }
3421                            }
3422                        }
3423                    }
3424                    else {
3425                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3426                        if( is_array( $search_criteria) )
3427                        {
3428                            foreach($search_criteria as $new_search)
3429                            {
3430                                if ($search_result_number != '65536' && $sum == $search_result_number)
3431                                {
3432                                    return $retorno ? $sum . "=sumResults=" . $retorno : "none";
3433                                }
3434                                $retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
3435                                $sum++;
3436                            }
3437                        }
3438                    }
3439                }
3440            }
3441            if($mbox_stream)
3442            {
3443                imap_close($mbox_stream);
3444            }
3445
3446            if ($retorno)
3447            {
3448                return $retorno;
3449            }
3450            else
3451            {
3452                return 'none';
3453            }
3454        }
3455
3456        function get_msg($uid_msg,$name_box, $mbox_stream )
3457        {
3458                $header = $this->get_header($uid_msg);
3459                include_once("class.imap_attachment.inc.php");
3460                $imap_attachment = new imap_attachment();
3461                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3462                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3463                $flag = $header->Unseen
3464                        .$header->Recent
3465                        .$header->Flagged
3466                        .$header->Draft
3467                        .$header->Answered
3468                        .$header->Deleted
3469                        .$attachments;
3470
3471
3472                $subject = $this->decode_string($header->fetchsubject);
3473                $from = $header->from[0]->mailbox;
3474                if($header->from[0]->personal != "")
3475                        $from = $header->from[0]->personal;
3476                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size) ."--". $flag;
3477                return $ret_msg;
3478        }
3479
3480        function size_msg($size){
3481                $var = floor($size/1024);
3482                if($var >= 1){
3483                        return $var." kb";
3484                }else{
3485                        return $size ." b";
3486                }
3487        }
3488
3489        function ob_array($the_object)
3490        {
3491           $the_array=array();
3492           if(!is_scalar($the_object))
3493           {
3494               foreach($the_object as $id => $object)
3495               {
3496                   if(is_scalar($object))
3497                   {
3498                       $the_array[$id]=$object;
3499                   }
3500                   else
3501                   {
3502                       $the_array[$id]=$this->ob_array($object);
3503                   }
3504               }
3505               return $the_array;
3506           }
3507           else
3508           {
3509               return $the_object;
3510           }
3511        }
3512
3513        function getacl()
3514        {
3515                $this->ldap = new ldap_functions();
3516
3517                $return = array();
3518                $mbox_stream = $this->open_mbox();
3519                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3520
3521                $i = 0;
3522                foreach ($mbox_acl as $user => $acl)
3523                {
3524                        if ($user != $this->username)
3525                        {
3526                                $return[$i]['uid'] = $user;
3527                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3528                        }
3529                        $i++;
3530                }
3531                return $return;
3532        }
3533
3534        function setacl($params)
3535        {
3536                $old_users = $this->getacl();
3537                if (!count($old_users))
3538                        $old_users = array();
3539
3540                $tmp_array = array();
3541                foreach ($old_users as $index => $user_info)
3542                {
3543                        $tmp_array[$index] = $user_info['uid'];
3544                }
3545                $old_users = $tmp_array;
3546
3547                $users = unserialize($params['users']);
3548                if (!count($users))
3549                        $users = array();
3550
3551                //$add_share = array_diff($users, $old_users);
3552                $remove_share = array_diff($old_users, $users);
3553
3554                $mbox_stream = $this->open_mbox();
3555
3556                $serverString = "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}";
3557                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->email_server['imapDelimiter'].$this->username."*");
3558
3559                /*if (count($add_share))
3560                {
3561                        foreach ($add_share as $index=>$uid)
3562                        {
3563                        if (is_array($mailboxes_list))
3564                        {
3565                        foreach ($mailboxes_list as $key => $val)
3566                        {
3567                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3568                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3569                        }
3570                        }
3571                        }
3572                }*/
3573
3574                if (count($remove_share))
3575                {
3576                        foreach ($remove_share as $index=>$uid)
3577                        {
3578                        if (is_array($mailboxes_list))
3579                        {
3580                        foreach ($mailboxes_list as $key => $val)
3581                        {
3582                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3583                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3584                        }
3585                        }
3586                        }
3587                }
3588
3589                return true;
3590        }
3591
3592        function getaclfromuser($params)
3593        {
3594                $useracl = $params['user'];
3595
3596                $return = array();
3597                $return[$useracl] = 'false';
3598                $mbox_stream = $this->open_mbox();
3599                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3600
3601                foreach ($mbox_acl as $user => $acl)
3602                {
3603                        if (($user != $this->username) && ($user == $useracl))
3604                        {
3605                                $return[$user] = $acl;
3606                        }
3607                }
3608                return $return;
3609        }
3610
3611        function getacltouser($user)
3612        {
3613                $return = array();
3614                $mbox_stream = $this->open_mbox();
3615                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->email_server['imapDelimiter'].$user);
3616                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3617                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3618                if(substr($user,0,4) != 'user')
3619                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->email_server['imapDelimiter'].$user);
3620                else
3621                  $mbox_acl = imap_getacl($mbox_stream, $user);
3622                return $mbox_acl[$this->username];
3623        }
3624
3625
3626        function setaclfromuser($params)
3627        {
3628                $user = $params['user'];
3629                $acl = $params['acl'];
3630
3631                $mbox_stream = $this->open_mbox();
3632
3633                $serverString = "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}";
3634                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->email_server['imapDelimiter'].$this->username."*");
3635
3636                if (is_array($mailboxes_list))
3637                {
3638                        foreach ($mailboxes_list as $key => $val)
3639                        {
3640                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3641                                $folder = str_replace("&-", "&", $folder);
3642                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3643                                {
3644                                        $return = imap_last_error();
3645                                }
3646                        }
3647                }
3648                if (isset($return))
3649                        return $return;
3650                else
3651                        return true;
3652        }
3653
3654        function download_attachment($msg,$msgno)
3655        {
3656                $array_parts_attachments = array();
3657                $array_parts_attachments['names'] = '';
3658                include_once("class.imap_attachment.inc.php");
3659                $imap_attachment = new imap_attachment();
3660
3661                if (count($msg->fname[$msgno]) > 0)
3662                {
3663                        $i = 0;
3664                        foreach ($msg->fname[$msgno] as $index=>$fname)
3665                        {
3666                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3667                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
3668                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3669                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3670                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3671                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3672                                $i++;
3673                        }
3674                }
3675                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3676                return $array_parts_attachments;
3677        }
3678
3679        function spam($params)
3680        {
3681                $is_spam = $params['spam'];
3682                $folder = $params['folder'];
3683                $mbox_stream = $this->open_mbox($folder);
3684                $msgs_number = explode(',',$params['msgs_number']);
3685
3686                foreach($msgs_number as $msg_number) {
3687                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3688                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3689                        $body = imap_body($mbox_stream, $imap_msg_number);
3690                        $msg = $header . $body;
3691                        $email = $this->email;
3692                        $username = $this->username;
3693                        strtok($email, '@');
3694                        $domain = strtok('@');
3695
3696                        //Encontrar a assinatura do dspam no cabecalho
3697                        $v = explode("\r\n", $header);
3698                        foreach ($v as $linha){
3699                                if (eregi("^Message-ID", $linha)) {
3700                                        $args = explode(" ", $linha);
3701                                        $msg_id = "'$args[1]'";
3702                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
3703                                        $args = explode(" ",$linha);
3704                                        $signature = $args[1];
3705                                }
3706                        }
3707
3708                        // Seleciona qual comando a ser executado
3709                        switch($is_spam){
3710                                case 'true':  $cmd = $this->command_for_spam; break;
3711                                case 'false': $cmd = $this->command_for_ham; break;
3712                        }
3713
3714                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3715                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
3716                        system($cmd);
3717                }
3718                imap_close($mbox_stream);
3719                return false;
3720        }
3721        function get_header($msg_number){
3722                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3723                if (!is_object($header))
3724                        return false;
3725                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
3726                $header->udate_original = $header->udate;
3727                $pdate = date_parse($header->MailDate);
3728                $header->udate +=  $pdate['zone']*(-60);
3729
3730                if($header->Flagged != "F" && $this->preferences['use_important_flag']) {
3731                        $flag = preg_match('/importance *: *(.*)\r/i',
3732                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3733                                                ,$importance);
3734                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3735                }
3736
3737                return $header;
3738        }
3739
3740//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Insere emails no imap a partir do fonte do mesmo. Se o argumento timestamp for passado ele utiliza do script python
3741///expressoMail1_2/imap.py para inserir uma msg com o horário correto pois isso não é porssível com a função imap_append do php.
3742
3743    function insert_email($source,$folder,$timestamp){
3744        $username = $this->username;
3745        $password = $this->password;
3746        $imap_server = $this->email_server['imapServer'];
3747        $imap_port      = $this->email_server['imapPort'];
3748        $imap_options = '/notls/novalidate-cert';
3749        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3750        if(imap_last_error())
3751        {
3752            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3753       }
3754        if($timestamp){
3755            $tempDir = ini_get("session.save_path");
3756            $file = $tempDir."imap_".$this->session_id;
3757                $f = fopen($file,"w");
3758                fputs($f,base64_encode($source));
3759            fclose($f);
3760            $command = "python ".$_SERVER['DOCUMENT_ROOT']."/expressoMail1_2/imap.py ".escapeshellarg($imap_server)." ".escapeshellarg($imap_port)." ".escapeshellarg($username)." ".escapeshellarg($password)." ".escapeshellarg($timestamp)." ".escapeshellarg($folder)." ".escapeshellarg($file);
3761            $return['command']=exec(escapeshellcmd($command));
3762        }else{
3763            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3764        }
3765        $status = imap_status($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort']."}".$folder, SA_UIDNEXT);
3766        $return['msg_no'] = $status->uidnext - 1;
3767                $return['error'] = imap_last_error();
3768        if($mbox_stream)
3769                        imap_close($mbox_stream);
3770        return $return;
3771
3772    }
3773
3774    function show_decript($params){
3775        $source = $params['source'];
3776        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3777        $source = str_replace(" ", "+", $source,$i);
3778
3779        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3780            if(!$source = base64_decode($source,true))
3781                return "error ".$source."Espaços ".$i;
3782
3783        }
3784        else {
3785            if(!$source = base64_decode($source))
3786                return "error ".$source."Espaços ".$i;
3787        }
3788
3789        $insert = $this->insert_email($source,'INBOX'.$this->email_server['imapDelimiter'].'decifradas');
3790
3791                $get['msg_number'] = $insert['msg_no'];
3792                $get['msg_folder'] = 'INBOX'.$this->email_server['imapDelimiter'].'decifradas';
3793                $return = $this->get_info_msg($get);
3794                $get['msg_number'] = $params['ID'];
3795                $get['msg_folder'] = $params['folder'];
3796                $tmp = $this->get_info_msg($get);
3797                if(!$tmp['status_get_msg_info'])
3798                {
3799                        $return['msg_day']=$tmp['msg_day'];
3800                        $return['msg_hour']=$tmp['msg_hour'];
3801                        $return['fulldate']=$tmp['fulldate'];
3802                        $return['smalldate']=$tmp['smalldate'];
3803                }
3804                else
3805                {
3806                        $return['msg_day']='';
3807                        $return['msg_hour']='';
3808                        $return['fulldate']='';
3809                        $return['smalldate']='';
3810                }
3811        $return['msg_no'] =$insert['msg_no'];
3812        $return['error'] = $insert['error'];
3813        $return['folder'] = $params['folder'];
3814        //$return['acls'] = $insert['acls'];
3815        $return['original_ID'] =  $params['ID'];
3816
3817        return $return;
3818
3819    }
3820
3821//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Trata fontes de emails enviados via POST para o servidor por um xmlhttprequest, as partes codificados com
3822//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
3823
3824    function treat_base64_from_post($source){
3825            $offset = 0;
3826            do
3827            {
3828                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
3829                    {
3830                            $inicio = strpos($source, "\n\r", $inicio);
3831                            $fim = strpos($source, '--', $inicio);
3832                            if(!$fim)
3833                                    $fim = strpos($source,"\n\r", $inicio);
3834                            $length = $fim-$inicio;
3835                            $parte = substr( $source,$inicio,$length-1);
3836                            $parte = str_replace(" ", "+", $parte);
3837                            $source = substr_replace($source, $parte, $inicio, $length-1);
3838                    }
3839                    if($offset > $inicio)
3840                    $offset=FALSE;
3841                    else
3842                    $offset = $inicio;
3843            }
3844            while($offset);
3845            return $source;
3846    }
3847
3848//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Recebe os fontes dos emails a serem desarquivados, separa e envia cada um para função insert_mail.
3849
3850    function unarchive_mail($params)
3851    {
3852        $dest_folder = $params['folder'];
3853        $sources = explode("#@#@#@",$params['source']);
3854        $timestamps = explode("#@#@#@",$params['timestamp']);
3855        foreach($sources as $index=>$src) {
3856                        if($src!=""){
3857                                $source = $this->treat_base64_from_post($src);
3858                                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index]);
3859                        }
3860                }
3861        return $insert;
3862    }
3863
3864    function download_all_local_attachments($params)
3865    {
3866        $source = $params['source'];
3867        $source = $this->treat_base64_from_post($source);
3868        $insert = $this->insert_email($source,'INBOX'.$this->email_server['imapDelimiter'].'decifradas');
3869        $exporteml = new ExportEml();
3870        $params['num_msg']=$insert['msg_no'];
3871        $params['folder']='INBOX'.$this->email_server['imapDelimiter'].'decifradas';
3872        return $exporteml->download_all_attachments($params);
3873    }
3874
3875    function get_quota_folders(){
3876       
3877        // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
3878                include_once("class.imapfp.inc.php");           
3879                $imapfp = new imapfp();
3880               
3881            if(!$imapfp->open($this->email_server['imapServer'],$this->email_server['imapPort']))
3882                return $imapfp->get_error();           
3883                if (!$imapfp->login( $this->username,$this->password ))
3884                return $imapfp->get_error();
3885                   
3886            $response_array = $imapfp->get_mailboxes_size();
3887            if ($imapfp->error)
3888                return $imapfp->get_error();
3889           
3890            $data = array();
3891            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
3892        $data["quota_root"] = $quota_root;
3893           
3894            foreach ($response_array as $idx=>$line) {
3895                        $line2 = str_replace('"', "", $line);
3896                        $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
3897                        list($folder,$size) = explode(";",$line2);
3898                        $size = str_replace(")","",$size);
3899                        $quotaPercent = (($size / 1048576) / $data["quota_root"]["quota_limit"])*100;
3900                        if ($size < 1048576 && $size > 1024)
3901                                $quota_used = round($size / 1024, 0).' Kb';
3902                        else if($size > 1024)
3903                                $quota_used = round($size / (1024*1024), 1).' Mb';
3904                        else
3905                                $quota_used = $size." b";
3906                        $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
3907                        if(!preg_match('/user\\'.$this->email_server['imapDelimiter'].$this->username.'\\'.$this->email_server['imapDelimiter'].'/i',$folder)){
3908                                $folder = $this->functions->getLang("Inbox");
3909                        }
3910                        else
3911                                $folder = preg_replace('/user\\'.$this->email_server['imapDelimiter'].$this->username.'\\'.$this->email_server['imapDelimiter'].'/i','', $folder);
3912                       
3913                        $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
3914            }
3915            $imapfp->close();
3916        return $data;
3917        }
3918}
3919?>
Note: See TracBrowser for help on using the repository browser.