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

Revision 2958, 139.2 KB checked in by niltonneto, 14 years ago (diff)

Ticket #1111 - Correção de problema ao responder, encaminhar e imprimir email text/plain.

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