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

Revision 3058, 138.6 KB checked in by amuller, 14 years ago (diff)

Ticket #974 - Colocando no alt e title do td a data completa

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