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

Revision 5022, 155.8 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #2255 - campo "reply to" vazio - Alguns dominios rejeitam as msgs.

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