source: branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 4039

Revision 4039, 146.0 KB checked in by alexandrecorreia, 13 years ago (diff)

Ticket #1751 - Corrigido problema na lentidao da abertura das mailboxes

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