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

Revision 2484, 140.2 KB checked in by amuller, 14 years ago (diff)

Ticket #1026 - Encapsulanto o session load vars

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