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

Revision 3040, 139.3 KB checked in by niltonneto, 14 years ago (diff)

Ticket #1111 - Adicionado estilo white-space para corrigir problema no Firefox 2.0.

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