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

Revision 2806, 137.7 KB checked in by amuller, 14 years ago (diff)

Ticket #1079 - corrige problema do sugestões text/plain

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