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

Revision 2715, 139.5 KB checked in by amuller, 14 years ago (diff)

Ticket #1059 - Cria uma classe draw_message no lugar da função gigante

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