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

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

Ticket #911 - Diminuindo a parte de código que inicia a sessão

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2
3/***************************************************************************
4        * Expresso Livre                                                           *
5        * http://www.expressolivre.org                                             *
6        * --------------------------------------------                             *
7        *  This program is free software; you can redistribute it and/or modify it *
8        *  under the terms of the GNU General Public License as published by the   *
9        *  Free Software Foundation; either version 2 of the License, or (at your  *
10        *  option) any later version.                                              *
11        \**************************************************************************/
12
13include_once("class.functions.inc.php");
14include_once("class.ldap_functions.inc.php");
15include_once("class.exporteml.inc.php");
16
17class imap_functions
18{
19        var $public_functions = array
20        (
21                'get_range_msgs'                                => True,
22                'get_info_msg'                                  => True,
23                'get_info_msgs'                                 => True,
24                'get_folders_list'                              => True,
25                'import_msgs'                                   => True,
26                'msgs_to_archive'                               => True
27        );
28
29        var $ldap;
30        var $mbox;
31        var $email_server;
32        var $cert;
33        var $preferences;
34        var $has_cid;
35        var $imap_options = '';
36        var $functions;
37        var $foldersLimit;
38        var $imap_sentfolder;
39        function load_session_vars(){
40                $this->foldersLimit = $_SESSION['phpgw_info']['expressomail']['max_folders_to_show']; //Limit of folders (mailboxes) user can see
41                $this->email_server = $_SESSION['phpgw_info']['expressomail']['email_server'];
42                $this->cert = $_SESSION['phpgw_info']['expressomail']['server']['certificado'];
43                $this->server_files_dir = $_SESSION['phpgw_info']['expressomail']['server']['files_dir'];
44
45                $this->username  = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
46                $this->password  = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
47                $this->account_id = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];
48                $this->email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
49                $this->fullname = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
50                $this->lang = $_SESSION['phpgw_info']['expressomail']['user']['preferences']['common']['lang'];
51                $this->session_ip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
52                $this->shared_mailboxes = $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'];
53
54                $this->command_for_ham = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham'];
55                $this->command_for_spam = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam'];
56                $this->enable_log_messages = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'];
57
58                $this->preferences = $_SESSION['phpgw_info']['user']['preferences']['expressoMail'];
59                $this->session_id = $_SESSION[ 'phpgw_session' ][ 'session_id' ];
60
61        }
62        function imap_functions (){
63                session_write_close();
64                $this->load_session_vars();
65                $this->functions          = new functions();
66                $this->imap_sentfolder = $this->email_server['imapDefaultSentFolder']  ? $this->email_server['imapDefaultSentFolder'] : str_replace("*","", $this->functions->getLang("Sent"));
67                $this->has_cid = false;
68
69                if ($this->email_server['imapTLSEncryption'] == 'yes')
70                {
71                        $this->imap_options = '/tls/novalidate-cert';
72                }
73                else
74                {
75                        $this->imap_options = '/notls/novalidate-cert';
76                }
77        }
78        // BEGIN of functions.
79        function open_mbox($folder = False)
80        {
81                if (is_resource($this->mbox))
82                        return $this->mbox;
83                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
84                $this->mbox = @imap_open("{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
85                return $this->mbox;
86         }
87
88        function parse_error($error){
89                // This error is returned from Imap.
90                if(strstr($error,'Connection refused')) {
91                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
92                }
93                // This error is returned from Postfix.
94                elseif(strstr($error,'message file too big')) {
95                        return str_replace("%1",$this->preferences['max_attachment_size'],$this->functions->getLang('The size of this message has exceeded  the limit (%1B).'));
96                }
97                elseif(strstr($error,'virus')) {
98                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
99                }
100                // This condition verifies if SESSION is expired.
101                elseif(!count( $this->email_server ))
102                        return "nosession";
103
104                return $error;
105        }
106
107        function get_range_msgs2($params)
108        {
109                $folder = $params['folder'];
110                $msg_range_begin = $params['msg_range_begin'];
111                $msg_range_end = $params['msg_range_end'];
112                $sort_box_type = $params['sort_box_type'];
113                $sort_box_reverse = $params['sort_box_reverse'];
114                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
115                $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
116
117                $return = array();
118                $i = 0;
119                $status = imap_status($this->mbox,
120                        "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}".$folder,
121                        SA_MESSAGES + SA_UNSEEN);
122                if(is_array($sort_array_msg)){
123                        foreach($sort_array_msg as $msg_number => $value)
124                        {
125                                $temp = $this->get_info_head_msg($msg_number);
126                                $temp['msg_sample'] = $this->get_msg_sample($msg_number);
127                                if(!$temp)
128                                {
129                                        return false;
130                                }
131
132                                $return[$i] = $temp;
133                                $i++;
134                        }
135                }
136                $return['num_msgs'] = $status->messages;
137                $return['num_unseen'] = $status->unseen;
138
139                return $return;
140        }
141
142        function get_info_head_msg($msg_number) {
143                $head_array = array();
144                include_once("class.imap_attachment.inc.php");
145                $imap_attachment = new imap_attachment();
146
147
148
149                /*Como eu preciso do atributo Importance para saber se o email é
150                 * importante ou não, uso abaixo a função imap_fetchheader e busco
151                 * o atributo importance nela. Isso faz com que eu acesse o cabeçalho
152                 * duas vezes e de duas formas diferentes, mas em contrapartida, eu
153                 * não preciso reimplementar o método utilizando o fetchheader.
154                 * Como as mensagens são renderizadas em um número pequeno por vez,
155                 * não parece ter perda considerável de performance.
156                 */
157
158                $tempHeader = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
159                $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
160
161                // Reimplemenatado código para identificação dos e-mails assinados e cifrados
162                // no método getMessageType(). Mário César Kolling <mario.kolling@serpro.gov.br>
163                $head_array['ContentType'] = $this->getMessageType($msg_number, $tempHeader);
164                $head_array['Importance'] = $flag==0?"Normal":$importance[1];
165
166
167                $header = $this->get_header($msg_number);
168                if (!is_object($header))
169                        return false;
170                $head_array['Recent'] = $header->Recent;
171                $head_array['Unseen'] = $header->Unseen;
172                if($header->Answered =='A' && $header->Draft == 'X'){
173                        $head_array['Forwarded'] = 'F';
174                }
175                else {
176                        $head_array['Answered'] = $header->Answered;
177                        $head_array['Draft']    = $header->Draft;
178                }
179                $head_array['Deleted'] = $header->Deleted;
180                $head_array['Flagged'] = $header->Flagged;
181
182                $head_array['msg_number'] = $msg_number;
183                //$head_array['msg_folder'] = $folder;
184
185                $date_msg = gmdate("d/m/Y",$header->udate);
186                if ( date("d/m/Y") == $date_msg)
187                        $head_array['udate'] = gmdate("H:i",$header->udate);
188                else
189                {
190                        $head_array['udate'] = $date_msg;
191                        if ( date("d/m/Y", time() - 86400) == gmdate("d/m/Y",$header->udate) )
192                                $head_array['udate'] = $this -> functions -> getLang( 'Yesterday' );
193                        if ( date("d/m/Y", time() - 172800) == gmdate("d/m/Y",$header->udate) )
194                                $head_array['udate'] = $this -> functions -> getLang( gmdate("l",$header->udate) );
195                        if ( date("d/m/Y", time() - 259200) == gmdate("d/m/Y",$header->udate) )
196                                $head_array['udate'] = $this -> functions -> getLang( gmdate("l",$header->udate) );
197                }
198
199                $head_array['aux_date'] = $date_msg; //Auxiliar apenas para mensagens locais.
200
201                $from = $header->from;
202                $head_array['from'] = array();
203                $head_array['from']['name'] = ( isset( $from[0]->personal ) ) ? $this->decode_string($from[0]->personal) : NULL;
204                $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
205                if(!$head_array['from']['name'])
206                        $head_array['from']['name'] = $head_array['from']['email'];
207                $to = $header->to;
208                $head_array['to'] = array();
209                $tmp = ( isset( $to[0]->personal ) ) ? imap_mime_header_decode($to[0]->personal) : NULL;
210                $head_array['to']['name'] = ( isset( $tmp[0]->text ) ) ? $this->decode_string($this->decode_string($tmp[0]->text)) : NULL;
211                $head_array['to']['email'] = ( isset( $to[0]->mailbox ) ) ? ( $this->decode_string($to[0]->mailbox) . "@" . ( ( isset( $to[0]->host ) ) ? $to[0]->host : '' ) ) : NULL;
212                if(!$head_array['to']['name'])
213                        $head_array['to']['name'] = $head_array['to']['email'];
214                $head_array['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
215
216                $head_array['Size'] = $header->Size;
217
218                $head_array['attachment'] = array();
219                $head_array['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
220
221                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
2004                $mail->Body = $body;
2005
2006        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
2007                {
2008                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2009            $email = explode(",",$email);
2010            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2011            // Deve ser verificado um numero limite de destinatarios.
2012            // Deve ser verificado se os certificados sao validos.
2013            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2014            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2015            $numero_maximo = $this->preferences['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2016            $erros_acumulados = "";
2017            $aux_mails = array();
2018            $mail_list = array();
2019            if(count($email) > $numero_maximo)
2020            {
2021                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2022                return $erros_acumulados;
2023            }
2024            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2025            $email[] = $this->email;
2026            foreach($email as $item)
2027            {
2028                $certificate = $db->get_certificate(strtolower($item));
2029                if(!$certificate)
2030                {
2031                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2032                    return $erros_acumulados;
2033                }
2034
2035                if (array_key_exists("dberr1", $certificate))
2036                {
2037
2038                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2039                    return $erros_acumulados;
2040                                }
2041                if (array_key_exists("dberr2", $certificate))
2042                {
2043                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2044                    //continue;
2045                }
2046                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2047                if (!array_key_exists("certs", $certificate))
2048                {
2049                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2050                    continue;
2051                }
2052            */
2053                include_once("../security/classes/CertificadoB.php");
2054
2055                foreach ($certificate['certs'] as $registro)
2056                {
2057                    $c1 = new certificadoB();
2058                    $c1->certificado($registro['chave_publica']);
2059                    if ($c1->apresentado)
2060                    {
2061                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2062                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2063                        {
2064                            $aux_mails[] = $registro['chave_publica'];
2065                            $mail_list[] = strtolower($item);
2066                        }
2067                        else
2068                        {
2069                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2070                            {
2071                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2072                                    $c1->dados['EXPIRADO'],$c2->revogado);
2073                            }
2074
2075                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2076                            foreach($c2->erros_ssl as $linha)
2077                            {
2078                                $erros_acumulados .=  $linha . chr(0x0A);
2079                            }
2080                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2081                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2082                        }
2083                    }
2084                    else
2085                    {
2086                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2087                    }
2088                }
2089                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2090                                {
2091                                        return $erros_acumulados;
2092                        }
2093            }
2094
2095            $mail->Certs_crypt = $aux_mails;
2096        }
2097
2098          $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2099        //      Build Uploading Attachments!!!
2100                if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
2101                {
2102                        $total_uploaded_size = 0;
2103                        $upload_max_filesize = str_replace("M","",$this->preferences['max_attachment_size']) * 1024 * 1024;
2104                        foreach ($attachments as $attach)
2105                        {
2106                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2107                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2108                        }
2109                        if( $total_uploaded_size > $upload_max_filesize)
2110                                return $this->parse_error("message file too big");
2111                }
2112                else if(($params['is_local_forward']=="1") && (count($local_attachments))) { //Caso seja forward de mensagens locais
2113
2114                        $total_uploaded_size = 0;
2115                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
2116                        foreach($local_attachments as $local_attachment) {
2117                                $file_description = unserialize(rawurldecode($local_attachment));
2118                                $tmp = array_values($file_description);
2119                                foreach($file_description as $i => $descriptor){
2120                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2121                                }
2122                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2123                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2124                        }
2125                        if( $total_uploaded_size > $upload_max_filesize)
2126                                return 'false';
2127                }
2128////////////////////////////////////////////////////////////////////////////////////////////////////
2129                //      Build Forwarding Attachments!!!
2130                if (count($forwarding_attachments) > 0)
2131                {
2132                        // Bug fixed for array_search function
2133                        $name_cid_files = array();
2134                        if(count($name_cid_files) > 0) {
2135                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2136                                $name_cid_files[0] = null;
2137                        }
2138
2139                        foreach($forwarding_attachments as $forwarding_attachment)
2140                        {
2141                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2142                                        $tmp = array_values($file_description);
2143                                        foreach($file_description as $i => $descriptor){
2144                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2145                                        }
2146                                        $file_description = $tmp;
2147                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2148                                        $fileName = $file_description[2];
2149                                        if(!array_search(trim($fileName),$name_cid_files)) {
2150                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2151                                }
2152                        }
2153                }
2154
2155////////////////////////////////////////////////////////////////////////////////////////////////////
2156                // Important message
2157                if($is_important)
2158                        $mail->isImportant();
2159
2160////////////////////////////////////////////////////////////////////////////////////////////////////
2161                // Disposition-Notification-To
2162                if ($return_receipt)
2163                        $mail->ConfirmReadingTo = $this->email;
2164////////////////////////////////////////////////////////////////////////////////////////////////////
2165
2166                $sent = $mail->Send();
2167
2168                if(!$sent)
2169                {
2170                        return $this->parse_error($mail->ErrorInfo);
2171                }
2172                else
2173                {
2174            if ($signed && !$params['smime'])
2175                        {
2176                                return $sent;
2177                        }
2178                        if($this->enable_log_messages == "True")
2179                        {
2180                                $userid = $this->username;
2181                                $userip = $this->session_ip;
2182                                $now = date("d/m/y H:i:s");
2183                                $addrs = $toaddress.$ccaddress.$ccoaddress;
2184                                $sent = trim($sent);
2185                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2186                        }
2187                        if($this->preferences['number_of_contacts'] &&
2188                           $this->preferences['use_dynamic_contacts']) {
2189                                $contacts = new dynamic_contacts();
2190                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2191                                return array("success" => true, "new_contacts" => $new_contacts);
2192                        }
2193                        return array("success" => true);
2194                }
2195        }
2196
2197        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments)
2198        {
2199                //      Build CID for embedded Images!!!
2200                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2201                $cid_imgs = '';
2202                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2203                $cid_array = array();
2204                foreach($cid_imgs[6] as $j => $val){
2205                        if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2206                        {
2207                                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2208                        }
2209                        $cid = $cid_array[$cid_imgs[4][$j].$val];
2210                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2211
2212                        if ($msg_uid != $cid_imgs[4][$j]) // The image is not in the same mail?
2213                        {
2214                                $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2215                                //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
2216                                $fileName = "image_".($j).".jpg";
2217                                $fileCode = "base64";
2218                                $fileType = "image/jpg";
2219                                $file_attached[0] = $cid_imgs[2][$j];
2220                                $file_attached[1] = $cid_imgs[4][$j];
2221                                $file_attached[2] = $fileName;
2222                                $file_attached[3] = $cid_imgs[6][$j];
2223                                $file_attached[4] = 'base64';
2224                                $file_attached[5] = strlen($fileContent); //Size of file
2225                                $return_forward[] = $file_attached;
2226
2227                                unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2228                        }
2229                        else
2230                        {
2231                                $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2232                                $file_description = unserialize(rawurldecode($attach_img));
2233                                if (is_array($file_description))
2234                                        foreach($file_description as $i => $descriptor){                               
2235                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2236                                        }
2237                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2238                                $fileName = $file_description[2];
2239                                $fileCode = $file_description[4];
2240                                $fileType = $this->get_file_type($file_description[2]);
2241                                unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2242                                if (!empty($file_description))
2243                                {
2244                                        $file_description[5] = strlen($fileContent); //Size of file
2245                                        $return_forward[] = $file_description;
2246                                }
2247                        }
2248                        $tempDir = ini_get("session.save_path");
2249                        $file = "cidimage_".$this->session_id.$cid_imgs[6][$j].".dat";                                 
2250                        $f = fopen($tempDir.'/'.$file,"w");
2251                        fputs($f,$fileContent);
2252                        fclose($f);
2253                        if ($fileContent)
2254                                $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2255                        //else
2256                        //      return "Error loading image attachment content";                                               
2257
2258                }
2259                return $return_forward;
2260        }
2261    function add_recipients_cert($full_address)
2262        {
2263                $result = "";
2264                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2265                foreach ($parse_address as $val)
2266                {
2267                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2268                        if ($val->mailbox == "INVALID_ADDRESS")
2269                                continue;
2270                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2271                                continue;
2272                        if (empty($val->personal))
2273                                $result .= $val->mailbox."@".$val->host . ",";
2274                        else
2275                                $result .= $val->mailbox."@".$val->host . ",";
2276                }
2277
2278                return substr($result,0,-1);
2279        }
2280
2281        function add_recipients($recipient_type, $full_address, $mail)
2282        {
2283                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2284                foreach ($parse_address as $val)
2285                {
2286                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2287                        if ($val->mailbox == "INVALID_ADDRESS")
2288                                continue;
2289
2290                        if (empty($val->personal))
2291                        {
2292                                switch($recipient_type)
2293                                {
2294                                        case "to":
2295                                                $mail->AddAddress($val->mailbox."@".$val->host);
2296                                                break;
2297                                        case "cc":
2298                                                $mail->AddCC($val->mailbox."@".$val->host);
2299                                                break;
2300                                        case "cco":
2301                                                $mail->AddBCC($val->mailbox."@".$val->host);
2302                                                break;
2303                                }
2304                        }
2305                        else
2306                        {
2307                                switch($recipient_type)
2308                                {
2309                                        case "to":
2310                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2311                                                break;
2312                                        case "cc":
2313                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2314                                                break;
2315                                        case "cco":
2316                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2317                                                break;
2318                                }
2319                        }
2320                }
2321                return true;
2322        }
2323
2324        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2325        {
2326                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
2327                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
2328                if($encoding == 'base64')
2329                        # The function imap_base64 adds a new line
2330                        # at ASCII text, with CRLF line terminators.
2331                        # So is being exchanged for base64_decode.
2332                        #
2333                        #$fileContent = imap_base64($fileContent);
2334                        $fileContent = base64_decode($fileContent);
2335                else if($encoding == 'quoted-printable')
2336                        $fileContent = quoted_printable_decode($fileContent);
2337                return $fileContent;
2338        }
2339
2340        function del_last_caracter($string)
2341        {
2342                $string = substr($string,0,(strlen($string) - 1));
2343                return $string;
2344        }
2345
2346        function del_last_two_caracters($string)
2347        {
2348                $string = substr($string,0,(strlen($string) - 2));
2349                return $string;
2350        }
2351
2352        function messages_sort($sort_box_type, $sort_box_reverse, $search_box_type, $offsetBegin, $offsetEnd)
2353        {
2354                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
2355                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2356                        foreach($imapsort as $iuid)
2357                                $sort[$iuid] = "";
2358                       
2359                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2360                                $slice_array = false;
2361                        else
2362                                $slice_array = true;
2363                }
2364                else
2365                {
2366                        $sort = array();
2367                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2368                        $num_msgs = imap_num_msg($this->mbox);
2369                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
2370                        $slice_array = true;
2371
2372                        for ($i=$num_msgs; $i>0; $i--)
2373                        {
2374                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2375                                        break;
2376                                $iuid = @imap_uid($this->mbox,$i);
2377                                $header = $this->get_header($iuid);
2378                                // List UNSEEN messages.
2379                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2380                                        continue;
2381                                }
2382                                // List SEEN messages.
2383                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2384                                        continue;
2385                                }
2386                                // List ANSWERED messages.
2387                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2388                                        continue;
2389                                }
2390                                // List FLAGGED messages.
2391                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2392                                        continue;
2393                                }
2394
2395                                if($sort_box_type=='SORTFROM') {
2396                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $this->email)
2397                                                $from = $header->to;
2398                                        else
2399                                                $from = $header->from;
2400
2401                                        $tmp = imap_mime_header_decode($from[0]->personal);
2402
2403                                        if ($tmp[0]->text != "")
2404                                                $sort[$iuid] = $tmp[0]->text;
2405                                        else
2406                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2407                                }
2408                                else if($sort_box_type=='SORTSUBJECT') {
2409                                        $sort[$iuid] = $header->subject;
2410                                }
2411                                else if($sort_box_type=='SORTSIZE') {
2412                                        $sort[$iuid] = $header->Size;
2413                                }
2414                                else {
2415                                        $sort[$iuid] = $header->udate;
2416                                }
2417
2418                        }
2419                        natcasesort($sort);
2420
2421                        if ($sort_box_reverse)
2422                                $sort = array_reverse($sort,true);
2423                }
2424
2425                if(!is_array($sort))
2426                        $sort = array();
2427
2428
2429                if ($slice_array)
2430                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
2431
2432
2433                return $sort;
2434
2435        }
2436
2437
2438        function move_search_messages($params){
2439                $params['selected_messages'] = urldecode($params['selected_messages']);
2440                $params['new_folder'] = urldecode($params['new_folder']);
2441                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2442                $sel_msgs = explode(",", $params['selected_messages']);
2443                @reset($sel_msgs);
2444                $sorted_msgs = array();
2445                foreach($sel_msgs as $idx => $sel_msg) {
2446                        $sel_msg = explode(";", $sel_msg);
2447                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2448                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
2449                         }
2450                         else {
2451                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2452                         }
2453                }
2454                @ksort($sorted_msgs);
2455                $last_return = false;
2456                foreach($sorted_msgs as $folder => $msgs_number) {
2457                        $params['msgs_number'] = $msgs_number;
2458                        $params['folder'] = $folder;
2459                        if($params['new_folder'] && $folder != $params['new_folder']){
2460                                $last_return = $this -> move_messages($params);
2461                        }
2462                        elseif(!$params['new_folder'] || $params['delete'] ){
2463                                $last_return = $this -> delete_msgs($params);
2464                                $last_return['deleted'] = true;
2465                        }
2466                }
2467                return $last_return;
2468        }
2469
2470        function move_messages($params)
2471        {
2472                $folder = $params['folder'];
2473                $mbox_stream = $this->open_mbox($folder);
2474                $newmailbox = ($params['new_folder']);
2475                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
2476                $new_folder_name = $params['new_folder_name'];
2477                $msgs_number = $params['msgs_number'];
2478                $return = array('msgs_number' => $msgs_number,
2479                                                'folder' => $folder,
2480                                                'new_folder_name' => $new_folder_name,
2481                                                'border_ID' => $params['border_ID'],
2482                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
2483
2484                $error_log_file=$this->server_files_dir."/expressoMail.log";
2485                if($this->enable_log_messages == "True" &&
2486                strpos($msgs_number,',') != False)
2487                        error_log(date("D M j G:i:s T Y").": expressoMail, move_messages: "
2488                                .$this->username." ".$folder."=>".$new_folder_name.
2489                                " ".$msgs_number."\n", 3, $error_log_file);
2490
2491                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2492        if (substr($folder,0,4) == 'user'){
2493                $acl = $this->getacltouser($folder);
2494                /*
2495                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2496                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2497                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2498                 *   w - write (STORE flags other than SEEN and DELETED)
2499                 *   i - insert (perform APPEND, COPY into mailbox)
2500                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2501                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2502                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2503                 *   a - administer (perform SETACL)
2504                        */
2505                        if (strpos($acl, "d") === false){
2506                                $return['status'] = false;
2507                                return $return;
2508                        }
2509        }
2510        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
2511        if ($this->preferences['uid2cn']){
2512            if (substr($new_folder_name,0,4) == 'user'){
2513                $this->ldap = new ldap_functions();
2514                $tmp_folder_name = explode($this->email_server['imapDelimiter'], $new_folder_name);
2515                $return['new_folder_name'] = array_pop($tmp_folder_name);
2516                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2517                {
2518                    $return['new_folder_name'] = $cn;
2519                }
2520            }
2521        }
2522
2523                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
2524                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
2525                {
2526                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2527                        // Fix problem in unserialize function JS.
2528                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2529                }
2530
2531                $mbox_stream = $this->open_mbox($folder);
2532                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2533                        imap_expunge($mbox_stream);
2534                        if($mbox_stream)
2535                                imap_close($mbox_stream);
2536                        return $return;
2537                }else {
2538                        if(strstr(imap_last_error(),'Over quota')) {
2539                                $accountID      = $this->email_server['imapAdminUsername'];
2540                                $pass           = $this->email_server['imapAdminPW'];
2541                                $userID         = $this->username;
2542                                $server         = $this->email_server['imapServer'];
2543                                $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()))));
2544                                if(!$mbox)
2545                                        return imap_last_error();
2546                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
2547                                if(! imap_set_quota($mbox, "user".$this->email_server['imapDelimiter'].$userID, 2.1 * $quota['usage'])) {
2548                                        if($mbox_stream)
2549                                                imap_close($mbox_stream);
2550                                        if($mbox)
2551                                                imap_close($mbox);
2552                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->email_server['imapDelimiter'].$userID." line ".__LINE__."\n";
2553                                }
2554                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2555                                        imap_expunge($mbox_stream);
2556                                        if($mbox_stream)
2557                                                imap_close($mbox_stream);
2558                                        // return to original quota limit.
2559                                        if(!imap_set_quota($mbox, "user".$this->email_server['imapDelimiter'].$userID, $quota['limit'])) {
2560                                                if($mbox)
2561                                                        imap_close($mbox);
2562                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2563                                        }
2564                                        return $return;
2565                                }
2566                                else {
2567                                        if($mbox_stream)
2568                                                imap_close($mbox_stream);
2569                                        if(!imap_set_quota($mbox, "user".$this->email_server['imapDelimiter'].$userID, $quota['limit'])) {
2570                                                if($mbox)
2571                                                        imap_close($mbox);
2572                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2573                                        }
2574                                        return imap_last_error();
2575                                }
2576
2577                        }
2578                        else {
2579                                if($mbox_stream)
2580                                        imap_close($mbox_stream);
2581                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
2582                        }
2583                }
2584        }
2585
2586        function save_msg($params)
2587        {
2588
2589                include_once("class.phpmailer.php");
2590                $mail = new PHPMailer();
2591                // Set lang for PHPMailer using user prefs.
2592                list($prefix,$userlang) = explode('-',$this->lang);             
2593                $mail->SetLanguage($userlang,dirname( __FILE__ )."/../setup/");         
2594                include_once("class.db_functions.inc.php");
2595                $toaddress = $params['input_to'];
2596                $ccaddress = $params['input_cc'];
2597                $ccoaddress = $params['input_cco'];
2598                $subject = $params['input_subject'];
2599                $msg_uid = $params['msg_id'];
2600                $body = $params['body'];
2601                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
2602                $body = preg_replace("/\n/"," ",$body);
2603                $body = preg_replace("/\r/","",$body);
2604                $forwarding_attachments = $params['forwarding_attachments'];
2605                $attachments = $params['FILES'];
2606                $return_files = $params['FILES'];
2607
2608                $folder = $params['folder'];
2609                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2610                // Fix problem with cyrus delimiter changes.
2611                // Dots in names: enabled/disabled.
2612                $folder = @eregi_replace("INBOX/", "INBOX".$this->email_server['imapDelimiter'], $folder);
2613                $folder = @eregi_replace("INBOX.", "INBOX".$this->email_server['imapDelimiter'], $folder);
2614                // End Fix.
2615                if(strtoupper($folder) == 'INBOX/DRAFTS')
2616                    {
2617                        $mail->SaveMessageAsDraft = $folder;
2618                    }
2619                $mail->SaveMessageInFolder = $folder;
2620                $mail->SMTPDebug = false;
2621
2622                $mail->IsSMTP();
2623                $mail->Host = $this->email_server['smtpServer'];
2624                $mail->Port = $this->email_server['smtpPort'];
2625                $mail->From = $this->email;
2626                $mail->FromName = $this->fullname;
2627
2628                $mail->Sender = $mail->From;
2629                $mail->SenderName = $mail->FromName;
2630                $mail->FromName = $this->fullname;
2631                $mail->From =  $this->email;
2632                $session_id = $this->session_id;
2633                $max_resolution = $this->preferences['image_size'];
2634
2635                $this->add_recipients("to", $toaddress, &$mail);
2636                $this->add_recipients("cc", $ccaddress, &$mail);
2637                $this->add_recipients("cco", $ccoaddress, &$mail);
2638                $mail->Subject = $subject;
2639                $mail->IsHTML(true);
2640                $mail->Body = $body;
2641
2642                 $return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2643
2644        //      Build Forwarding Attachments!!!
2645                if (count($forwarding_attachments) > 0)
2646                {
2647                        foreach($forwarding_attachments as $forwarding_attachment)
2648                        {
2649                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2650                                $tmp = array_values($file_description);
2651                                foreach($file_description as $i => $descriptor){
2652                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2653                                }
2654                                $file_description = $tmp;
2655
2656                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2657                                $fileName = $file_description[2];
2658
2659                                $file_description[5] = strlen($fileContent); //Size of file
2660                                $return_forward[] = $file_description;
2661
2662                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2663                        }
2664                }
2665
2666                if ((count($return_forward) > 0) && (count($return_files) > 0))
2667                        $return_files = array_merge_recursive($return_forward,$return_files);
2668                else
2669                        if (count($return_files) < 1)
2670                                $return_files = $return_forward;
2671
2672                //      Build Uploading Attachments!!!
2673                $sizeof_attachments = count($attachments);
2674                if ($sizeof_attachments)
2675                        foreach ($attachments as $numb => $attach){
2676                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2677                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2678                                        switch ($image_type)
2679                                        {
2680                                        // Do not corrupt animated gif
2681                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
2682                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2683                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2684                                        case 6:
2685                                                require_once("gd_functions.php");
2686                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2687                                        default:
2688                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2689                                                break;
2690                                        }
2691                                        header('Content-type: image/jpeg');
2692                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2693                                        if ($width < $max_resolution && $height < $max_resolution){
2694                                                $new_width = $width;
2695                                                $new_height = $height;
2696                                        }
2697                                        else if ($width > $max_resolution){
2698                                                $new_width = $max_resolution;
2699                                                $new_height = $height*($new_width/$width);
2700                                        }
2701                                        else {
2702                                                $new_height = $max_resolution;
2703                                                $new_width = $width*($new_height/$height);
2704                                        }
2705                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2706                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2707                                        $tmpDir = ini_get("session.save_path");
2708                                        $_file = "/cidimage_".$session_id.".dat";
2709                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2710                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2711                                }
2712                                else
2713                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2714                                // optional name
2715                                }
2716
2717
2718
2719
2720                if(!empty($mail->AltBody))
2721            $mail->ContentType = "multipart/alternative";
2722
2723                $mail->error_count = 0; // reset errors
2724                $mail->SetMessageType();
2725                $header = $mail->CreateHeader();
2726                $body = $mail->CreateBody();
2727
2728                $mbox_stream = $this->open_mbox($folder);
2729                $new_header = str_replace("\n", "\r\n", $header);
2730                $new_body = str_replace("\n", "\r\n", $body);
2731                $return['append'] = imap_append($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort']."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2732                $status = imap_status($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort']."}".$folder, SA_UIDNEXT);
2733                $return['msg_no'] = $status->uidnext - 1;
2734                $return['folder_id'] = $folder;
2735
2736                if($mbox_stream)
2737                        imap_close($mbox_stream);
2738                if (is_array($return_files))
2739                        foreach ($return_files as $index => $_attachment) {
2740                                if (array_key_exists("name",$_attachment)){
2741                                unset($return_files[$index]);
2742                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2743                        }
2744                        else
2745                        {
2746                                unset($return_files[$index]);
2747                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2748                        }
2749                }
2750
2751                $return['files'] = serialize($return_files);
2752                $return["subject"] = $subject;
2753
2754                if (!$return['append'])
2755                        $return['append'] = imap_last_error();
2756       
2757                return $return;
2758        }
2759
2760        function set_messages_flag($params)
2761        {
2762                $folder = $params['folder'];
2763                $msgs_to_set = $params['msgs_to_set'];
2764                $flag = $params['flag'];
2765                $return = array();
2766                $return["msgs_to_set"] = $msgs_to_set;
2767                $return["flag"] = $flag;
2768
2769                if(!$this->mbox && !is_resource($this->mbox))
2770                        $this->mbox = $this->open_mbox($folder);
2771
2772                if ($flag == "unseen")
2773                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2774                elseif ($flag == "seen")
2775                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2776                elseif ($flag == "answered"){
2777                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2778                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2779                }
2780                elseif ($flag == "forwarded")
2781                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2782                elseif ($flag == "flagged")
2783                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2784                elseif ($flag == "unflagged") {
2785                        $flag_importance = false;
2786                        $msgs_number = explode(",",$msgs_to_set);
2787                        $unflagged_msgs = "";
2788                        foreach($msgs_number as $msg_number) {
2789                                preg_match('/importance *: *(.*)\r/i',
2790                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2791                                        ,$importance);
2792                                if(strtolower($importance[1])=="high" && $this->preferences['use_important_flag']) {
2793                                        $flag_importance=true;
2794                                }
2795                                else {
2796                                        $unflagged_msgs.=$msg_number.",";
2797                                }
2798                        }
2799
2800                        if($unflagged_msgs!="") {
2801                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2802                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2803                        }
2804                        else {
2805                                $return["msgs_unflageds"] = false;
2806                        }
2807
2808                        if($flag_importance && $this->preferences['use_important_flag']) {
2809                                $return["status"] = false;
2810                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2811                        }
2812                        else {
2813                                $return["status"] = true;
2814                        }
2815                }
2816
2817                if($this->mbox && is_resource($this->mbox))
2818                        imap_close($this->mbox);
2819                return $return;
2820        }
2821
2822        function get_file_type($file_name)
2823        {
2824                $file_name = strtolower($file_name);
2825                $strFileType = strrev(substr(strrev($file_name),0,4));
2826                if ($strFileType == ".asf")
2827                        return "video/x-ms-asf";
2828                if ($strFileType == ".avi")
2829                        return "video/avi";
2830                if ($strFileType == ".doc")
2831                        return "application/msword";
2832                if ($strFileType == ".zip")
2833                        return "application/zip";
2834                if ($strFileType == ".xls")
2835                        return "application/vnd.ms-excel";
2836                if ($strFileType == ".gif")
2837                        return "image/gif";
2838                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2839                        return "image/jpeg";
2840                if ($strFileType == ".png")
2841                        return "image/png";
2842                if ($strFileType == ".wav")
2843                        return "audio/wav";
2844                if ($strFileType == ".mp3")
2845                        return "audio/mpeg3";
2846                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2847                        return "video/mpeg";
2848                if ($strFileType == ".rtf")
2849                        return "application/rtf";
2850                if ($strFileType == ".htm" || $strFileType == "html")
2851                        return "text/html";
2852                if ($strFileType == ".xml")
2853                        return "text/xml";
2854                if ($strFileType == ".xsl")
2855                        return "text/xsl";
2856                if ($strFileType == ".css")
2857                        return "text/css";
2858                if ($strFileType == ".php")
2859                        return "text/php";
2860                if ($strFileType == ".asp")
2861                        return "text/asp";
2862                if ($strFileType == ".pdf")
2863                        return "application/pdf";
2864                if ($strFileType == ".txt")
2865                        return "text/plain";
2866                if ($strFileType == ".wmv")
2867                        return "video/x-ms-wmv";
2868                if ($strFileType == ".sxc")
2869                        return "application/vnd.sun.xml.calc";
2870                if ($strFileType == ".stc")
2871                        return "application/vnd.sun.xml.calc.template";
2872                if ($strFileType == ".sxd")
2873                        return "application/vnd.sun.xml.draw";
2874                if ($strFileType == ".std")
2875                        return "application/vnd.sun.xml.draw.template";
2876                if ($strFileType == ".sxi")
2877                        return "application/vnd.sun.xml.impress";
2878                if ($strFileType == ".sti")
2879                        return "application/vnd.sun.xml.impress.template";
2880                if ($strFileType == ".sxm")
2881                        return "application/vnd.sun.xml.math";
2882                if ($strFileType == ".sxw")
2883                        return "application/vnd.sun.xml.writer";
2884                if ($strFileType == ".sxq")
2885                        return "application/vnd.sun.xml.writer.global";
2886                if ($strFileType == ".stw")
2887                        return "application/vnd.sun.xml.writer.template";
2888
2889
2890                return "application/octet-stream";
2891        }
2892
2893        function htmlspecialchars_encode($str)
2894        {
2895                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
2896        }
2897        function htmlspecialchars_decode($str)
2898        {
2899                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
2900        }
2901
2902        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2903        {
2904                if(!$this->mbox || !is_resource($this->mbox))
2905                        $this->mbox = $this->open_mbox($folder);
2906
2907                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2908        }
2909
2910        function get_info_next_msg($params)
2911        {
2912                $msg_number = $params['msg_number'];
2913                $folder = $params['msg_folder'];
2914                $sort_box_type = $params['sort_box_type'];
2915                $sort_box_reverse = $params['sort_box_reverse'];
2916                $reuse_border = $params['reuse_border'];
2917                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2918                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2919
2920                $success = false;
2921                if (is_array($sort_array_msg))
2922                {
2923                        foreach ($sort_array_msg as $i => $value){
2924                                if ($value == $msg_number)
2925                                {
2926                                        $success = true;
2927                                        break;
2928                                }
2929                        }
2930                }
2931
2932                if (! $success || $i >= sizeof($sort_array_msg)-1)
2933                {
2934                        $params['status'] = 'false';
2935                        $params['delete_border'] = $reuse_border;
2936                        return $params;
2937                }
2938
2939                $params = array();
2940                $params['msg_number'] = $sort_array_msg[($i+1)];
2941                $params['msg_folder'] = $folder;
2942
2943                $return = $this->get_info_msg($params);
2944                $return["reuse_border"] = $reuse_border;
2945                return $return;
2946        }
2947
2948        function get_info_previous_msg($params)
2949        {
2950                $msg_number = $params['msgs_number'];
2951                $folder = $params['folder'];
2952                $sort_box_type = $params['sort_box_type'];
2953                $sort_box_reverse = $params['sort_box_reverse'];
2954                $reuse_border = $params['reuse_border'];
2955                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2956                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2957
2958                $success = false;
2959                if (is_array($sort_array_msg))
2960                {
2961                        foreach ($sort_array_msg as $i => $value){
2962                                if ($value == $msg_number)
2963                                {
2964                                        $success = true;
2965                                        break;
2966                                }
2967                        }
2968                }
2969                if (! $success || $i == 0)
2970                {
2971                        $params['status'] = 'false';
2972                        $params['delete_border'] = $reuse_border;
2973                        return $params;
2974                }
2975
2976                $params = array();
2977                $params['msg_number'] = $sort_array_msg[($i-1)];
2978                $params['msg_folder'] = $folder;
2979
2980                $return = $this->get_info_msg($params);
2981                $return["reuse_border"] = $reuse_border;
2982                return $return;
2983        }
2984
2985        // This function updates the values: quota, paging and new messages menu.
2986        function get_menu_values($params){
2987                $return_array = array();
2988                $return_array = $this->get_quota($params);
2989
2990                $mbox_stream = $this->open_mbox($params['folder']);
2991                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
2992                if($mbox_stream)
2993                        imap_close($mbox_stream);
2994
2995                return $return_array;
2996        }
2997
2998        function get_quota($params){
2999                // folder_id = user/{uid} for shared folders
3000                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->email_server['imapDelimiter'].'/i', $params['folder_id'])){
3001                        $array_folder =  explode($this->email_server['imapDelimiter'],$params['folder_id']);
3002                        $folder_id = "user".$this->email_server['imapDelimiter'].$array_folder[1];
3003                }
3004                // folder_id = INBOX for inbox folders
3005                else
3006                        $folder_id = "INBOX";
3007
3008                if(!$this->mbox || !is_resource($this->mbox))
3009                        $this->mbox = $this->open_mbox();
3010
3011                $quota = imap_get_quotaroot($this->mbox, $folder_id);
3012                if($this->mbox && is_resource($this->mbox))
3013                        imap_close($this->mbox);
3014
3015                if (!$quota){
3016                        return array(
3017                                'quota_percent' => 0,
3018                                'quota_used' => 0,
3019                                'quota_limit' =>  0
3020                        );
3021                }
3022
3023                if(count($quota) && $quota['limit']) {
3024                        $quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
3025                        $quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
3026                        if($quota_used >= $quota_limit)
3027                        {
3028                                $quotaPercent = 100;
3029                        }
3030                        else
3031                        {
3032                        $quotaPercent = ($quota_used / $quota_limit)*100;
3033                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
3034                        }
3035                        return array(
3036                                'quota_percent' => floor($quotaPercent),
3037                                'quota_used' => floor($quota_used),
3038                                'quota_limit' =>  floor($quota_limit)
3039                        );
3040                }
3041                else
3042                        return array();
3043        }
3044
3045        function send_notification($params){
3046                require_once("class.phpmailer.php");
3047                $mail = new PHPMailer();
3048                // Set lang for PHPMailer using user prefs.
3049                list($prefix,$userlang) = explode('-',$this->lang);             
3050                $mail->SetLanguage($userlang,dirname( __FILE__ )."/../setup/");
3051
3052                $toaddress = $params['notificationto'];
3053
3054                $subject = 'Confirmação de leitura: ' . $params['subject'];
3055                $body = 'Sua mensagem: ' . $params['subject'] . '<br>';
3056                $body .= 'foi lida por: ' . $this->fullname . ' &lt;' . $this->email . '&gt; em ' . date("d/m/Y H:i");
3057                $mail->SMTPDebug = false;
3058                $mail->IsSMTP();
3059                $mail->Host = $this->email_server['smtpServer'];
3060                $mail->Port = $this->email_server['smtpPort'];
3061                $mail->From = $this->email;
3062                $mail->FromName = $this->fullname;
3063                $mail->AddAddress($toaddress);
3064                $mail->Subject = $this->htmlspecialchars_decode($subject);
3065
3066                $mail->IsHTML(true);
3067                $mail->Body = $body;
3068
3069                if(!$mail->Send()){
3070                        return $mail->ErrorInfo;
3071                }
3072                else
3073                        return true;
3074        }
3075
3076        function empty_folder($params)
3077        {
3078                $folder = 'INBOX' . $this->email_server['imapDelimiter ']. $this->email_server[$params['clean_folder']];
3079                $mbox_stream = $this->open_mbox($folder);
3080                $return = imap_delete($mbox_stream,'1:*');
3081                if($mbox_stream)
3082                        imap_close($mbox_stream, CL_EXPUNGE);
3083                return $return;
3084        }
3085
3086        function search($params)
3087        {
3088                include("class.imap_attachment.inc.php");
3089                $imap_attachment = new imap_attachment();
3090                $criteria = $params['criteria'];
3091                $return = array();
3092                $folders = $this->get_folders_list();
3093
3094                $j = 0;
3095                foreach($folders as $folder)
3096                {
3097                        $mbox_stream = $this->open_mbox($folder);
3098                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
3099
3100                        if ($messages == '')
3101                                continue;
3102
3103                        $i = 0;
3104                        $return[$j] = array();
3105                        $return[$j]['folder_name'] = $folder['name'];
3106
3107                        foreach($messages as $msg_number)
3108                        {
3109                                $header = $this->get_header($msg_number);
3110                                if (!is_object($header))
3111                                        return false;
3112
3113                                $return[$j][$i]['msg_folder']   = $folder['name'];
3114                                $return[$j][$i]['msg_number']   = $msg_number;
3115                                $return[$j][$i]['Recent']               = $header->Recent;
3116                                $return[$j][$i]['Unseen']               = $header->Unseen;
3117                                $return[$j][$i]['Answered']     = $header->Answered;
3118                                $return[$j][$i]['Deleted']              = $header->Deleted;
3119                                $return[$j][$i]['Draft']                = $header->Draft;
3120                                $return[$j][$i]['Flagged']              = $header->Flagged;
3121
3122                                $date_msg = gmdate("d/m/Y",$header->udate);
3123                                if (gmdate("d/m/Y") == $date_msg)
3124                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
3125                                else
3126                                        $return[$j][$i]['udate'] = $date_msg;
3127
3128                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3129                                $return[$j][$i]['fromaddress'] = '';
3130                                foreach ($fromaddress as $tmp)
3131                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
3132
3133                                $from = $header->from;
3134                                $return[$j][$i]['from'] = array();
3135                                $tmp = imap_mime_header_decode($from[0]->personal);
3136                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3137                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
3138                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
3139
3140                                $to = $header->to;
3141                                $return[$j][$i]['to'] = array();
3142                                $tmp = imap_mime_header_decode($to[0]->personal);
3143                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3144                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
3145                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
3146
3147                                $subject = imap_mime_header_decode($header->fetchsubject);
3148                                $return[$j][$i]['subject'] = '';
3149                                foreach ($subject as $tmp)
3150                                        $return[$j][$i]['subject'] .= $tmp->text;
3151
3152                                $return[$j][$i]['Size'] = $header->Size;
3153                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
3154
3155                                $return[$j][$i]['attachment'] = array();
3156                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
3157
3158                                $i++;
3159                        }
3160                        $j++;
3161                        if($mbox_stream)
3162                                imap_close($mbox_stream);
3163                }
3164
3165                return $return;
3166        }
3167       
3168       
3169        function mobile_search($params)
3170        {
3171                include("class.imap_attachment.inc.php");
3172                $imap_attachment = new imap_attachment();
3173                $criterias = array ("TO","SUBJECT","FROM","CC");
3174                $return = array();
3175                $folders = $this->get_folders_list();
3176                $num_msgs = 0;
3177                                         
3178                foreach($folders as $id =>$folder)
3179                {
3180                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3181                                foreach($criterias as $criteria_fixed)
3182                    {
3183                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3184                                        $mbox_stream = $this->open_mbox($folder['folder_name']);
3185       
3186                                        $messages = imap_search($mbox_stream, $_filter, SE_UID);
3187                                       
3188                                        if ($messages == ''){
3189                                                if($mbox_stream)
3190                                                        imap_close($mbox_stream);
3191                                                continue;       
3192                                        }
3193                                                                       
3194                                        foreach($messages as $msg_number)
3195                                        {                                       
3196                                                $temp = $this->get_info_head_msg($msg_number);
3197                                                if(!$temp)
3198                                                        return false;
3199               
3200                                                $return[$num_msgs] = $temp;
3201                                                $num_msgs++;
3202                                        }
3203                                        $return['num_msgs'] = $num_msgs;
3204                                       
3205                                        if($mbox_stream)
3206                                                imap_close($mbox_stream);
3207                                }
3208                        }
3209                               
3210                }
3211                return $return;
3212        }
3213
3214        function delete_and_show_previous_message($params)
3215        {
3216                $return = $this->get_info_previous_msg($params);
3217
3218                $params_tmp1 = array();
3219                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3220                $params_tmp1['folder'] = $params['msg_folder'];
3221                $return_tmp1 = $this->delete_msg($params_tmp1);
3222
3223                $return['msg_number_deleted'] = $return_tmp1;
3224
3225                return $return;
3226        }
3227
3228
3229        function automatic_trash_cleanness($params)
3230        {
3231                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3232                $criteria =  'BEFORE "'.$before_date.'"';
3233                $trash_folder = $this->email_server['imapDefaultTrashFolder'];
3234
3235                $mbox_stream = $this->open_mbox('INBOX'.$this->email_server['imapDelimiter'].$trash_folder);
3236
3237                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3238
3239                if (is_array($messages)){
3240                        foreach ($messages as $msg_number){
3241                                imap_delete($mbox_stream, $msg_number, FT_UID);
3242                        }
3243                }
3244                if($mbox_stream)
3245                        imap_close($mbox_stream, CL_EXPUNGE);
3246                return $messages;
3247        }
3248//      Fix the search problem with special characters!!!!
3249        function remove_accents($string) {
3250                return strtr($string,
3251                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
3252                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3253        }
3254
3255        function make_search_date($date){
3256
3257            $months = array(
3258                1   => 'jan',
3259                2   => 'feb',
3260                3   => 'mar',
3261                4   => 'apr',
3262                5   => 'may',
3263                6   => 'jun',
3264                7   => 'jul',
3265                8   => 'aug',
3266                9   => 'sep',
3267                10  => 'oct',
3268                11  => 'nov',
3269                12  => 'dec'
3270            );
3271
3272            //TODO: Adaptar a data de acordo com o locale do sistema.
3273            list($day,$month,$year) = explode("/", $date);
3274            $search_date = $day."-".$months[intval($month)]."-".$year;
3275            return $search_date;
3276
3277        }
3278
3279        function search_msg($params = ''){
3280            $mbox_stream = "";
3281            if(strpos($params['condition'],"#")===false) { //local messages
3282                    $search=false;
3283            }
3284            else {
3285                    $search = explode(",",$params['condition']);
3286            }
3287
3288            if($search){
3289                $search_criteria = '';
3290                $search_result_number = $this->preferences['search_result_number'];
3291                foreach($search as $tmp)
3292                {
3293                    $tmp1 = explode("##",$tmp);
3294                    $sum = 0;
3295                    $name_box = $tmp1[0];
3296                    unset($filter);
3297                    foreach($tmp1 as $index => $criteria)
3298                    {
3299                        if ($index != 0 && strlen($criteria) != 0)
3300                        {
3301                            $filter_array = explode("<=>",rawurldecode($criteria));
3302                            $filter .= " ".$filter_array[0];
3303                            if (strlen($filter_array[1]) != 0){
3304                                if (trim($filter_array[0]) != 'BEFORE' &&
3305                                    trim($filter_array[0]) != 'SINCE' &&
3306                                    trim($filter_array[0]) != 'ON')
3307                                {
3308                                    $filter .= '"'.$filter_array[1].'"';
3309                                }
3310                                else
3311                                    {
3312                                        $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3313                                    }
3314                            }
3315                        }
3316                    }
3317                    $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3318                    $filter = $this->remove_accents($filter);
3319                    //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
3320                    if ($this->preferences['uid2cn'] && substr($name_box,0,4) == 'user')
3321                    {
3322                        $folder_name = explode($this->email_server['imapDelimiter'],$name_box);
3323                        $this->ldap = new ldap_functions();
3324                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3325                        {
3326                            $folder_name[1] = $cn;
3327                        }
3328                        $folder_name = implode($this->email_server['imapDelimiter'],$folder_name);
3329                    }
3330                    else
3331                    {
3332                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3333                    }
3334
3335                    if(!is_resource($mbox_stream))
3336                    {
3337                        $mbox_stream = $this->open_mbox($name_box);
3338                    }
3339                    else
3340                        {
3341                            imap_reopen($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}".$name_box);
3342                        }
3343
3344                    if (preg_match("/^.?\bALL\b/", $filter))
3345                    { // Quick Search, note: this ALL isn't the same ALL from imap_search
3346
3347                            $all_criterias = array ("TO","SUBJECT","FROM","CC");
3348                            foreach($all_criterias as $criteria_fixed)
3349                            {
3350                                    $_filter = $criteria_fixed . substr($filter,4);
3351
3352                                    $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
3353
3354                                    if($search_criteria) //&& count($search_criteria) < 50)
3355                                    {
3356                                            foreach($search_criteria as $new_search)
3357                                            {
3358                                                    if ($search_result_number != '65536' && $sum == $search_result_number)
3359                                                    {
3360                                                            return $retorno['sum'] = $sum;
3361                                                    }
3362                                                    $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3363                                                    $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
3364                                                    $elem['uid'] = $new_search;
3365                                                    $retorno[] = $elem;
3366                                                    $sum ++;
3367
3368                                            }
3369                                    }
3370                            }
3371                    }
3372                    else {
3373                            $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3374                            if( is_array( $search_criteria) )
3375                            {
3376                                    foreach($search_criteria as $new_search)
3377                                    {
3378                                            if ($search_result_number != '65536' && $sum == $search_result_number)
3379                                            {
3380                                                          return $retorno['sum'] = $sum;
3381                                            }
3382                                            $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3383                                            $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
3384                                            $elem['uid'] = $new_search;
3385                                            $retorno[] = $elem;
3386                                            $sum++;
3387                                    }
3388                            }
3389                    }
3390                }
3391            }
3392            if($mbox_stream)
3393            {
3394                imap_close($mbox_stream);
3395            }
3396
3397            if ($retorno)
3398            {
3399                return $retorno;
3400            }
3401            else
3402            {
3403                return 'none';
3404            }
3405        }
3406
3407        function get_msg_detail($uid_msg,$name_box, $mbox_stream )
3408        {
3409                $header = $this->get_header($uid_msg);
3410                require_once("class.imap_attachment.inc.php");
3411                $imap_attachment = new imap_attachment();
3412                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3413                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3414                $flag = $header->Unseen
3415                        .$header->Recent
3416                        .$header->Flagged
3417                        .$header->Draft
3418                        .$header->Answered
3419                        .$header->Deleted
3420                        .$attachments;
3421
3422
3423                $subject = $this->decode_string($header->fetchsubject);
3424                $from = $header->from[0]->mailbox;
3425                if($header->from[0]->personal != "")
3426                        $from = $header->from[0]->personal;
3427                $ret_msg['from'] = $this->decode_string($from);
3428                $ret_msg['subject'] = $subject;
3429                $ret_msg['udate'] = $header ->udate;
3430                $ret_msg['size'] = $header->Size;
3431                $ret_msg['flag'] = $flag;
3432                return $ret_msg;
3433        }
3434
3435        function ob_array($the_object)
3436        {
3437           $the_array=array();
3438           if(!is_scalar($the_object))
3439           {
3440               foreach($the_object as $id => $object)
3441               {
3442                   if(is_scalar($object))
3443                   {
3444                       $the_array[$id]=$object;
3445                   }
3446                   else
3447                   {
3448                       $the_array[$id]=$this->ob_array($object);
3449                   }
3450               }
3451               return $the_array;
3452           }
3453           else
3454           {
3455               return $the_object;
3456           }
3457        }
3458
3459        function getacl()
3460        {
3461                $this->ldap = new ldap_functions();
3462
3463                $return = array();
3464                $mbox_stream = $this->open_mbox();
3465                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3466
3467                $i = 0;
3468                foreach ($mbox_acl as $user => $acl)
3469                {
3470                        if ($user != $this->username)
3471                        {
3472                                $return[$i]['uid'] = $user;
3473                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3474                        }
3475                        $i++;
3476                }
3477                return $return;
3478        }
3479
3480        function setacl($params)
3481        {
3482                $old_users = $this->getacl();
3483                if (!count($old_users))
3484                        $old_users = array();
3485
3486                $tmp_array = array();
3487                foreach ($old_users as $index => $user_info)
3488                {
3489                        $tmp_array[$index] = $user_info['uid'];
3490                }
3491                $old_users = $tmp_array;
3492
3493                $users = unserialize($params['users']);
3494                if (!count($users))
3495                        $users = array();
3496
3497                //$add_share = array_diff($users, $old_users);
3498                $remove_share = array_diff($old_users, $users);
3499
3500                $mbox_stream = $this->open_mbox();
3501
3502                $serverString = "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}";
3503                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->email_server['imapDelimiter'].$this->username."*");
3504
3505                /*if (count($add_share))
3506                {
3507                        foreach ($add_share as $index=>$uid)
3508                        {
3509                        if (is_array($mailboxes_list))
3510                        {
3511                        foreach ($mailboxes_list as $key => $val)
3512                        {
3513                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3514                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3515                        }
3516                        }
3517                        }
3518                }*/
3519
3520                if (count($remove_share))
3521                {
3522                        foreach ($remove_share as $index=>$uid)
3523                        {
3524                        if (is_array($mailboxes_list))
3525                        {
3526                        foreach ($mailboxes_list as $key => $val)
3527                        {
3528                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3529                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3530                        }
3531                        }
3532                        }
3533                }
3534
3535                return true;
3536        }
3537
3538        function getaclfromuser($params)
3539        {
3540                $useracl = $params['user'];
3541
3542                $return = array();
3543                $return[$useracl] = 'false';
3544                $mbox_stream = $this->open_mbox();
3545                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3546
3547                foreach ($mbox_acl as $user => $acl)
3548                {
3549                        if (($user != $this->username) && ($user == $useracl))
3550                        {
3551                                $return[$user] = $acl;
3552                        }
3553                }
3554                return $return;
3555        }
3556
3557        function getacltouser($user)
3558        {
3559                $return = array();
3560                $mbox_stream = $this->open_mbox();
3561                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->email_server['imapDelimiter'].$user);
3562                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3563                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3564                if(substr($user,0,4) != 'user')
3565                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->email_server['imapDelimiter'].$user);
3566                else
3567                  $mbox_acl = imap_getacl($mbox_stream, $user);
3568                return $mbox_acl[$this->username];
3569        }
3570
3571
3572        function setaclfromuser($params)
3573        {
3574                $user = $params['user'];
3575                $acl = $params['acl'];
3576
3577                $mbox_stream = $this->open_mbox();
3578
3579                $serverString = "{".$this->email_server['imapServer'].":".$this->email_server['imapPort'].$this->imap_options."}";
3580                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->email_server['imapDelimiter'].$this->username."*");
3581
3582                if (is_array($mailboxes_list))
3583                {
3584                        foreach ($mailboxes_list as $key => $val)
3585                        {
3586                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3587                                $folder = str_replace("&-", "&", $folder);
3588                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3589                                {
3590                                        $return = imap_last_error();
3591                                }
3592                        }
3593                }
3594                if (isset($return))
3595                        return $return;
3596                else
3597                        return true;
3598        }
3599
3600        function download_attachment($msg,$msgno)
3601        {
3602                $array_parts_attachments = array();
3603                $array_parts_attachments['names'] = '';
3604                include_once("class.imap_attachment.inc.php");
3605                $imap_attachment = new imap_attachment();
3606
3607                if (count($msg->fname[$msgno]) > 0)
3608                {
3609                        $i = 0;
3610                        foreach ($msg->fname[$msgno] as $index=>$fname)
3611                        {
3612                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3613                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
3614                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3615                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3616                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3617                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3618                                $i++;
3619                        }
3620                }
3621                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3622                return $array_parts_attachments;
3623        }
3624
3625        function spam($params)
3626        {
3627                $is_spam = $params['spam'];
3628                $folder = $params['folder'];
3629                $mbox_stream = $this->open_mbox($folder);
3630                $msgs_number = explode(',',$params['msgs_number']);
3631
3632                foreach($msgs_number as $msg_number) {
3633                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3634                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3635                        $body = imap_body($mbox_stream, $imap_msg_number);
3636                        $msg = $header . $body;
3637                        $email = $this->email;
3638                        $username = $this->username;
3639                        strtok($email, '@');
3640                        $domain = strtok('@');
3641
3642                        //Encontrar a assinatura do dspam no cabecalho
3643                        $v = explode("\r\n", $header);
3644                        foreach ($v as $linha){
3645                                if (eregi("^Message-ID", $linha)) {
3646                                        $args = explode(" ", $linha);
3647                                        $msg_id = "'$args[1]'";
3648                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
3649                                        $args = explode(" ",$linha);
3650                                        $signature = $args[1];
3651                                }
3652                        }
3653
3654                        // Seleciona qual comando a ser executado
3655                        switch($is_spam){
3656                                case 'true':  $cmd = $this->command_for_spam; break;
3657                                case 'false': $cmd = $this->command_for_ham; break;
3658                        }
3659
3660                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3661                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
3662                        system($cmd);
3663                }
3664                imap_close($mbox_stream);
3665                return false;
3666        }
3667        function get_header($msg_number){
3668                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3669                if (!is_object($header))
3670                        return false;
3671                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
3672                $header->udate_original = $header->udate;
3673                $pdate = date_parse($header->MailDate);
3674                $header->udate +=  $pdate['zone']*(-60);
3675
3676                if($header->Flagged != "F" && $this->preferences['use_important_flag']) {
3677                        $flag = preg_match('/importance *: *(.*)\r/i',
3678                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3679                                                ,$importance);
3680                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3681                }
3682
3683                return $header;
3684        }
3685
3686//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
3687///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.
3688
3689    function insert_email($source,$folder,$timestamp){
3690        $username = $this->username;
3691        $password = $this->password;
3692        $imap_server = $this->email_server['imapServer'];
3693        $imap_port      = $this->email_server['imapPort'];
3694        $imap_options = '/notls/novalidate-cert';
3695        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3696        if(imap_last_error())
3697        {
3698            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3699       }
3700        if($timestamp){
3701            $tempDir = ini_get("session.save_path");
3702            $file = $tempDir."imap_".$this->session_id;
3703                $f = fopen($file,"w");
3704                fputs($f,base64_encode($source));
3705            fclose($f);
3706            $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);
3707            $return['command']=exec(escapeshellcmd($command));
3708        }else{
3709            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3710        }
3711        $status = imap_status($mbox_stream, "{".$this->email_server['imapServer'].":".$this->email_server['imapPort']."}".$folder, SA_UIDNEXT);
3712        $return['msg_no'] = $status->uidnext - 1;
3713                $return['error'] = imap_last_error();
3714        if($mbox_stream)
3715                        imap_close($mbox_stream);
3716        return $return;
3717
3718    }
3719
3720    function show_decript($params){
3721        $source = $params['source'];
3722        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3723        $source = str_replace(" ", "+", $source,$i);
3724
3725        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3726            if(!$source = base64_decode($source,true))
3727                return "error ".$source."Espaços ".$i;
3728
3729        }
3730        else {
3731            if(!$source = base64_decode($source))
3732                return "error ".$source."Espaços ".$i;
3733        }
3734
3735        $insert = $this->insert_email($source,'INBOX'.$this->email_server['imapDelimiter'].'decifradas');
3736
3737                $get['msg_number'] = $insert['msg_no'];
3738                $get['msg_folder'] = 'INBOX'.$this->email_server['imapDelimiter'].'decifradas';
3739                $return = $this->get_info_msg($get);
3740                $get['msg_number'] = $params['ID'];
3741                $get['msg_folder'] = $params['folder'];
3742                $tmp = $this->get_info_msg($get);
3743                if(!$tmp['status_get_msg_info'])
3744                {
3745                        $return['msg_day']=$tmp['msg_day'];
3746                        $return['msg_hour']=$tmp['msg_hour'];
3747                        $return['fulldate']=$tmp['fulldate'];
3748                        $return['smalldate']=$tmp['smalldate'];
3749                }
3750                else
3751                {
3752                        $return['msg_day']='';
3753                        $return['msg_hour']='';
3754                        $return['fulldate']='';
3755                        $return['smalldate']='';
3756                }
3757        $return['msg_no'] =$insert['msg_no'];
3758        $return['error'] = $insert['error'];
3759        $return['folder'] = $params['folder'];
3760
3761        return $return;
3762
3763    }
3764
3765//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
3766//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
3767
3768    function treat_base64_from_post($source){
3769            $offset = 0;
3770            do
3771            {
3772                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
3773                    {
3774                            $inicio = strpos($source, "\n\r", $inicio);
3775                            $fim = strpos($source, '--', $inicio);
3776                            if(!$fim)
3777                                    $fim = strpos($source,"\n\r", $inicio);
3778                            $length = $fim-$inicio;
3779                            $parte = substr( $source,$inicio,$length-1);
3780                            $parte = str_replace(" ", "+", $parte);
3781                            $source = substr_replace($source, $parte, $inicio, $length-1);
3782                    }
3783                    if($offset > $inicio)
3784                    $offset=FALSE;
3785                    else
3786                    $offset = $inicio;
3787            }
3788            while($offset);
3789            return $source;
3790    }
3791
3792//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.
3793
3794    function unarchive_mail($params)
3795    {
3796        $dest_folder = $params['folder'];
3797        $sources = explode("#@#@#@",$params['source']);
3798        $timestamps = explode("#@#@#@",$params['timestamp']);
3799        foreach($sources as $index=>$src) {
3800                        if($src!=""){
3801                                $source = $this->treat_base64_from_post($src);
3802                                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index]);
3803                        }
3804                }
3805        return $insert;
3806    }
3807
3808    function download_all_local_attachments($params)
3809    {
3810        $source = $params['source'];
3811        $source = $this->treat_base64_from_post($source);
3812        $insert = $this->insert_email($source,'INBOX'.$this->email_server['imapDelimiter'].'decifradas');
3813        $exporteml = new ExportEml();
3814        $params['num_msg']=$insert['msg_no'];
3815        $params['folder']='INBOX'.$this->email_server['imapDelimiter'].'decifradas';
3816        return $exporteml->download_all_attachments($params);
3817    }
3818
3819    function get_quota_folders(){
3820       
3821        // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
3822                include_once("class.imapfp.inc.php");           
3823                $imapfp = new imapfp();
3824               
3825            if(!$imapfp->open($this->email_server['imapServer'],$this->email_server['imapPort']))
3826                return $imapfp->get_error();           
3827                if (!$imapfp->login( $this->username,$this->password ))
3828                return $imapfp->get_error();
3829                   
3830            $response_array = $imapfp->get_mailboxes_size();
3831            if ($imapfp->error)
3832                return $imapfp->get_error();
3833           
3834            $data = array();
3835            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
3836        $data["quota_root"] = $quota_root;
3837           
3838            foreach ($response_array as $idx=>$line) {
3839                        $line2 = str_replace('"', "", $line);
3840                        $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
3841                        list($folder,$size) = explode(";",$line2);
3842                        $size = str_replace(")","",$size);
3843                        $quotaPercent = (($size / 1048576) / $data["quota_root"]["quota_limit"])*100;
3844                        if ($size < 1048576 && $size > 1024)
3845                                $quota_used = round($size / 1024, 0).' Kb';
3846                        else if($size > 1024)
3847                                $quota_used = round($size / (1024*1024), 1).' Mb';
3848                        else
3849                                $quota_used = $size." b";
3850                        $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
3851                        if(!preg_match('/user\\'.$this->email_server['imapDelimiter'].$this->username.'\\'.$this->email_server['imapDelimiter'].'/i',$folder)){
3852                                $folder = $this->functions->getLang("Inbox");
3853                        }
3854                        else
3855                                $folder = preg_replace('/user\\'.$this->email_server['imapDelimiter'].$this->username.'\\'.$this->email_server['imapDelimiter'].'/i','', $folder);
3856                       
3857                        $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
3858            }
3859            $imapfp->close();
3860        return $data;
3861        }
3862}
3863?>
Note: See TracBrowser for help on using the repository browser.