source: branches/2.3/expressoMail1_2/inc/class.imap_functions.inc.php @ 6264

Revision 6264, 159.1 KB checked in by brunocosta, 12 years ago (diff)

Ticket #2780 - Exclue msg do arquivamento local ao desarquivar.

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