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

Revision 4014, 147.2 KB checked in by alexandrecorreia, 13 years ago (diff)

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