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

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

Ticket #737 - Arrumando flags de desanexar e outros campos do header

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