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

Revision 2853, 138.0 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #1061 - Corrigidos para exibir dados do certificado qdo. msg assinada

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