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

Revision 4945, 154.0 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #2224 - Caracteres estranhos em e-mail originado do Outlook

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