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

Revision 2597, 140.4 KB checked in by amuller, 14 years ago (diff)

Ticket #1047 - Não puxar o corpo quando a preferência não está habilitada

  • 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,serialize($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                                $img = "<IMG id='".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' style='border:2px solid #fde7bc;padding:5px' title='".$this->functions->getLang("Click here do view (+)")."'src=./inc/show_thumbs.php?file_type=".$file_type."&msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index].">";
1427                                $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]."' onClick=\"window.open('./inc/show_img.php?msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index]."','mywindow','width=700,height=600,scrollbars=yes');\">". $img ."</a>";
1428                                        $thumbs_array[] = $href;
1429                        }
1430                        $i++;
1431                }
1432        }
1433        return $thumbs_array;
1434        }
1435
1436        /*function delete_msg($params)
1437        {
1438                $folder = $params['folder'];
1439                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
1440
1441                $mbox_stream = $this->open_mbox($folder);
1442
1443                foreach ($msgs_to_delete as $msg_number){
1444                        imap_delete($mbox_stream, $msg_number, FT_UID);
1445                }
1446                imap_close($mbox_stream, CL_EXPUNGE);
1447                return $params['msgs_to_delete'];
1448        }*/
1449
1450        // Novo
1451        function delete_msgs($params)
1452        {
1453
1454                $folder = $params['folder'];
1455                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
1456                $msgs_number = explode(",",$params['msgs_number']);
1457                $border_ID = $params['border_ID'];
1458
1459                $return = array();
1460
1461                if ($params['get_previous_msg']){
1462                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1463                        // Fix problem in unserialize function JS.
1464                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1465                }
1466
1467                //$mbox_stream = $this->open_mbox($folder);
1468                $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()))));
1469
1470                foreach ($msgs_number as $msg_number)
1471                {
1472                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1473                                $return['msgs_number'][] = $msg_number;
1474                }
1475
1476                $return['folder'] = $folder;
1477                $return['border_ID'] = $border_ID;
1478
1479                if($mbox_stream)
1480                        imap_close($mbox_stream, CL_EXPUNGE);
1481                return $return;
1482        }
1483
1484
1485        function refresh($params)
1486        {
1487                include_once("class.imap_attachment.inc.php");
1488                $imap_attachment = new imap_attachment();
1489                $folder = $params['folder'];
1490                $msg_range_begin = $params['msg_range_begin'];
1491                $msg_range_end = $params['msg_range_end'];
1492                $msgs_existent = $params['msgs_existent'];
1493                $sort_box_type = $params['sort_box_type'];
1494                $sort_box_reverse = $params['sort_box_reverse'];
1495                $msgs_in_the_server = array();
1496                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1497                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1498                $msgs_in_the_server = array_keys($msgs_in_the_server);
1499                if(!count($msgs_in_the_server))
1500                        return array();
1501
1502                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
1503                $msgs_in_the_client = explode(",", $msgs_existent);
1504
1505                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
1506                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
1507
1508                $msgs_to_exec = array();
1509                if ((count($msg_to_insert)) && ($msgs_existent))
1510                {
1511                        foreach($msg_to_insert as $index => $msg_number)
1512                        {
1513                                if ($msgs_in_the_server[$index+1])
1514                                {
1515                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
1516                                        $msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
1517                                }
1518                                else
1519                                {
1520                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
1521                                        $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1522                                }
1523                        }
1524                        ksort($msgs_to_exec);
1525                }
1526                elseif(!$msgs_existent)
1527                {
1528                        foreach($msgs_in_the_server as $index => $msg_number)
1529                        {
1530                                $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1531                        }
1532                }
1533
1534                $return = array();
1535                $i = 0;
1536                foreach($msgs_to_exec as $msg_number => $command)
1537                {
1538                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
1539                        * atributos do cabeçalho. Como eu preciso do atributo Importance
1540                        * para saber se o email é importante ou não, uso abaixo a função
1541                        * imap_fetchheader e busco o atributo importance nela para passar
1542                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1543                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1544                        * não preciso reimplementar o método utilizando o fetchheader.
1545                        * Como na atualização são poucas as mensagens que devem ser renderizadas,
1546                        * a perda em performance é insignificante.
1547                        */
1548            $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1549                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
1550                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
1551
1552                        $msg_sample = $this->get_msg_sample($msg_number);
1553                        $return[$i]['msg_sample'] = $msg_sample;
1554
1555                        $header = $this->get_header($msg_number);
1556                        if (!is_object($header))
1557                                continue;
1558
1559                        $return[$i]['msg_number']       = $msg_number;
1560                        $return[$i]['command']          = $command;
1561
1562                        $return[$i]['msg_folder']       = $folder;
1563            // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1564            $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
1565                        $return[$i]['Recent']           = $header->Recent;
1566                        $return[$i]['Unseen']           = $header->Unseen;
1567                        $return[$i]['Answered']         = $header->Answered;
1568                        $return[$i]['Deleted']          = $header->Deleted;
1569                        $return[$i]['Draft']            = $header->Draft;
1570                        $return[$i]['Flagged']          = $header->Flagged;
1571
1572                        $date_msg = gmdate("d/m/Y",$header->udate);
1573                        if (gmdate("d/m/Y") == $date_msg)
1574                                $return[$i]['udate'] = gmdate("H:i",$header->udate);
1575                        else
1576                                $return[$i]['udate'] = $date_msg;
1577
1578                        $from = $header->from;
1579                        $return[$i]['from'] = array();
1580                        $tmp = imap_mime_header_decode($from[0]->personal);
1581                        $return[$i]['from']['name'] = $tmp[0]->text;
1582                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
1583                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
1584                        if(!$return[$i]['from']['name'])
1585                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
1586
1587                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1588                        $return[$i]['toaddress'] = '';
1589                        foreach ($toaddress as $tmp)
1590                                $return[$i]['toaddress'] .= $tmp->text;*/
1591                        $to = $header->to;
1592                        $return[$i]['to'] = array();
1593                        $tmp = imap_mime_header_decode($to[0]->personal);
1594                        $return[$i]['to']['name'] = $tmp[0]->text;
1595                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1596                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
1597
1598                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1599
1600                        $return[$i]['Size'] = $header->Size;
1601                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
1602
1603                        $return[$i]['attachment'] = array();
1604                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
1605                        $i++;
1606                }
1607                $return['new_msgs'] = imap_num_recent($this->mbox);
1608                $return['msgs_to_delete'] = $msg_to_delete;
1609                if($this->mbox && is_resource($this->mbox))
1610                        imap_close($this->mbox);
1611
1612                return $return;
1613        }
1614
1615     /**
1616     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1617     * assinado ou cifrado.
1618     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1619     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1620     * @param $msg_number O número da mesagem
1621     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1622     */
1623    function getMessageType($msg_number, $headers = false){
1624
1625            $contentType = "normal";
1626            if (!$headers){
1627                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1628            }
1629            //$header2 = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1630            if (preg_match("/Content-Type:.*pkcs7-signature/i", $headers) == 1){
1631                $contentType = "signature";
1632            } else if (preg_match("/Content-Type:.*x-pkcs7-mime/i", $headers) == 1){
1633                $contentType = "cipher";
1634            }
1635
1636            return $contentType;
1637    }
1638
1639         /**
1640     * Metodo que retorna todas as pastas do usuario logado.
1641     * @param $params array opcional para repassar os argumentos ao metodo.
1642     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
1643     * excluindo as compartilhadas para ele.
1644     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
1645     * folder_id, folder_name, folder_parent e folder_hasChildren.
1646     */
1647        function get_folders_list($params = null)
1648        {
1649                $inbox = 'INBOX';
1650                $trash = $inbox . $this->email_server['imapDelimiter ']. $this->email_server['imapDefaultTrashFolder;'];
1651                $drafts = $inbox . $this->email_server['imapDelimiter ']. $this->email_server['imapDefaultDraftsFolder'];
1652                $spam = $inbox . $this->email_server['imapDelimiter ']. $this->email_server['imapDefaultSpamFolder'];
1653                $sent = $inbox . $this->email_server['imapDelimiter ']. $this->email_server['imapDefaultSentFolder'];
1654                $uid2cn = $this->preferences['uid2cn'];
1655
1656                if(!$this->mbox || !is_resource($this->mbox))
1657                        $this->mbox = $this->open_mbox();
1658
1659                if($params && $params['onload'] && $this->cert){
1660                        $this->delete_mailbox(array("del_past" => "INBOX/decifradas"));
1661                }
1662
1663                $serverString = "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}";
1664                $folders_list = imap_getmailboxes($this->mbox, $serverString, ($params && $params['noSharedFolders']) ? "INBOX/*" : "*");
1665                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1666
1667                $tmp = array();
1668                $resultMine = array();
1669                $resultDefault = array();
1670
1671                if (is_array($folders_list)) {
1672                        reset($folders_list);
1673                        $this->ldap = new ldap_functions();
1674
1675                        $i = 0;
1676                        while (list($key, $val) = each($folders_list)) {
1677                                $status = imap_status($this->mbox, $val->name, SA_UNSEEN);
1678
1679                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1680                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
1681                                if($tmp_folder_id[1]=='INBOX'.$this->email_server['imapDelimiter'].'decifradas') {
1682                                        //error_log('passou', 3,'/tmp/imap_get_list.log');
1683                                        //imap_deletemailbox($this->mbox, imap_utf7_encode("{".$this->email_server['imapServer']."}".'INBOX/decifradas'));
1684                                        continue;
1685                                }
1686                                $result[$i]['folder_unseen'] = $status->unseen;
1687                                $folder_id = $tmp_folder_id[1];
1688                                $result[$i]['folder_id'] = $folder_id;
1689
1690                                $tmp_folder_parent = explode($this->email_server['imapDelimiter'], $folder_id);
1691                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1692                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1693                                if ($uid2cn && substr($folder_id,0,4) == 'user') {
1694                                        //$this->ldap = new ldap_functions();
1695                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
1696                                                $result[$i]['folder_name'] = $cn;
1697                                        }
1698                                }
1699
1700                                $tmp_folder_parent = implode($this->email_server['imapDelimiter'], $tmp_folder_parent);
1701                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
1702
1703                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1704                                        $result[$i]['folder_hasChildren'] = 1;
1705                                else
1706                                        $result[$i]['folder_hasChildren'] = 0;
1707
1708                                switch ($tmp_folder_id[1]) {
1709                                        case $inbox:
1710                                        case $sent:
1711                                        case $drafts:
1712                                        case $spam:
1713                                        case $trash:
1714                                                $resultDefault[]=$result[$i];
1715                                        default:
1716                                                $resultMine[]=$result[$i];
1717                                }
1718
1719                                $i++;
1720                        }
1721                }
1722
1723                // Sorting resultMine
1724                foreach ($resultMine as $folder_info)
1725                {
1726                        $array_tmp[] = $folder_info['folder_id'];
1727                }
1728
1729                natcasesort($array_tmp);
1730
1731                foreach ($array_tmp as $key => $folder_id)
1732                {
1733                        $result2[] = $resultMine[$key];
1734                }
1735               
1736                $resultDefault2=$resultDefault;
1737                // Sorting resultDefault
1738                foreach ($resultDefault as $key => $folder_id)
1739                {
1740
1741                        switch ($resultDefault[$key]['folder_id']) {
1742                                case $inbox:
1743                                        $resultDefault2[0] = $resultDefault[$key];
1744                                        break;
1745                                case $sent:
1746                                        $resultDefault2[1] = $resultDefault[$key];
1747                                        break;
1748                                case $drafts:
1749                                        $resultDefault2[2] = $resultDefault[$key];
1750                                        break;
1751                                case $spam:
1752                                        $resultDefault2[3] = $resultDefault[$key];
1753                                        break;
1754                                case $trash:
1755                                        $resultDefault2[4] = $resultDefault[$key];
1756                                        break;
1757                        }
1758                }
1759
1760                // Merge default folders and mines
1761                $result2 = array_merge($resultDefault2, $result2);
1762               
1763                $current_folder = "INBOX";
1764                if($params && $params['folder'])
1765                        $current_folder = $params['folder'];
1766                return array_merge($result2, $this->get_quota(array('folder_id' => $current_folder)));
1767        }
1768
1769        function create_mailbox($arr)
1770        {
1771                $namebox        = $arr['newp'];
1772                $mbox_stream = $this->open_mbox();
1773                $imap_server = $this->email_server['imapServer'];
1774                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
1775
1776                $result = "Ok";
1777                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
1778                {
1779                        $result = implode("<br />\n", imap_errors());
1780                }
1781
1782                if($mbox_stream)
1783                        imap_close($mbox_stream);
1784
1785                return $result;
1786
1787        }
1788
1789        function create_extra_mailbox($arr)
1790        {
1791                $nameboxs = explode(";",$arr['nw_folders']);
1792                $result = "";
1793                $mbox_stream = $this->open_mbox();
1794                $imap_server = $this->email_server['imapServer'];
1795                foreach($nameboxs as $key=>$tmp){
1796                        if($tmp != ""){
1797                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1798                                        $result = implode("<br />\n", imap_errors());
1799                                        if($mbox_stream)
1800                                                imap_close($mbox_stream);
1801                                        return $result;
1802                                }
1803                        }
1804                }
1805                if($mbox_stream)
1806                        imap_close($mbox_stream);
1807                return true;
1808        }
1809
1810        function delete_mailbox($arr)
1811        {
1812                $namebox = $arr['del_past'];
1813                $imap_server = $this->email_server['imapServer'];
1814                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
1815                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
1816
1817                $result = "Ok";
1818                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1819                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1820                {
1821                        $result = implode("<br />\n", imap_errors());
1822                }
1823                /*
1824                if($mbox_stream)
1825                        imap_close($mbox_stream);
1826                */
1827                return $result;
1828        }
1829
1830        function ren_mailbox($arr)
1831        {
1832                $namebox = $arr['current'];
1833                $new_box = $arr['rename'];
1834                $imap_server = $this->email_server['imapServer'];
1835                $mbox_stream = $this->open_mbox();
1836                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
1837
1838                $result = "Ok";
1839                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1840                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
1841                if(!$this->folder_exists($new_box))
1842                {
1843                        if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1844                        {
1845                                $result = imap_errors();
1846                        }
1847                }
1848                else{
1849                        $result = "Mailbox already exists";
1850                }
1851                if($mbox_stream)
1852                        imap_close($mbox_stream);
1853                return $result;
1854
1855        }
1856
1857        function get_num_msgs($params)
1858        {
1859                $folder = $params['folder'];
1860                if(!$this->mbox || !is_resource($this->mbox)) {
1861                        $this->mbox = $this->open_mbox($folder);
1862                        if(!$this->mbox || !is_resource($this->mbox))
1863                        return imap_last_error();
1864                }
1865                $num_msgs = imap_num_msg($this->mbox);
1866                if($this->mbox && is_resource($this->mbox))
1867                        imap_close($this->mbox);
1868
1869                return $num_msgs;
1870        }
1871
1872        function folder_exists($folder){
1873                $mbox =  $this->open_mbox();
1874                $serverString = "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}";             
1875                $list = imap_getmailboxes($mbox,$serverString, $folder);
1876                $return = is_array($list);             
1877                imap_close($mbox);
1878                return $return;
1879        }
1880       
1881        function send_mail($params)
1882        {
1883                include_once("class.phpmailer.php");
1884                $mail = new PHPMailer();
1885                $mail->email_server = $this->email_server;
1886                $mail->username = $this->username;
1887                $mail->password = $this->password;
1888                $mail->session_id = $this->session_id;
1889
1890                // Set lang for PHPMailer using user prefs.
1891                list($prefix,$userlang) = explode('-',$this->lang);
1892                $mail->SetLanguage($userlang,dirname( __FILE__ )."/../setup/");
1893                include_once("class.db_functions.inc.php");
1894                $db = new db_functions();
1895                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
1896                ##
1897                # @AUTHOR Rodrigo Souza dos Santos
1898                # @DATE 2008/09/17
1899                # @BRIEF Checks if the user has permission to send an email with the email address used.
1900                ##
1901                if ( is_array($fromaddress) && ($fromaddress[1] != $this->email) )
1902                {
1903                        $deny = true;
1904                        foreach( $this->shared_mailboxes as $key => $val )
1905                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
1906                                        $deny = false and end($this->shared_mailboxes);
1907
1908                        if ( $deny )
1909                                return "The server denied your request to send a mail, you cannot use this mail address.";
1910                }
1911
1912                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1913                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1914                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1915                $subject = $params['input_subject'];
1916                $msg_uid = $params['msg_id'];
1917                $return_receipt = $params['input_return_receipt'];
1918                $is_important = $params['input_important_message'];
1919        $encrypt = $params['input_return_cripto'];
1920                $signed = $params['input_return_digital'];
1921
1922                if($params['smime'])
1923        {
1924            $body = $params['smime'];
1925            $mail->SMIME = true;
1926            // A MSG assinada deve ser testada neste ponto.
1927            // Testar o certificado e a integridade da msg....
1928            include_once(dirname( __FILE__ )."/../../security/classes/CertificadoB.php");
1929            $erros_acumulados = '';
1930            $certificado = new certificadoB();
1931            $validade = $certificado->verificar($body);
1932            if(!$validade)
1933            {
1934                foreach($certificado->erros_ssl as $linha_erro)
1935                {
1936                    $erros_acumulados .= $linha_erro;
1937                }
1938            }
1939            else
1940            {
1941                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
1942                if ($certificado->apresentado)
1943                {
1944                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
1945                    if($certificado->dados['CPF'] != $this->username) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
1946                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
1947                }
1948                else
1949                {
1950                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
1951                }
1952            }
1953            if(!$erros_acumulados =='')
1954            {
1955                return $erros_acumulados;
1956            }
1957        }
1958        else
1959        {
1960            $body = $params['body'];
1961        }
1962                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
1963                $attachments = $params['FILES'];
1964                $forwarding_attachments = $params['forwarding_attachments'];
1965                $local_attachments = $params['local_attachments'];
1966               
1967                //Test if must be saved in shared folder and change if necessary
1968                if( $fromaddress[2] == 'y' ){
1969                        //build shared folder path
1970                        $newfolder = "user".$this->email_server['imapDelimiter'].$fromaddress[3].$this->email_server['imapDelimiter'].$this->imap_sentfolder;
1971                        if( $this->folder_exists($newfolder) ) $folder = $newfolder;
1972                        else $folder =  $params['folder'];                     
1973                } else  {
1974                        $folder = $params['folder'];                   
1975                }
1976               
1977                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
1978                $folder_name = $params['folder_name'];
1979                // Fix problem with cyrus delimiter changes.
1980                // Dots in names: enabled/disabled.
1981                $folder = @eregi_replace("INBOX/", "INBOX".$this->email_server['imapDelimiter'], $folder);
1982                $folder = @eregi_replace("INBOX.", "INBOX".$this->email_server['imapDelimiter'], $folder);
1983                // End Fix.
1984                if ($folder != 'null'){
1985                        $mail->SaveMessageInFolder = $folder;
1986                }
1987////////////////////////////////////////////////////////////////////////////////////////////////////
1988                $mail->SMTPDebug = false;
1989
1990                if($signed && !$params['smime'])
1991                {
1992            $mail->Mailer = "smime";
1993                        $mail->SignedBody = true;
1994                }
1995                else
1996            $mail->IsSMTP();
1997
1998                $mail->Host = $this->email_server['smtpServer'];
1999                $mail->Port = $this->email_server['smtpPort'];
2000                $mail->From = $this->email;
2001                $mail->FromName = $this->fullname;
2002                if($fromaddress){
2003                        $mail->Sender = $mail->From;
2004                        $mail->SenderName = $mail->FromName;
2005                        $mail->FromName = $fromaddress[0];
2006                        $mail->From = $fromaddress[1];
2007                }
2008
2009                $this->add_recipients("to", $toaddress, &$mail);
2010                $this->add_recipients("cc", $ccaddress, &$mail);
2011                $this->add_recipients("cco", $ccoaddress, &$mail);
2012                $mail->Subject = $subject;
2013                $mail->IsHTML(true);
2014                $mail->Body = $body;
2015
2016        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
2017                {
2018                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2019            $email = explode(",",$email);
2020            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2021            // Deve ser verificado um numero limite de destinatarios.
2022            // Deve ser verificado se os certificados sao validos.
2023            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2024            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2025            $numero_maximo = $this->preferences['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2026            $erros_acumulados = "";
2027            $aux_mails = array();
2028            $mail_list = array();
2029            if(count($email) > $numero_maximo)
2030            {
2031                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2032                return $erros_acumulados;
2033            }
2034            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2035            $email[] = $this->email;
2036            foreach($email as $item)
2037            {
2038                $certificate = $db->get_certificate(strtolower($item));
2039                if(!$certificate)
2040                {
2041                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2042                    return $erros_acumulados;
2043                }
2044
2045                if (array_key_exists("dberr1", $certificate))
2046                {
2047
2048                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2049                    return $erros_acumulados;
2050                                }
2051                if (array_key_exists("dberr2", $certificate))
2052                {
2053                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2054                    //continue;
2055                }
2056                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2057                if (!array_key_exists("certs", $certificate))
2058                {
2059                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2060                    continue;
2061                }
2062            */
2063                include_once("../security/classes/CertificadoB.php");
2064
2065                foreach ($certificate['certs'] as $registro)
2066                {
2067                    $c1 = new certificadoB();
2068                    $c1->certificado($registro['chave_publica']);
2069                    if ($c1->apresentado)
2070                    {
2071                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2072                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2073                        {
2074                            $aux_mails[] = $registro['chave_publica'];
2075                            $mail_list[] = strtolower($item);
2076                        }
2077                        else
2078                        {
2079                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2080                            {
2081                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2082                                    $c1->dados['EXPIRADO'],$c2->revogado);
2083                            }
2084
2085                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2086                            foreach($c2->erros_ssl as $linha)
2087                            {
2088                                $erros_acumulados .=  $linha . chr(0x0A);
2089                            }
2090                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2091                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2092                        }
2093                    }
2094                    else
2095                    {
2096                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2097                    }
2098                }
2099                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2100                                {
2101                                        return $erros_acumulados;
2102                        }
2103            }
2104
2105            $mail->Certs_crypt = $aux_mails;
2106        }
2107
2108////////////////////////////////////////////////////////////////////////////////////////////////////
2109                //      Build CID for embedded Images!!!
2110                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2111                $cid_imgs = '';
2112                $name_cid_files = array();
2113                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2114                $cid_array = array();
2115                foreach($cid_imgs[6] as $j => $val){
2116                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2117                        {
2118                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2119                        }
2120                        $cid = $cid_array[$cid_imgs[4][$j].$val];
2121                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2122
2123                                if (!$forwarding_attachments[$cid_imgs[6][$j]-2]) // The image isn't in the same mail?
2124                                {
2125                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2126                                        $fileName = "image_".($j).".jpg";
2127                                        $fileCode = "base64";
2128                                        $fileType = "image/jpg";
2129                                }
2130                                else
2131                                {
2132                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2133                                        $file_description = unserialize(rawurldecode($attach_img));
2134
2135                                        foreach($file_description as $i => $descriptor){
2136                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2137                                        }
2138                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $cid_imgs[4][$j], $file_description[3], 'base64');
2139                                        $fileName = $file_description[2];
2140                                        $fileCode = $file_description[4];
2141                                        $fileType = $this->get_file_type($file_description[2]);
2142                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2143                                }
2144                                $tempDir = ini_get("session.save_path");
2145                                $file = "cidimage_".$this->session_id.$cid_imgs[6][$j].".dat";
2146                                $f = fopen($tempDir.'/'.$file,"w");
2147                                fputs($f,$fileContent);
2148                                fclose($f);
2149                                if ($fileContent)
2150                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2151                                //else
2152                                //      return "Error loading image attachment content";
2153
2154                }
2155////////////////////////////////////////////////////////////////////////////////////////////////////
2156                //      Build Uploading Attachments!!!
2157                if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
2158                {
2159                        $total_uploaded_size = 0;
2160                        $upload_max_filesize = str_replace("M","",$this->preferences['max_attachment_size']) * 1024 * 1024;
2161                        foreach ($attachments as $attach)
2162                        {
2163                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2164                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2165                        }
2166                        if( $total_uploaded_size > $upload_max_filesize)
2167                                return $this->parse_error("message file too big");
2168                }
2169                else if(($params['is_local_forward']=="1") && (count($local_attachments))) { //Caso seja forward de mensagens locais
2170
2171                        $total_uploaded_size = 0;
2172                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
2173                        foreach($local_attachments as $local_attachment) {
2174                                $file_description = unserialize(rawurldecode($local_attachment));
2175                                $tmp = array_values($file_description);
2176                                foreach($file_description as $i => $descriptor){
2177                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2178                                }
2179                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2180                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2181                        }
2182                        if( $total_uploaded_size > $upload_max_filesize)
2183                                return 'false';
2184                }
2185////////////////////////////////////////////////////////////////////////////////////////////////////
2186                //      Build Forwarding Attachments!!!
2187                if (count($forwarding_attachments) > 0)
2188                {
2189                        // Bug fixed for array_search function
2190                        if(count($name_cid_files) > 0) {
2191                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2192                                $name_cid_files[0] = null;
2193                        }
2194
2195                        foreach($forwarding_attachments as $forwarding_attachment)
2196                        {
2197                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2198                                        $tmp = array_values($file_description);
2199                                        foreach($file_description as $i => $descriptor){
2200                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2201                                        }
2202                                        $file_description = $tmp;
2203                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2204                                        $fileName = $file_description[2];
2205                                        if(!array_search(trim($fileName),$name_cid_files)) {
2206                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2207                                }
2208                        }
2209                }
2210
2211////////////////////////////////////////////////////////////////////////////////////////////////////
2212                // Important message
2213                if($is_important)
2214                        $mail->isImportant();
2215
2216////////////////////////////////////////////////////////////////////////////////////////////////////
2217                // Disposition-Notification-To
2218                if ($return_receipt)
2219                        $mail->ConfirmReadingTo = $this->email;
2220////////////////////////////////////////////////////////////////////////////////////////////////////
2221
2222                $sent = $mail->Send();
2223
2224                if(!$sent)
2225                {
2226                        return $this->parse_error($mail->ErrorInfo);
2227                }
2228                else
2229                {
2230            if ($signed && !$params['smime'])
2231                        {
2232                                return $sent;
2233                        }
2234                        if($this->enable_log_messages == "True")
2235                        {
2236                                $userid = $this->username;
2237                                $userip = $this->session_ip;
2238                                $now = date("d/m/y H:i:s");
2239                                $addrs = $toaddress.$ccaddress.$ccoaddress;
2240                                $sent = trim($sent);
2241                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2242                        }
2243                        if($this->preferences['number_of_contacts'] &&
2244                           $this->preferences['use_dynamic_contacts']) {
2245                                $contacts = new dynamic_contacts();
2246                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2247                                return array("success" => true, "new_contacts" => $new_contacts);
2248                        }
2249                        return array("success" => true);
2250                }
2251        }
2252
2253    function add_recipients_cert($full_address)
2254        {
2255                $result = "";
2256                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2257                foreach ($parse_address as $val)
2258                {
2259                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2260                        if ($val->mailbox == "INVALID_ADDRESS")
2261                                continue;
2262                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2263                                continue;
2264                        if (empty($val->personal))
2265                                $result .= $val->mailbox."@".$val->host . ",";
2266                        else
2267                                $result .= $val->mailbox."@".$val->host . ",";
2268                }
2269
2270                return substr($result,0,-1);
2271        }
2272
2273        function add_recipients($recipient_type, $full_address, $mail)
2274        {
2275                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2276                foreach ($parse_address as $val)
2277                {
2278                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2279                        if ($val->mailbox == "INVALID_ADDRESS")
2280                                continue;
2281
2282                        if (empty($val->personal))
2283                        {
2284                                switch($recipient_type)
2285                                {
2286                                        case "to":
2287                                                $mail->AddAddress($val->mailbox."@".$val->host);
2288                                                break;
2289                                        case "cc":
2290                                                $mail->AddCC($val->mailbox."@".$val->host);
2291                                                break;
2292                                        case "cco":
2293                                                $mail->AddBCC($val->mailbox."@".$val->host);
2294                                                break;
2295                                }
2296                        }
2297                        else
2298                        {
2299                                switch($recipient_type)
2300                                {
2301                                        case "to":
2302                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2303                                                break;
2304                                        case "cc":
2305                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2306                                                break;
2307                                        case "cco":
2308                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2309                                                break;
2310                                }
2311                        }
2312                }
2313                return true;
2314        }
2315
2316        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2317        {
2318                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
2319                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
2320                if($encoding == 'base64')
2321                        # The function imap_base64 adds a new line
2322                        # at ASCII text, with CRLF line terminators.
2323                        # So is being exchanged for base64_decode.
2324                        #
2325                        #$fileContent = imap_base64($fileContent);
2326                        $fileContent = base64_decode($fileContent);
2327                else if($encoding == 'quoted-printable')
2328                        $fileContent = quoted_printable_decode($fileContent);
2329                return $fileContent;
2330        }
2331
2332        function del_last_caracter($string)
2333        {
2334                $string = substr($string,0,(strlen($string) - 1));
2335                return $string;
2336        }
2337
2338        function del_last_two_caracters($string)
2339        {
2340                $string = substr($string,0,(strlen($string) - 2));
2341                return $string;
2342        }
2343
2344        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
2345        {
2346                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
2347                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2348                        foreach($imapsort as $iuid)
2349                                $sort[$iuid] = "";
2350                       
2351                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2352                                $slice_array = false;
2353                        else
2354                                $slice_array = true;
2355                }
2356                else
2357                {
2358                        $sort = array();
2359                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2360                        $num_msgs = imap_num_msg($this->mbox);
2361                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
2362                        $slice_array = true;
2363
2364                        for ($i=$num_msgs; $i>0; $i--)
2365                        {
2366                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2367                                        break;
2368                                $iuid = @imap_uid($this->mbox,$i);
2369                                $header = $this->get_header($iuid);
2370                                // List UNSEEN messages.
2371                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2372                                        continue;
2373                                }
2374                                // List SEEN messages.
2375                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2376                                        continue;
2377                                }
2378                                // List ANSWERED messages.
2379                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2380                                        continue;
2381                                }
2382                                // List FLAGGED messages.
2383                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2384                                        continue;
2385                                }
2386
2387                                if($sort_box_type=='SORTFROM') {
2388                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $this->email)
2389                                                $from = $header->to;
2390                                        else
2391                                                $from = $header->from;
2392
2393                                        $tmp = imap_mime_header_decode($from[0]->personal);
2394
2395                                        if ($tmp[0]->text != "")
2396                                                $sort[$iuid] = $tmp[0]->text;
2397                                        else
2398                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2399                                }
2400                                else if($sort_box_type=='SORTSUBJECT') {
2401                                        $sort[$iuid] = $header->subject;
2402                                }
2403                                else if($sort_box_type=='SORTSIZE') {
2404                                        $sort[$iuid] = $header->Size;
2405                                }
2406                                else {
2407                                        $sort[$iuid] = $header->udate;
2408                                }
2409
2410                        }
2411                        natcasesort($sort);
2412
2413                        if ($sort_box_reverse)
2414                                $sort = array_reverse($sort,true);
2415                }
2416
2417                if(!is_array($sort))
2418                        $sort = array();
2419
2420
2421                if ($slice_array)
2422                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
2423
2424
2425                return $sort;
2426
2427        }
2428
2429
2430        function move_search_messages($params){
2431                $params['selected_messages'] = urldecode($params['selected_messages']);
2432                $params['new_folder'] = urldecode($params['new_folder']);
2433                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2434                $sel_msgs = explode(",", $params['selected_messages']);
2435                @reset($sel_msgs);
2436                $sorted_msgs = array();
2437                foreach($sel_msgs as $idx => $sel_msg) {
2438                        $sel_msg = explode(";", $sel_msg);
2439                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2440                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
2441                         }
2442                         else {
2443                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2444                         }
2445                }
2446                @ksort($sorted_msgs);
2447                $last_return = false;
2448                foreach($sorted_msgs as $folder => $msgs_number) {
2449                        $params['msgs_number'] = $msgs_number;
2450                        $params['folder'] = $folder;
2451                        if($params['new_folder'] && $folder != $params['new_folder']){
2452                                $last_return = $this -> move_messages($params);
2453                        }
2454                        elseif(!$params['new_folder'] || $params['delete'] ){
2455                                $last_return = $this -> delete_msgs($params);
2456                                $last_return['deleted'] = true;
2457                        }
2458                }
2459                return $last_return;
2460        }
2461
2462        function move_messages($params)
2463        {
2464                $folder = $params['folder'];
2465                $mbox_stream = $this->open_mbox($folder);
2466                $newmailbox = ($params['new_folder']);
2467                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
2468                $new_folder_name = $params['new_folder_name'];
2469                $msgs_number = $params['msgs_number'];
2470                $return = array('msgs_number' => $msgs_number,
2471                                                'folder' => $folder,
2472                                                'new_folder_name' => $new_folder_name,
2473                                                'border_ID' => $params['border_ID'],
2474                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
2475
2476                $error_log_file=$this->server_files_dir."/expressoMail.log";
2477                if($this->enable_log_messages == "True" &&
2478                strpos($msgs_number,',') != False)
2479                        error_log(date("D M j G:i:s T Y").": expressoMail, move_messages: "
2480                                .$this->username." ".$folder."=>".$new_folder_name.
2481                                " ".$msgs_number."\n", 3, $error_log_file);
2482
2483                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2484        if (substr($folder,0,4) == 'user'){
2485                $acl = $this->getacltouser($folder);
2486                /*
2487                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2488                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2489                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2490                 *   w - write (STORE flags other than SEEN and DELETED)
2491                 *   i - insert (perform APPEND, COPY into mailbox)
2492                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2493                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2494                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2495                 *   a - administer (perform SETACL)
2496                        */
2497                        if (strpos($acl, "d") === false){
2498                                $return['status'] = false;
2499                                return $return;
2500                        }
2501        }
2502        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
2503        if ($this->preferences['uid2cn']){
2504            if (substr($new_folder_name,0,4) == 'user'){
2505                $this->ldap = new ldap_functions();
2506                $tmp_folder_name = explode($this->email_server['imapDelimiter'], $new_folder_name);
2507                $return['new_folder_name'] = array_pop($tmp_folder_name);
2508                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2509                {
2510                    $return['new_folder_name'] = $cn;
2511                }
2512            }
2513        }
2514
2515                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
2516                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
2517                {
2518                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2519                        // Fix problem in unserialize function JS.
2520                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2521                }
2522
2523                $mbox_stream = $this->open_mbox($folder);
2524                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2525                        imap_expunge($mbox_stream);
2526                        if($mbox_stream)
2527                                imap_close($mbox_stream);
2528                        return $return;
2529                }else {
2530                        if(strstr(imap_last_error(),'Over quota')) {
2531                                $accountID      = $this->email_server['imapAdminUsername'];
2532                                $pass           = $this->email_server['imapAdminPW'];
2533                                $userID         = $this->username;
2534                                $server         = $this->email_server['imapServer'];
2535                                $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()))));
2536                                if(!$mbox)
2537                                        return imap_last_error();
2538                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
2539                                if(! imap_set_quota($mbox, "user".$this->email_server['imapDelimiter'].$userID, 2.1 * $quota['usage'])) {
2540                                        if($mbox_stream)
2541                                                imap_close($mbox_stream);
2542                                        if($mbox)
2543                                                imap_close($mbox);
2544                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->email_server['imapDelimiter'].$userID." line ".__LINE__."\n";
2545                                }
2546                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2547                                        imap_expunge($mbox_stream);
2548                                        if($mbox_stream)
2549                                                imap_close($mbox_stream);
2550                                        // return to original quota limit.
2551                                        if(!imap_set_quota($mbox, "user".$this->email_server['imapDelimiter'].$userID, $quota['limit'])) {
2552                                                if($mbox)
2553                                                        imap_close($mbox);
2554                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2555                                        }
2556                                        return $return;
2557                                }
2558                                else {
2559                                        if($mbox_stream)
2560                                                imap_close($mbox_stream);
2561                                        if(!imap_set_quota($mbox, "user".$this->email_server['imapDelimiter'].$userID, $quota['limit'])) {
2562                                                if($mbox)
2563                                                        imap_close($mbox);
2564                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2565                                        }
2566                                        return imap_last_error();
2567                                }
2568
2569                        }
2570                        else {
2571                                if($mbox_stream)
2572                                        imap_close($mbox_stream);
2573                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
2574                        }
2575                }
2576        }
2577
2578        function save_msg($params)
2579        {
2580
2581                include_once("class.phpmailer.php");
2582                $mail = new PHPMailer();
2583                // Set lang for PHPMailer using user prefs.
2584                list($prefix,$userlang) = explode('-',$this->lang);             
2585                $mail->SetLanguage($userlang,dirname( __FILE__ )."/../setup/");         
2586                include_once("class.db_functions.inc.php");
2587                $toaddress = $params['input_to'];
2588                $ccaddress = $params['input_cc'];
2589                $ccoaddress = $params['input_cco'];
2590                $subject = $params['input_subject'];
2591                $msg_uid = $params['msg_id'];
2592                $body = $params['body'];
2593                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
2594                $body = preg_replace("/\n/"," ",$body);
2595                $body = preg_replace("/\r/","",$body);
2596                $forwarding_attachments = $params['forwarding_attachments'];
2597                $attachments = $params['FILES'];
2598                $return_files = $params['FILES'];
2599
2600                $folder = $params['folder'];
2601                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2602                // Fix problem with cyrus delimiter changes.
2603                // Dots in names: enabled/disabled.
2604                $folder = @eregi_replace("INBOX/", "INBOX".$this->email_server['imapDelimiter'], $folder);
2605                $folder = @eregi_replace("INBOX.", "INBOX".$this->email_server['imapDelimiter'], $folder);
2606                // End Fix.
2607                if(strtoupper($folder) == 'INBOX/DRAFTS')
2608                    {
2609                        $mail->SaveMessageAsDraft = $folder;
2610                    }
2611                $mail->SaveMessageInFolder = $folder;
2612                $mail->SMTPDebug = false;
2613
2614                $mail->IsSMTP();
2615                $mail->Host = $this->email_server['smtpServer'];
2616                $mail->Port = $this->email_server['smtpPort'];
2617                $mail->From = $this->email;
2618                $mail->FromName = $this->fullname;
2619
2620                $mail->Sender = $mail->From;
2621                $mail->SenderName = $mail->FromName;
2622                $mail->FromName = $this->fullname;
2623                $mail->From =  $this->email;
2624                $session_id = $this->session_id;
2625                $max_resolution = $this->preferences['image_size'];
2626
2627                $this->add_recipients("to", $toaddress, &$mail);
2628                $this->add_recipients("cc", $ccaddress, &$mail);
2629                $this->add_recipients("cco", $ccoaddress, &$mail);
2630                $mail->Subject = $subject;
2631                $mail->IsHTML(true);
2632                $mail->Body = $body;
2633
2634                //      Build CID for embedded Images!!!
2635                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2636                $cid_imgs = '';
2637                $name_cid_files = array();
2638                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2639                $cid_array = array();
2640                foreach($cid_imgs[6] as $j => $val){
2641                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2642                        {
2643                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2644                        }
2645                        $cid = $cid_array[$cid_imgs[4][$j].$val];
2646                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2647
2648                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
2649                                {
2650                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2651                                        //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
2652                                        $fileName = "image_".($j).".jpg";
2653                                        $fileCode = "base64";
2654                                        $fileType = "image/jpg";
2655                                        $file_attached[0] = $cid_imgs[2][$j];
2656                                        $file_attached[1] = $cid_imgs[4][$j];
2657                                        $file_attached[2] = $fileName;
2658                                        $file_attached[3] = $cid_imgs[6][$j];
2659                                        $file_attached[4] = 'base64';
2660                                        $file_attached[5] = strlen($fileContent); //Size of file
2661                                        $return_forward[] = $file_attached;
2662                                }
2663                                else
2664                                {
2665                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2666                                        $file_description = unserialize(rawurldecode($attach_img));
2667                                        foreach($file_description as $i => $descriptor){
2668                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2669                                        }
2670                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2671                                        $fileName = $file_description[2];
2672                                        $fileCode = $file_description[4];
2673                                        $fileType = $this->get_file_type($file_description[2]);
2674                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2675                                        if (!empty($file_description))
2676                                        {
2677                                                $file_description[5] = strlen($fileContent); //Size of file
2678                                                $return_forward[] = $file_description;
2679                                        }
2680                                }
2681                                $tempDir = ini_get("session.save_path");
2682                                $file = "cidimage_".$session_id.$cid_imgs[6][$j].".dat";
2683                                $f = fopen($tempDir.'/'.$file,"w");
2684                                fputs($f,$fileContent);
2685                                fclose($f);
2686                                if ($fileContent)
2687                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2688                                //else
2689                                //      return "Error loading image attachment content";
2690
2691                }
2692
2693        //      Build Forwarding Attachments!!!
2694                if (count($forwarding_attachments) > 0)
2695                {
2696                        foreach($forwarding_attachments as $forwarding_attachment)
2697                        {
2698                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2699                                $tmp = array_values($file_description);
2700                                foreach($file_description as $i => $descriptor){
2701                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2702                                }
2703                                $file_description = $tmp;
2704
2705                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2706                                $fileName = $file_description[2];
2707
2708                                $file_description[5] = strlen($fileContent); //Size of file
2709                                $return_forward[] = $file_description;
2710
2711                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2712                        }
2713                }
2714
2715                if ((count($return_forward) > 0) && (count($return_files) > 0))
2716                        $return_files = array_merge_recursive($return_forward,$return_files);
2717                else
2718                        if (count($return_files) < 1)
2719                                $return_files = $return_forward;
2720
2721                //      Build Uploading Attachments!!!
2722                $sizeof_attachments = count($attachments);
2723                if ($sizeof_attachments)
2724                        foreach ($attachments as $numb => $attach){
2725                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2726                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2727                                        switch ($image_type)
2728                                        {
2729                                        // Do not corrupt animated gif
2730                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
2731                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2732                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2733                                        case 6:
2734                                                require_once("gd_functions.php");
2735                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2736                                        default:
2737                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2738                                                break;
2739                                        }
2740                                        header('Content-type: image/jpeg');
2741                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2742                                        if ($width < $max_resolution && $height < $max_resolution){
2743                                                $new_width = $width;
2744                                                $new_height = $height;
2745                                        }
2746                                        else if ($width > $max_resolution){
2747                                                $new_width = $max_resolution;
2748                                                $new_height = $height*($new_width/$width);
2749                                        }
2750                                        else {
2751                                                $new_height = $max_resolution;
2752                                                $new_width = $width*($new_height/$height);
2753                                        }
2754                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2755                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2756                                        $tmpDir = ini_get("session.save_path");
2757                                        $_file = "/cidimage_".$session_id.".dat";
2758                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2759                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2760                                }
2761                                else
2762                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2763                                // optional name
2764                                }
2765
2766
2767
2768
2769                if(!empty($mail->AltBody))
2770            $mail->ContentType = "multipart/alternative";
2771
2772                $mail->error_count = 0; // reset errors
2773                $mail->SetMessageType();
2774                $header = $mail->CreateHeader();
2775                $body = $mail->CreateBody();
2776
2777                $mbox_stream = $this->open_mbox($folder);
2778                $new_header = str_replace("\n", "\r\n", $header);
2779                $new_body = str_replace("\n", "\r\n", $body);
2780                $return['append'] = imap_append($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort']."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2781                $status = imap_status($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort']."}".$folder, SA_UIDNEXT);
2782                $return['msg_no'] = $status->uidnext - 1;
2783                $return['folder_id'] = $folder;
2784
2785                if($mbox_stream)
2786                        imap_close($mbox_stream);
2787                if (is_array($return_files))
2788                        foreach ($return_files as $index => $_attachment) {
2789                                if (array_key_exists("name",$_attachment)){
2790                                unset($return_files[$index]);
2791                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2792                        }
2793                        else
2794                        {
2795                                unset($return_files[$index]);
2796                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2797                        }
2798                }
2799
2800                $return['files'] = serialize($return_files);
2801                $return["subject"] = $subject;
2802
2803                if (!$return['append'])
2804                        $return['append'] = imap_last_error();
2805       
2806                return $return;
2807        }
2808
2809        function set_messages_flag($params)
2810        {
2811                $folder = $params['folder'];
2812                $msgs_to_set = $params['msgs_to_set'];
2813                $flag = $params['flag'];
2814                $return = array();
2815                $return["msgs_to_set"] = $msgs_to_set;
2816                $return["flag"] = $flag;
2817
2818                if(!$this->mbox && !is_resource($this->mbox))
2819                        $this->mbox = $this->open_mbox($folder);
2820
2821                if ($flag == "unseen")
2822                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2823                elseif ($flag == "seen")
2824                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2825                elseif ($flag == "answered"){
2826                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2827                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2828                }
2829                elseif ($flag == "forwarded")
2830                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2831                elseif ($flag == "flagged")
2832                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2833                elseif ($flag == "unflagged") {
2834                        $flag_importance = false;
2835                        $msgs_number = explode(",",$msgs_to_set);
2836                        $unflagged_msgs = "";
2837                        foreach($msgs_number as $msg_number) {
2838                                preg_match('/importance *: *(.*)\r/i',
2839                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2840                                        ,$importance);
2841                                if(strtolower($importance[1])=="high" && $this->preferences['use_important_flag']) {
2842                                        $flag_importance=true;
2843                                }
2844                                else {
2845                                        $unflagged_msgs.=$msg_number.",";
2846                                }
2847                        }
2848
2849                        if($unflagged_msgs!="") {
2850                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2851                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2852                        }
2853                        else {
2854                                $return["msgs_unflageds"] = false;
2855                        }
2856
2857                        if($flag_importance && $this->preferences['use_important_flag']) {
2858                                $return["status"] = false;
2859                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2860                        }
2861                        else {
2862                                $return["status"] = true;
2863                        }
2864                }
2865
2866                if($this->mbox && is_resource($this->mbox))
2867                        imap_close($this->mbox);
2868                return $return;
2869        }
2870
2871        function get_file_type($file_name)
2872        {
2873                $file_name = strtolower($file_name);
2874                $strFileType = strrev(substr(strrev($file_name),0,4));
2875                if ($strFileType == ".asf")
2876                        return "video/x-ms-asf";
2877                if ($strFileType == ".avi")
2878                        return "video/avi";
2879                if ($strFileType == ".doc")
2880                        return "application/msword";
2881                if ($strFileType == ".zip")
2882                        return "application/zip";
2883                if ($strFileType == ".xls")
2884                        return "application/vnd.ms-excel";
2885                if ($strFileType == ".gif")
2886                        return "image/gif";
2887                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2888                        return "image/jpeg";
2889                if ($strFileType == ".png")
2890                        return "image/png";
2891                if ($strFileType == ".wav")
2892                        return "audio/wav";
2893                if ($strFileType == ".mp3")
2894                        return "audio/mpeg3";
2895                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2896                        return "video/mpeg";
2897                if ($strFileType == ".rtf")
2898                        return "application/rtf";
2899                if ($strFileType == ".htm" || $strFileType == "html")
2900                        return "text/html";
2901                if ($strFileType == ".xml")
2902                        return "text/xml";
2903                if ($strFileType == ".xsl")
2904                        return "text/xsl";
2905                if ($strFileType == ".css")
2906                        return "text/css";
2907                if ($strFileType == ".php")
2908                        return "text/php";
2909                if ($strFileType == ".asp")
2910                        return "text/asp";
2911                if ($strFileType == ".pdf")
2912                        return "application/pdf";
2913                if ($strFileType == ".txt")
2914                        return "text/plain";
2915                if ($strFileType == ".wmv")
2916                        return "video/x-ms-wmv";
2917                if ($strFileType == ".sxc")
2918                        return "application/vnd.sun.xml.calc";
2919                if ($strFileType == ".stc")
2920                        return "application/vnd.sun.xml.calc.template";
2921                if ($strFileType == ".sxd")
2922                        return "application/vnd.sun.xml.draw";
2923                if ($strFileType == ".std")
2924                        return "application/vnd.sun.xml.draw.template";
2925                if ($strFileType == ".sxi")
2926                        return "application/vnd.sun.xml.impress";
2927                if ($strFileType == ".sti")
2928                        return "application/vnd.sun.xml.impress.template";
2929                if ($strFileType == ".sxm")
2930                        return "application/vnd.sun.xml.math";
2931                if ($strFileType == ".sxw")
2932                        return "application/vnd.sun.xml.writer";
2933                if ($strFileType == ".sxq")
2934                        return "application/vnd.sun.xml.writer.global";
2935                if ($strFileType == ".stw")
2936                        return "application/vnd.sun.xml.writer.template";
2937
2938
2939                return "application/octet-stream";
2940        }
2941
2942        function htmlspecialchars_encode($str)
2943        {
2944                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
2945        }
2946        function htmlspecialchars_decode($str)
2947        {
2948                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
2949        }
2950
2951        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2952        {
2953                if(!$this->mbox || !is_resource($this->mbox))
2954                        $this->mbox = $this->open_mbox($folder);
2955
2956                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2957        }
2958
2959        function get_info_next_msg($params)
2960        {
2961                $msg_number = $params['msg_number'];
2962                $folder = $params['msg_folder'];
2963                $sort_box_type = $params['sort_box_type'];
2964                $sort_box_reverse = $params['sort_box_reverse'];
2965                $reuse_border = $params['reuse_border'];
2966                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2967                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2968
2969                $success = false;
2970                if (is_array($sort_array_msg))
2971                {
2972                        foreach ($sort_array_msg as $i => $value){
2973                                if ($value == $msg_number)
2974                                {
2975                                        $success = true;
2976                                        break;
2977                                }
2978                        }
2979                }
2980
2981                if (! $success || $i >= sizeof($sort_array_msg)-1)
2982                {
2983                        $params['status'] = 'false';
2984                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2985                        return $params;
2986                }
2987
2988                $params = array();
2989                $params['msg_number'] = $sort_array_msg[($i+1)];
2990                $params['msg_folder'] = $folder;
2991
2992                $return = $this->get_info_msg($params);
2993                $return["reuse_border"] = $reuse_border;
2994                return $return;
2995        }
2996
2997        function get_info_previous_msg($params)
2998        {
2999                $msg_number = $params['msgs_number'];
3000                $folder = $params['folder'];
3001                $sort_box_type = $params['sort_box_type'];
3002                $sort_box_reverse = $params['sort_box_reverse'];
3003                $reuse_border = $params['reuse_border'];
3004                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
3005                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
3006
3007                $success = false;
3008                if (is_array($sort_array_msg))
3009                {
3010                        foreach ($sort_array_msg as $i => $value){
3011                                if ($value == $msg_number)
3012                                {
3013                                        $success = true;
3014                                        break;
3015                                }
3016                        }
3017                }
3018                if (! $success || $i == 0)
3019                {
3020                        $params['status'] = 'false';
3021                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3022                        return $params;
3023                }
3024
3025                $params = array();
3026                $params['msg_number'] = $sort_array_msg[($i-1)];
3027                $params['msg_folder'] = $folder;
3028
3029                $return = $this->get_info_msg($params);
3030                $return["reuse_border"] = $reuse_border;
3031                return $return;
3032        }
3033
3034        // This function updates the values: quota, paging and new messages menu.
3035        function get_menu_values($params){
3036                $return_array = array();
3037                $return_array = $this->get_quota($params);
3038
3039                $mbox_stream = $this->open_mbox($params['folder']);
3040                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
3041                if($mbox_stream)
3042                        imap_close($mbox_stream);
3043
3044                return $return_array;
3045        }
3046
3047        function get_quota($params){
3048                // folder_id = user/{uid} for shared folders
3049                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->email_server['imapDelimiter'].'/i', $params['folder_id'])){
3050                        $array_folder =  explode($this->email_server['imapDelimiter'],$params['folder_id']);
3051                        $folder_id = "user".$this->email_server['imapDelimiter'].$array_folder[1];
3052                }
3053                // folder_id = INBOX for inbox folders
3054                else
3055                        $folder_id = "INBOX";
3056
3057                if(!$this->mbox || !is_resource($this->mbox))
3058                        $this->mbox = $this->open_mbox();
3059
3060                $quota = imap_get_quotaroot($this->mbox, $folder_id);
3061                if($this->mbox && is_resource($this->mbox))
3062                        imap_close($this->mbox);
3063
3064                if (!$quota){
3065                        return array(
3066                                'quota_percent' => 0,
3067                                'quota_used' => 0,
3068                                'quota_limit' =>  0
3069                        );
3070                }
3071
3072                if(count($quota) && $quota['limit']) {
3073                        $quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
3074                        $quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
3075                        if($quota_used >= $quota_limit)
3076                        {
3077                                $quotaPercent = 100;
3078                        }
3079                        else
3080                        {
3081                        $quotaPercent = ($quota_used / $quota_limit)*100;
3082                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
3083                        }
3084                        return array(
3085                                'quota_percent' => floor($quotaPercent),
3086                                'quota_used' => floor($quota_used),
3087                                'quota_limit' =>  floor($quota_limit)
3088                        );
3089                }
3090                else
3091                        return array();
3092        }
3093
3094        function send_notification($params){
3095                require_once("class.phpmailer.php");
3096                $mail = new PHPMailer();
3097                // Set lang for PHPMailer using user prefs.
3098                list($prefix,$userlang) = explode('-',$this->lang);             
3099                $mail->SetLanguage($userlang,dirname( __FILE__ )."/../setup/");
3100
3101                $toaddress = $params['notificationto'];
3102
3103                $subject = 'Confirmação de leitura: ' . $params['subject'];
3104                $body = 'Sua mensagem: ' . $params['subject'] . '<br>';
3105                $body .= 'foi lida por: ' . $this->fullname . ' &lt;' . $this->email . '&gt; em ' . date("d/m/Y H:i");
3106                $mail->SMTPDebug = false;
3107                $mail->IsSMTP();
3108                $mail->Host = $this->email_server['smtpServer'];
3109                $mail->Port = $this->email_server['smtpPort'];
3110                $mail->From = $this->email;
3111                $mail->FromName = $this->fullname;
3112                $mail->AddAddress($toaddress);
3113                $mail->Subject = $this->htmlspecialchars_decode($subject);
3114
3115                $mail->IsHTML(true);
3116                $mail->Body = $body;
3117
3118                if(!$mail->Send()){
3119                        return $mail->ErrorInfo;
3120                }
3121                else
3122                        return true;
3123        }
3124
3125        function empty_folder($params)
3126        {
3127                $folder = 'INBOX' . $this->email_server['imapDelimiter ']. $this->email_server[$params['clean_folder']];
3128                $mbox_stream = $this->open_mbox($folder);
3129                $return = imap_delete($mbox_stream,'1:*');
3130                if($mbox_stream)
3131                        imap_close($mbox_stream, CL_EXPUNGE);
3132                return $return;
3133        }
3134
3135        function search($params)
3136        {
3137                include("class.imap_attachment.inc.php");
3138                $imap_attachment = new imap_attachment();
3139                $criteria = $params['criteria'];
3140                $return = array();
3141                $folders = $this->get_folders_list();
3142
3143                $j = 0;
3144                foreach($folders as $folder)
3145                {
3146                        $mbox_stream = $this->open_mbox($folder);
3147                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
3148
3149                        if ($messages == '')
3150                                continue;
3151
3152                        $i = 0;
3153                        $return[$j] = array();
3154                        $return[$j]['folder_name'] = $folder['name'];
3155
3156                        foreach($messages as $msg_number)
3157                        {
3158                                $header = $this->get_header($msg_number);
3159                                if (!is_object($header))
3160                                        return false;
3161
3162                                $return[$j][$i]['msg_folder']   = $folder['name'];
3163                                $return[$j][$i]['msg_number']   = $msg_number;
3164                                $return[$j][$i]['Recent']               = $header->Recent;
3165                                $return[$j][$i]['Unseen']               = $header->Unseen;
3166                                $return[$j][$i]['Answered']     = $header->Answered;
3167                                $return[$j][$i]['Deleted']              = $header->Deleted;
3168                                $return[$j][$i]['Draft']                = $header->Draft;
3169                                $return[$j][$i]['Flagged']              = $header->Flagged;
3170
3171                                $date_msg = gmdate("d/m/Y",$header->udate);
3172                                if (gmdate("d/m/Y") == $date_msg)
3173                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
3174                                else
3175                                        $return[$j][$i]['udate'] = $date_msg;
3176
3177                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3178                                $return[$j][$i]['fromaddress'] = '';
3179                                foreach ($fromaddress as $tmp)
3180                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
3181
3182                                $from = $header->from;
3183                                $return[$j][$i]['from'] = array();
3184                                $tmp = imap_mime_header_decode($from[0]->personal);
3185                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3186                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
3187                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
3188
3189                                $to = $header->to;
3190                                $return[$j][$i]['to'] = array();
3191                                $tmp = imap_mime_header_decode($to[0]->personal);
3192                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3193                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
3194                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
3195
3196                                $subject = imap_mime_header_decode($header->fetchsubject);
3197                                $return[$j][$i]['subject'] = '';
3198                                foreach ($subject as $tmp)
3199                                        $return[$j][$i]['subject'] .= $tmp->text;
3200
3201                                $return[$j][$i]['Size'] = $header->Size;
3202                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
3203
3204                                $return[$j][$i]['attachment'] = array();
3205                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
3206
3207                                $i++;
3208                        }
3209                        $j++;
3210                        if($mbox_stream)
3211                                imap_close($mbox_stream);
3212                }
3213
3214                return $return;
3215        }
3216       
3217       
3218        function mobile_search($params)
3219        {
3220                include("class.imap_attachment.inc.php");
3221                $imap_attachment = new imap_attachment();
3222                $criterias = array ("TO","SUBJECT","FROM","CC");
3223                $return = array();
3224                $folders = $this->get_folders_list();
3225                $num_msgs = 0;
3226                                         
3227                foreach($folders as $id =>$folder)
3228                {
3229                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3230                                foreach($criterias as $criteria_fixed)
3231                    {
3232                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3233                                        $mbox_stream = $this->open_mbox($folder['folder_name']);
3234       
3235                                        $messages = imap_search($mbox_stream, $_filter, SE_UID);
3236                                       
3237                                        if ($messages == ''){
3238                                                if($mbox_stream)
3239                                                        imap_close($mbox_stream);
3240                                                continue;       
3241                                        }
3242                                                                       
3243                                        foreach($messages as $msg_number)
3244                                        {                                       
3245                                                $temp = $this->get_info_head_msg($msg_number);
3246                                                if(!$temp)
3247                                                        return false;
3248               
3249                                                $return[$num_msgs] = $temp;
3250                                                $num_msgs++;
3251                                        }
3252                                        $return['num_msgs'] = $num_msgs;
3253                                       
3254                                        if($mbox_stream)
3255                                                imap_close($mbox_stream);
3256                                }
3257                        }
3258                               
3259                }
3260                return $return;
3261        }
3262
3263        function delete_and_show_previous_message($params)
3264        {
3265                $return = $this->get_info_previous_msg($params);
3266
3267                $params_tmp1 = array();
3268                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3269                $params_tmp1['folder'] = $params['msg_folder'];
3270                $return_tmp1 = $this->delete_msg($params_tmp1);
3271
3272                $return['msg_number_deleted'] = $return_tmp1;
3273
3274                return $return;
3275        }
3276
3277
3278        function automatic_trash_cleanness($params)
3279        {
3280                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3281                $criteria =  'BEFORE "'.$before_date.'"';
3282                $trash_folder = $this->email_server['imapDefaultTrashFolder'];
3283
3284                $mbox_stream = $this->open_mbox('INBOX'.$this->email_server['imapDelimiter'].$trash_folder);
3285
3286                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3287
3288                if (is_array($messages)){
3289                        foreach ($messages as $msg_number){
3290                                imap_delete($mbox_stream, $msg_number, FT_UID);
3291                        }
3292                }
3293                if($mbox_stream)
3294                        imap_close($mbox_stream, CL_EXPUNGE);
3295                return $messages;
3296        }
3297//      Fix the search problem with special characters!!!!
3298        function remove_accents($string) {
3299                return strtr($string,
3300                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
3301                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3302        }
3303
3304        function make_search_date($date){
3305
3306            $months = array(
3307                1   => 'jan',
3308                2   => 'feb',
3309                3   => 'mar',
3310                4   => 'apr',
3311                5   => 'may',
3312                6   => 'jun',
3313                7   => 'jul',
3314                8   => 'aug',
3315                9   => 'sep',
3316                10  => 'oct',
3317                11  => 'nov',
3318                12  => 'dec'
3319            );
3320
3321            //TODO: Adaptar a data de acordo com o locale do sistema.
3322            list($day,$month,$year) = explode("/", $date);
3323            $search_date = $day."-".$months[intval($month)]."-".$year;
3324            return $search_date;
3325
3326        }
3327
3328        function search_msg($params = ''){
3329            $retorno = "";
3330            $mbox_stream = "";
3331            if(strpos($params['condition'],"#")===false) { //local messages
3332                    $search=false;
3333            }
3334            else {
3335                    $search = explode(",",$params['condition']);
3336            }
3337
3338            if($search){
3339                $search_criteria = '';
3340                $search_result_number = $this->preferences['search_result_number'];
3341                foreach($search as $tmp)
3342                {
3343                    $tmp1 = explode("##",$tmp);
3344                    $sum = 0;
3345                    $name_box = $tmp1[0];
3346                    unset($filter);
3347                    foreach($tmp1 as $index => $criteria)
3348                    {
3349                        if ($index != 0 && strlen($criteria) != 0)
3350                        {
3351                            $filter_array = explode("<=>",rawurldecode($criteria));
3352                            $filter .= " ".$filter_array[0];
3353                            if (strlen($filter_array[1]) != 0){
3354                                if (trim($filter_array[0]) != 'BEFORE' &&
3355                                    trim($filter_array[0]) != 'SINCE' &&
3356                                    trim($filter_array[0]) != 'ON')
3357                                {
3358                                    $filter .= '"'.$filter_array[1].'"';
3359                                }
3360                                else
3361                                    {
3362                                        $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3363                                    }
3364                            }
3365                        }
3366                    }
3367                    $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3368                    $filter = $this->remove_accents($filter);
3369                    //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
3370                    if ($this->preferences['uid2cn'] && substr($name_box,0,4) == 'user')
3371                    {
3372                        $folder_name = explode($this->email_server['imapDelimiter'],$name_box);
3373                        $this->ldap = new ldap_functions();
3374                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3375                        {
3376                            $folder_name[1] = $cn;
3377                        }
3378                        $folder_name = implode($this->email_server['imapDelimiter'],$folder_name);
3379                    }
3380                    else
3381                    {
3382                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3383                    }
3384
3385                    if(!is_resource($mbox_stream))
3386                    {
3387                        $mbox_stream = $this->open_mbox($name_box);
3388                    }
3389                    else
3390                        {
3391                            imap_reopen($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}".$name_box);
3392                        }
3393
3394                    if (preg_match("/^.?\bALL\b/", $filter))
3395                    { // Quick Search, note: this ALL isn't the same ALL from imap_search
3396
3397                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3398                        foreach($all_criterias as $criteria_fixed)
3399                        {
3400                            $_filter = $criteria_fixed . substr($filter,4);
3401
3402                            $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
3403
3404                            if($search_criteria) //&& count($search_criteria) < 50)
3405                            {
3406                                foreach($search_criteria as $new_search)
3407                                {
3408                                    if ($search_result_number != '65536' && $sum == $search_result_number)
3409                                    {
3410                                        return $retorno ? $sum . "=sumResults=" . $retorno : "none";
3411                                    }
3412
3413                                    $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");
3414                                    if(!@strstr($retorno,$m_token))
3415                                    {
3416                                        $retorno .= $m_token;
3417                                        $sum ++;
3418                                    }
3419                                }
3420                            }
3421                        }
3422                    }
3423                    else {
3424                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3425                        if( is_array( $search_criteria) )
3426                        {
3427                            foreach($search_criteria as $new_search)
3428                            {
3429                                if ($search_result_number != '65536' && $sum == $search_result_number)
3430                                {
3431                                    return $retorno ? $sum . "=sumResults=" . $retorno : "none";
3432                                }
3433                                $retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
3434                                $sum++;
3435                            }
3436                        }
3437                    }
3438                }
3439            }
3440            if($mbox_stream)
3441            {
3442                imap_close($mbox_stream);
3443            }
3444
3445            if ($retorno)
3446            {
3447                return $retorno;
3448            }
3449            else
3450            {
3451                return 'none';
3452            }
3453        }
3454
3455        function get_msg($uid_msg,$name_box, $mbox_stream )
3456        {
3457                $header = $this->get_header($uid_msg);
3458                include_once("class.imap_attachment.inc.php");
3459                $imap_attachment = new imap_attachment();
3460                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3461                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3462                $flag = $header->Unseen
3463                        .$header->Recent
3464                        .$header->Flagged
3465                        .$header->Draft
3466                        .$header->Answered
3467                        .$header->Deleted
3468                        .$attachments;
3469
3470
3471                $subject = $this->decode_string($header->fetchsubject);
3472                $from = $header->from[0]->mailbox;
3473                if($header->from[0]->personal != "")
3474                        $from = $header->from[0]->personal;
3475                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size) ."--". $flag;
3476                return $ret_msg;
3477        }
3478
3479        function size_msg($size){
3480                $var = floor($size/1024);
3481                if($var >= 1){
3482                        return $var." kb";
3483                }else{
3484                        return $size ." b";
3485                }
3486        }
3487
3488        function ob_array($the_object)
3489        {
3490           $the_array=array();
3491           if(!is_scalar($the_object))
3492           {
3493               foreach($the_object as $id => $object)
3494               {
3495                   if(is_scalar($object))
3496                   {
3497                       $the_array[$id]=$object;
3498                   }
3499                   else
3500                   {
3501                       $the_array[$id]=$this->ob_array($object);
3502                   }
3503               }
3504               return $the_array;
3505           }
3506           else
3507           {
3508               return $the_object;
3509           }
3510        }
3511
3512        function getacl()
3513        {
3514                $this->ldap = new ldap_functions();
3515
3516                $return = array();
3517                $mbox_stream = $this->open_mbox();
3518                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3519
3520                $i = 0;
3521                foreach ($mbox_acl as $user => $acl)
3522                {
3523                        if ($user != $this->username)
3524                        {
3525                                $return[$i]['uid'] = $user;
3526                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3527                        }
3528                        $i++;
3529                }
3530                return $return;
3531        }
3532
3533        function setacl($params)
3534        {
3535                $old_users = $this->getacl();
3536                if (!count($old_users))
3537                        $old_users = array();
3538
3539                $tmp_array = array();
3540                foreach ($old_users as $index => $user_info)
3541                {
3542                        $tmp_array[$index] = $user_info['uid'];
3543                }
3544                $old_users = $tmp_array;
3545
3546                $users = unserialize($params['users']);
3547                if (!count($users))
3548                        $users = array();
3549
3550                //$add_share = array_diff($users, $old_users);
3551                $remove_share = array_diff($old_users, $users);
3552
3553                $mbox_stream = $this->open_mbox();
3554
3555                $serverString = "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}";
3556                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->email_server['imapDelimiter'].$this->username."*");
3557
3558                /*if (count($add_share))
3559                {
3560                        foreach ($add_share as $index=>$uid)
3561                        {
3562                        if (is_array($mailboxes_list))
3563                        {
3564                        foreach ($mailboxes_list as $key => $val)
3565                        {
3566                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3567                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3568                        }
3569                        }
3570                        }
3571                }*/
3572
3573                if (count($remove_share))
3574                {
3575                        foreach ($remove_share as $index=>$uid)
3576                        {
3577                        if (is_array($mailboxes_list))
3578                        {
3579                        foreach ($mailboxes_list as $key => $val)
3580                        {
3581                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3582                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3583                        }
3584                        }
3585                        }
3586                }
3587
3588                return true;
3589        }
3590
3591        function getaclfromuser($params)
3592        {
3593                $useracl = $params['user'];
3594
3595                $return = array();
3596                $return[$useracl] = 'false';
3597                $mbox_stream = $this->open_mbox();
3598                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3599
3600                foreach ($mbox_acl as $user => $acl)
3601                {
3602                        if (($user != $this->username) && ($user == $useracl))
3603                        {
3604                                $return[$user] = $acl;
3605                        }
3606                }
3607                return $return;
3608        }
3609
3610        function getacltouser($user)
3611        {
3612                $return = array();
3613                $mbox_stream = $this->open_mbox();
3614                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->email_server['imapDelimiter'].$user);
3615                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3616                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3617                if(substr($user,0,4) != 'user')
3618                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->email_server['imapDelimiter'].$user);
3619                else
3620                  $mbox_acl = imap_getacl($mbox_stream, $user);
3621                return $mbox_acl[$this->username];
3622        }
3623
3624
3625        function setaclfromuser($params)
3626        {
3627                $user = $params['user'];
3628                $acl = $params['acl'];
3629
3630                $mbox_stream = $this->open_mbox();
3631
3632                $serverString = "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}";
3633                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->email_server['imapDelimiter'].$this->username."*");
3634
3635                if (is_array($mailboxes_list))
3636                {
3637                        foreach ($mailboxes_list as $key => $val)
3638                        {
3639                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3640                                $folder = str_replace("&-", "&", $folder);
3641                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3642                                {
3643                                        $return = imap_last_error();
3644                                }
3645                        }
3646                }
3647                if (isset($return))
3648                        return $return;
3649                else
3650                        return true;
3651        }
3652
3653        function download_attachment($msg,$msgno)
3654        {
3655                $array_parts_attachments = array();
3656                $array_parts_attachments['names'] = '';
3657                include_once("class.imap_attachment.inc.php");
3658                $imap_attachment = new imap_attachment();
3659
3660                if (count($msg->fname[$msgno]) > 0)
3661                {
3662                        $i = 0;
3663                        foreach ($msg->fname[$msgno] as $index=>$fname)
3664                        {
3665                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3666                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
3667                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3668                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3669                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3670                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3671                                $i++;
3672                        }
3673                }
3674                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3675                return $array_parts_attachments;
3676        }
3677
3678        function spam($params)
3679        {
3680                $is_spam = $params['spam'];
3681                $folder = $params['folder'];
3682                $mbox_stream = $this->open_mbox($folder);
3683                $msgs_number = explode(',',$params['msgs_number']);
3684
3685                foreach($msgs_number as $msg_number) {
3686                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3687                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3688                        $body = imap_body($mbox_stream, $imap_msg_number);
3689                        $msg = $header . $body;
3690                        $email = $this->email;
3691                        $username = $this->username;
3692                        strtok($email, '@');
3693                        $domain = strtok('@');
3694
3695                        //Encontrar a assinatura do dspam no cabecalho
3696                        $v = explode("\r\n", $header);
3697                        foreach ($v as $linha){
3698                                if (eregi("^Message-ID", $linha)) {
3699                                        $args = explode(" ", $linha);
3700                                        $msg_id = "'$args[1]'";
3701                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
3702                                        $args = explode(" ",$linha);
3703                                        $signature = $args[1];
3704                                }
3705                        }
3706
3707                        // Seleciona qual comando a ser executado
3708                        switch($is_spam){
3709                                case 'true':  $cmd = $this->command_for_spam; break;
3710                                case 'false': $cmd = $this->command_for_ham; break;
3711                        }
3712
3713                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3714                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
3715                        system($cmd);
3716                }
3717                imap_close($mbox_stream);
3718                return false;
3719        }
3720        function get_header($msg_number){
3721                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3722                if (!is_object($header))
3723                        return false;
3724                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
3725                $header->udate_original = $header->udate;
3726                $pdate = date_parse($header->MailDate);
3727                $header->udate +=  $pdate['zone']*(-60);
3728
3729                if($header->Flagged != "F" && $this->preferences['use_important_flag']) {
3730                        $flag = preg_match('/importance *: *(.*)\r/i',
3731                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3732                                                ,$importance);
3733                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3734                }
3735
3736                return $header;
3737        }
3738
3739//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
3740///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.
3741
3742    function insert_email($source,$folder,$timestamp){
3743        $username = $this->username;
3744        $password = $this->password;
3745        $imap_server = $this->email_server['imapServer'];
3746        $imap_port      = $this->email_server['imapPort'];
3747        $imap_options = '/notls/novalidate-cert';
3748        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3749        if(imap_last_error())
3750        {
3751            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3752       }
3753        if($timestamp){
3754            $tempDir = ini_get("session.save_path");
3755            $file = $tempDir."imap_".$this->session_id;
3756                $f = fopen($file,"w");
3757                fputs($f,base64_encode($source));
3758            fclose($f);
3759            $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);
3760            $return['command']=exec(escapeshellcmd($command));
3761        }else{
3762            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3763        }
3764        $status = imap_status($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort']."}".$folder, SA_UIDNEXT);
3765        $return['msg_no'] = $status->uidnext - 1;
3766                $return['error'] = imap_last_error();
3767        if($mbox_stream)
3768                        imap_close($mbox_stream);
3769        return $return;
3770
3771    }
3772
3773    function show_decript($params){
3774        $source = $params['source'];
3775        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3776        $source = str_replace(" ", "+", $source,$i);
3777
3778        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3779            if(!$source = base64_decode($source,true))
3780                return "error ".$source."Espaços ".$i;
3781
3782        }
3783        else {
3784            if(!$source = base64_decode($source))
3785                return "error ".$source."Espaços ".$i;
3786        }
3787
3788        $insert = $this->insert_email($source,'INBOX'.$this->email_server['imapDelimiter'].'decifradas');
3789
3790                $get['msg_number'] = $insert['msg_no'];
3791                $get['msg_folder'] = 'INBOX'.$this->email_server['imapDelimiter'].'decifradas';
3792                $return = $this->get_info_msg($get);
3793                $get['msg_number'] = $params['ID'];
3794                $get['msg_folder'] = $params['folder'];
3795                $tmp = $this->get_info_msg($get);
3796                if(!$tmp['status_get_msg_info'])
3797                {
3798                        $return['msg_day']=$tmp['msg_day'];
3799                        $return['msg_hour']=$tmp['msg_hour'];
3800                        $return['fulldate']=$tmp['fulldate'];
3801                        $return['smalldate']=$tmp['smalldate'];
3802                }
3803                else
3804                {
3805                        $return['msg_day']='';
3806                        $return['msg_hour']='';
3807                        $return['fulldate']='';
3808                        $return['smalldate']='';
3809                }
3810        $return['msg_no'] =$insert['msg_no'];
3811        $return['error'] = $insert['error'];
3812        $return['folder'] = $params['folder'];
3813        //$return['acls'] = $insert['acls'];
3814        $return['original_ID'] =  $params['ID'];
3815
3816        return $return;
3817
3818    }
3819
3820//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
3821//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
3822
3823    function treat_base64_from_post($source){
3824            $offset = 0;
3825            do
3826            {
3827                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
3828                    {
3829                            $inicio = strpos($source, "\n\r", $inicio);
3830                            $fim = strpos($source, '--', $inicio);
3831                            if(!$fim)
3832                                    $fim = strpos($source,"\n\r", $inicio);
3833                            $length = $fim-$inicio;
3834                            $parte = substr( $source,$inicio,$length-1);
3835                            $parte = str_replace(" ", "+", $parte);
3836                            $source = substr_replace($source, $parte, $inicio, $length-1);
3837                    }
3838                    if($offset > $inicio)
3839                    $offset=FALSE;
3840                    else
3841                    $offset = $inicio;
3842            }
3843            while($offset);
3844            return $source;
3845    }
3846
3847//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.
3848
3849    function unarchive_mail($params)
3850    {
3851        $dest_folder = $params['folder'];
3852        $sources = explode("#@#@#@",$params['source']);
3853        $timestamps = explode("#@#@#@",$params['timestamp']);
3854        foreach($sources as $index=>$src) {
3855                        if($src!=""){
3856                                $source = $this->treat_base64_from_post($src);
3857                                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index]);
3858                        }
3859                }
3860        return $insert;
3861    }
3862
3863    function download_all_local_attachments($params)
3864    {
3865        $source = $params['source'];
3866        $source = $this->treat_base64_from_post($source);
3867        $insert = $this->insert_email($source,'INBOX'.$this->email_server['imapDelimiter'].'decifradas');
3868        $exporteml = new ExportEml();
3869        $params['num_msg']=$insert['msg_no'];
3870        $params['folder']='INBOX'.$this->email_server['imapDelimiter'].'decifradas';
3871        return $exporteml->download_all_attachments($params);
3872    }
3873
3874    function get_quota_folders(){
3875       
3876        // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
3877                include_once("class.imapfp.inc.php");           
3878                $imapfp = new imapfp();
3879               
3880            if(!$imapfp->open($this->email_server['imapServer'],$this->email_server['imapPort']))
3881                return $imapfp->get_error();           
3882                if (!$imapfp->login( $this->username,$this->password ))
3883                return $imapfp->get_error();
3884                   
3885            $response_array = $imapfp->get_mailboxes_size();
3886            if ($imapfp->error)
3887                return $imapfp->get_error();
3888           
3889            $data = array();
3890            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
3891        $data["quota_root"] = $quota_root;
3892           
3893            foreach ($response_array as $idx=>$line) {
3894                        $line2 = str_replace('"', "", $line);
3895                        $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
3896                        list($folder,$size) = explode(";",$line2);
3897                        $size = str_replace(")","",$size);
3898                        $quotaPercent = (($size / 1048576) / $data["quota_root"]["quota_limit"])*100;
3899                        if ($size < 1048576 && $size > 1024)
3900                                $quota_used = round($size / 1024, 0).' Kb';
3901                        else if($size > 1024)
3902                                $quota_used = round($size / (1024*1024), 1).' Mb';
3903                        else
3904                                $quota_used = $size." b";
3905                        $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
3906                        if(!preg_match('/user\\'.$this->email_server['imapDelimiter'].$this->username.'\\'.$this->email_server['imapDelimiter'].'/i',$folder)){
3907                                $folder = $this->functions->getLang("Inbox");
3908                        }
3909                        else
3910                                $folder = preg_replace('/user\\'.$this->email_server['imapDelimiter'].$this->username.'\\'.$this->email_server['imapDelimiter'].'/i','', $folder);
3911                       
3912                        $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
3913            }
3914            $imapfp->close();
3915        return $data;
3916        }
3917}
3918?>
Note: See TracBrowser for help on using the repository browser.