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

Revision 2777, 137.5 KB checked in by amuller, 14 years ago (diff)

Ticket #405 - Arruma problema da sessão que não está definida mais

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