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

Revision 2844, 137.8 KB checked in by niltonneto, 14 years ago (diff)

Ticket #1083 - Corrigido problema na mensagem após utilizar desanexar arquivo.

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