source: branches/2.2.0.1/expressoMail1_2/inc/class.imap_functions.inc.php @ 4243

Revision 4243, 149.1 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1739 - Login com certificado em atributo customizável

  • 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");
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((strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime') && (count($return['signature']) == 0 ) ){
924                                $return['body']='isCripted';
925                                return $return;
926                        }
927
928                        $attachment = array(); //No attachments
929
930                        if (strtolower($msg->structure[$msg_number]->subtype) == "x-pkcs7-mime")
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 = str_replace("\x00", '', $body);
1329                $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
1330
1331                $tag_list = Array('head','blink','object','frame',
1332                        'iframe','layer','ilayer','plaintext','script',
1333                        'applet','embed','frameset','xml','xmp','style');
1334
1335                $blocked_tags = array();
1336                foreach($tag_list as $index => $tag) {
1337                        $new_body = @mb_eregi_replace("<$tag", "<!--$tag", $body);
1338                        if($body != $new_body) {
1339                                $blocked_tags[] = $tag;
1340                        }
1341                        $body = @mb_eregi_replace("</$tag>", "</$tag-->", $new_body);
1342                }
1343                // Malicious Code Remove
1344                $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";
1345                preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
1346                foreach($rest[0] as $i => $val)
1347                        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
1348                                $body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
1349
1350                $body = $this-> replace_links($body);
1351
1352                //Remoção de tags <span></span> para correção de erro no firefox
1353                $body = mb_eregi_replace("<span><span>","",$body);
1354                $body = mb_eregi_replace("</span></span>","",$body);
1355                //Correção para compatibilização com Outlook, ao visualizar a mensagem
1356                $body = mb_ereg_replace('<!--\[','<!-- [',$body);
1357                $body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
1358                $body = str_replace("\x00", '', $body);
1359               
1360                return  "<span>".$body;
1361        }
1362
1363        function replace_links( $body )
1364        {
1365                // Domains and IPs addresses found in the text and which is not a link yet should be replaced by one.
1366                // See more informations in www.iana.org
1367                $octets = array(
1368                        'first' => '(2[0-3][0-9]|1[0-9]{2}|[1-9][0-9]?)',
1369                        'middle' => '(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})',
1370                        'last' => '(25[0-4]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)'
1371                );
1372
1373                $ip = "\b{$octets[ 'first' ]}\.({$octets[ 'middle' ]}\.){2}{$octets[ 'last' ]}\b";
1374
1375                $top_level_domains = '(\.(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|as|asia|at|au|aw|ax|az|'
1376                        . 'ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bl|bm|bn|bo|br|bs|bt|bv|bw|by|bz|'
1377                        . 'ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|'
1378                        . 'de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|'
1379                        . 'ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|'
1380                        . 'hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|'
1381                        . 'ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|'
1382                        . 'ma|mc|md|me|mf|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|'
1383                        . 'mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|'
1384                        . 'pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|'
1385                        . 'sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|'
1386                        . 'tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|'
1387                        . 'ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))+\b';
1388
1389                $path = '(?>\/[\w\d\/\.\'\(\)\-\+~?!&#@$%|:;,*=_]+)?';
1390                $port = '(?>:\d{2,5})?';
1391                $domain = '(?>[\w\d_\-]+)';
1392                $subdomain = "(?>{$domain}\.)*";
1393                $protocol = '(?>(http|ftp)(s)?:\/\/)?';
1394                $url = "(?>{$protocol}((?>{$subdomain}{$domain}{$top_level_domains}|{$ip}){$port}{$path}))";
1395
1396                $pattern = "/(<\w[^>]+|[\/\"'@=])?{$url}/";
1397                ini_set( 'pcre.backtrack_limit', 300000 );
1398
1399                /*
1400                // PHP 5.3
1401                $replace = function( $matches )
1402                {
1403                        if ( $matches[ 1 ] )
1404                                return $matches[ 0 ];
1405
1406                        $url = ( $matches[ 2 ] ) ? $matches[ 2 ] : 'http';
1407                        $url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";
1408                        return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";
1409                };
1410                $body = preg_replace_callback( $pattern, $replace, $body );
1411                 */
1412
1413                // PHP 5.2.x - Remover assim que possível
1414                $body = preg_replace_callback( $pattern,
1415                        create_function(
1416                                '$matches',
1417                                'if ( $matches[ 1 ] ) return $matches[ 0 ];'
1418                                . '$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : "http";'
1419                                . '$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";'
1420                                . 'return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";'
1421                        ), $body
1422                );
1423                ini_set( 'pcre.backtrack_limit', 100000 );
1424                // E-mail address in the text should create a new e-mail on ExpressoMail
1425                $pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im';
1426                $replacement = '$1<a href="mailto:$2">$2</a>$3';
1427                $body = preg_replace( $pattern, $replacement, $body );
1428
1429                return $body;
1430        }
1431
1432        function get_signature($msg, $msg_number, $msg_folder)
1433        {
1434            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1435            include_once("class.db_functions.inc.php");
1436            foreach ($msg->file_type[$msg_number] as $index => $file_type)
1437            {
1438                $sign = array();
1439                $temp = $this->get_info_head_msg($msg_number);
1440                if($temp['ContentType'] =='normal') return $sign;
1441                $file_type = strtolower($file_type);
1442                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
1443                {
1444                    if ($temp['ContentType'] == 'signature')
1445                    {
1446                        if(!$this->mbox || !is_resource($this->mbox))
1447                        $this->mbox = $this->open_mbox($msg_folder);
1448
1449                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
1450
1451                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1452                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
1453
1454                        $certificado = new certificadoB();
1455                        $validade = $certificado->verificar($imap_msg);
1456                                        $sign[] = $certificado->msg_sem_assinatura;
1457                        if ($certificado->apresentado)
1458                        {
1459                            $from = $header->from;
1460                            foreach ($from as $id => $object)
1461                            {
1462                                $fromname = $object->personal;
1463                                $fromaddress = $object->mailbox . "@" . $object->host;
1464                            }
1465                            foreach ($certificado->erros_ssl as $item)
1466                            {
1467                                $sign[] = $item . "#@#";
1468                            }
1469
1470                            if (count($certificado->erros_ssl) < 1)
1471                            {
1472                                $check_msg = 'Message untouched';
1473                                if(strtoupper($fromaddress) == strtoupper($certificado->dados['EMAIL']))
1474                                {
1475                                    $check_msg .= ' and authentic###';
1476                                }
1477                                else
1478                                {
1479                                    $check_msg .= ' with signer different from sender#@#';
1480                                }
1481                                $sign[] = $check_msg;
1482                            }
1483                                               
1484                            $sign[] = 'Message signed by: ###' . $certificado->dados['NOME'];
1485                            $sign[] = 'Certificate email: ###' . $certificado->dados['EMAIL'];
1486                            $sign[] = 'Mail from: ###' . $fromaddress;
1487                            $sign[] = 'Certificate Authority: ###' . $certificado->dados['EMISSOR'];
1488                            $sign[] = 'Validity of certificate: ###' . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
1489                            $sign[] = 'Message date: ###' . $header->Date;
1490
1491                            $cert = openssl_x509_parse($certificado->cert_assinante);
1492
1493                            $sign_alert = array();
1494                            $sign_alert[] = 'Certificate Owner###:\n';
1495                            $sign_alert[] = 'Common Name (CN)###  ' . $cert[subject]['CN'] .  '\n';
1496                            $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1497                            $sign_alert[]= 'Organization (O)###  ' . $cert[subject]['O'] .  '\n';
1498                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[subject]['OU'][0] .  '\n';
1499                            //$sign_alert[] = 'Serial Number### ' . $cert['serialNumber'] . '\n';
1500                            $sign_alert[] = 'Personal Data###:' . '\n';
1501                            $sign_alert[] = 'Birthday### ' . $X .  '\n';
1502                            $sign_alert[]= 'Fiscal Id### ' . $certificado->dados['CPF'] .  '\n';
1503                            $sign_alert[]= 'Identification### ' . $certificado->dados['RG'] .  '\n\n';
1504                            $sign_alert[]= 'Certificate Issuer###:\n';
1505                            $sign_alert[]= 'Common Name (CN)###  ' . $cert[issuer]['CN'] . '\n';
1506                            $sign_alert[]= 'Organization (O)###  ' . $cert[issuer]['O'] .  '\n';
1507                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[issuer]['OU'][0] .  '\n\n';
1508                            $sign_alert[]= 'Validity###:\n';
1509                            $H = data_hora($cert[validFrom]);
1510                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1511                            $sign_alert[]= 'Valid From### ' . $X .  '\n';
1512                            $H = data_hora($cert[validTo]);
1513                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1514                            $sign_alert[]= 'Valid Until### ' . $X;
1515                            $sign[] = $sign_alert;
1516
1517                            $this->db = new db_functions();
1518                           
1519                            // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
1520                            if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
1521                                $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
1522                        }
1523                        else
1524                        {
1525                            $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
1526                            foreach($certificado->erros_ssl as $item)
1527                                $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
1528                        }
1529                    }
1530                }
1531            }
1532            return $sign;
1533        }
1534
1535        function get_thumbs($msg, $msg_number, $msg_folder)
1536        {
1537                $thumbs_array = array();
1538                $i = 0;
1539        foreach ($msg->file_type[$msg_number] as $index => $file_type)
1540        {
1541                $file_type = strtolower($file_type);
1542                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
1543                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
1544                                $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].">";
1545                                $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>";
1546                                        $thumbs_array[] = $href;
1547                        }
1548                        $i++;
1549                }
1550        }
1551        return $thumbs_array;
1552        }
1553
1554        /*function delete_msg($params)
1555        {
1556                $folder = $params['folder'];
1557                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
1558
1559                $mbox_stream = $this->open_mbox($folder);
1560
1561                foreach ($msgs_to_delete as $msg_number){
1562                        imap_delete($mbox_stream, $msg_number, FT_UID);
1563                }
1564                imap_close($mbox_stream, CL_EXPUNGE);
1565                return $params['msgs_to_delete'];
1566        }*/
1567
1568        // Novo
1569        function delete_msgs($params)
1570        {
1571
1572                $folder = $params['folder'];
1573                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
1574                $msgs_number = explode(",",$params['msgs_number']);
1575                $border_ID = $params['border_ID'];
1576
1577                $return = array();
1578
1579                if ($params['get_previous_msg']){
1580                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1581                        // Fix problem in unserialize function JS.
1582                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1583                }
1584
1585                //$mbox_stream = $this->open_mbox($folder);
1586                $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()))));
1587
1588                foreach ($msgs_number as $msg_number)
1589                {
1590                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1591                                $return['msgs_number'][] = $msg_number;
1592                }
1593
1594                $return['folder'] = $folder;
1595                $return['border_ID'] = $border_ID;
1596
1597                if($mbox_stream)
1598                        imap_close($mbox_stream, CL_EXPUNGE);
1599                return $return;
1600        }
1601
1602
1603        function refresh($params)
1604        {
1605
1606                $folder = $params['folder'];
1607                $msg_range_begin = $params['msg_range_begin'];
1608                $msg_range_end = $params['msg_range_end'];
1609                $msgs_existent = $params['msgs_existent'];
1610                $sort_box_type = $params['sort_box_type'];
1611                $sort_box_reverse = $params['sort_box_reverse'];
1612                $msgs_in_the_server = array();
1613                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1614                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1615                $msgs_in_the_server = array_keys($msgs_in_the_server);
1616                if(!count($msgs_in_the_server))
1617                        return array();
1618
1619                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
1620                $msgs_in_the_client = explode(",", $msgs_existent);
1621
1622                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
1623                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
1624
1625                $msgs_to_exec = array();
1626                foreach($msg_to_insert as $msg_number)
1627                        $msgs_to_exec[] = $msg_number;
1628                sort($msgs_to_exec);
1629
1630                $return = array();
1631                $i = 0;
1632                foreach($msgs_to_exec as $msg_number)
1633                {
1634                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
1635                        * atributos do cabeçalho. Como eu preciso do atributo Importance
1636                        * para saber se o email é importante ou não, uso abaixo a função
1637                        * imap_fetchheader e busco o atributo importance nela para passar
1638                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1639                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1640                        * não preciso reimplementar o método utilizando o fetchheader.
1641                        */
1642   
1643                        $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1644                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
1645                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
1646
1647                        $msg_sample = $this->get_msg_sample($msg_number);
1648                        $return[$i]['msg_sample'] = $msg_sample;
1649
1650                        $header = $this->get_header($msg_number);
1651                        if (!is_object($header))
1652                                continue;
1653
1654                        $return[$i]['msg_number']       = $msg_number;
1655                       
1656                        //get the next msg number to append this msg in the view in a correct place
1657                        $msg_key_position = array_search($msg_number, $msgs_in_the_server);
1658                       
1659                        if($msg_key_position !== false && array_key_exists($msg_key_position + 1) !== false)
1660                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position + 1];
1661
1662                        $return[$i]['msg_folder']       = $folder;
1663                        // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1664                        $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
1665                        $return[$i]['Recent']           = $header->Recent;
1666                        $return[$i]['Unseen']           = $header->Unseen;
1667                        $return[$i]['Answered']         = $header->Answered;
1668                        $return[$i]['Deleted']          = $header->Deleted;
1669                        $return[$i]['Draft']            = $header->Draft;
1670                        $return[$i]['Flagged']          = $header->Flagged;
1671
1672                        $return[$i]['udate'] = $header->udate;
1673               
1674                        $from = $header->from;
1675                        $return[$i]['from'] = array();
1676                        $tmp = imap_mime_header_decode($from[0]->personal);
1677                        $return[$i]['from']['name'] = $tmp[0]->text;
1678                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
1679                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
1680                        if(!$return[$i]['from']['name'])
1681                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
1682
1683                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1684                        $return[$i]['toaddress'] = '';
1685                        foreach ($toaddress as $tmp)
1686                                $return[$i]['toaddress'] .= $tmp->text;*/
1687                        $to = $header->to;
1688                        $return[$i]['to'] = array();
1689                        $tmp = imap_mime_header_decode($to[0]->personal);
1690                        $return[$i]['to']['name'] = $tmp[0]->text;
1691                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1692                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
1693                        $cc = $header->cc;
1694                        if ( ($cc) && (!$return[$i]['to']['name']) ){
1695                                $return[$i]['to']['name'] =  $cc[0]->personal;
1696                                $return[$i]['to']['email'] = $cc[0]->mailbox . "@" . $cc[0]->host;
1697                        }
1698                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1699
1700                        $return[$i]['Size'] = $header->Size;
1701                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
1702
1703                        $return[$i]['attachment'] = array();
1704                        if (!isset($imap_attachment))
1705                        {
1706                                include_once("class.imap_attachment.inc.php");
1707                                $imap_attachment = new imap_attachment();
1708                        }
1709                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
1710                        $i++;
1711                }
1712                $return['quota'] = $this->get_quota(array('folder_id' => $folder));
1713                $return['sort_box_type'] = $params['sort_box_type'];
1714                if(!$this->mbox || !is_resource($this->mbox))
1715                {
1716                    $this->open_mbox($folder);
1717                }
1718                $return['new_msgs'] = imap_num_recent($this->mbox);
1719                $return['msgs_to_delete'] = $msg_to_delete;
1720                $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
1721                if($this->mbox && is_resource($this->mbox))
1722                        imap_close($this->mbox);
1723
1724                return $return;
1725        }
1726
1727     /**
1728     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1729     * assinado ou cifrado.
1730     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1731     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1732     * @param $msg_number O número da mesagem
1733     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1734     */
1735    function getMessageType($msg_number, $headers = false){
1736            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1737            $contentType = "normal";
1738            if (!$headers){
1739                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1740            }
1741           
1742            if (preg_match("/pkcs7-signature/i", $headers) == 1){
1743                $contentType = "signature";
1744            } else if (preg_match("/pkcs7-mime/i", $headers) == 1){
1745                $contentType = testa_p7m( imap_body($this->mbox, imap_msgno($this->mbox, $msg_number)) );
1746            }
1747
1748            return $contentType;
1749    }
1750
1751         /**
1752     * Metodo que retorna todas as pastas do usuario logado.
1753     * @param $params array opcional para repassar os argumentos ao metodo.
1754     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
1755     * excluindo as compartilhadas para ele.
1756     * Se usar $params['folderType'] = "default" irá retornar somente as pastas defaults
1757     * Se usar $params['folderType'] = "personal" irá retornar somente as pastas pessoais
1758     * Se usar $params['folderType'] = null irá retornar todas as pastas
1759     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
1760     * folder_id, folder_name, folder_parent e folder_hasChildren.
1761     */
1762        function get_folders_list($params = null)
1763        {
1764                $mbox_stream = $this->open_mbox();
1765                if($params && $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
1766                        $this->delete_mailbox(array("del_past" => "INBOX/decifradas"));
1767                }
1768
1769                $inbox = 'INBOX';
1770                $trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
1771                $drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
1772                $spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
1773                $sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
1774                $uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'];
1775                // Free others requests
1776                session_write_close();
1777
1778                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
1779               
1780                if ( $params && $params['noSharedFolders'] )
1781                        $folders_list = array_merge(imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ), imap_getmailboxes($mbox_stream, $serverString, 'INBOX/*' ) );
1782                else
1783                        $folders_list = imap_getmailboxes($mbox_stream, $serverString, '*' );
1784
1785                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1786
1787                $tmp = array();
1788                $resultMine = array();
1789                $resultDefault = array();
1790
1791                if (is_array($folders_list)) {
1792                        reset($folders_list);
1793                        $this->ldap = new ldap_functions();
1794
1795                        $i = 0;
1796                        while (list($key, $val) = each($folders_list)) {
1797                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
1798
1799                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1800                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
1801
1802                                if($tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas') {
1803                                        //error_log('passou', 3,'/tmp/imap_get_list.log');
1804                                        //imap_deletemailbox($mbox_stream,imap_utf7_encode("{".$this->imap_server."}".'INBOX/decifradas'));
1805                                        continue;
1806                                }
1807                                $result[$i]['folder_unseen'] = $status->unseen;
1808                                $folder_id = $tmp_folder_id[1];
1809                                $result[$i]['folder_id'] = $folder_id;
1810
1811                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1812                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1813                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1814                       
1815                                if ($uid2cn && substr($folder_id,0,4) == 'user') {
1816                                        //$this->ldap = new ldap_functions();
1817                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
1818                                                $result[$i]['folder_name'] = $cn;
1819                                        }
1820                                }
1821
1822                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1823                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
1824
1825                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1826                                        $result[$i]['folder_hasChildren'] = 1;
1827                                else
1828                                        $result[$i]['folder_hasChildren'] = 0;
1829
1830                                switch ($tmp_folder_id[1]) {
1831                                        case $inbox:
1832                                        case $sent:
1833                                        case $drafts:
1834                                        case $spam:
1835                                        case $trash:
1836                                                $resultDefault[]=$result[$i];
1837                                                break;
1838                                        default:
1839                                                $resultMine[]=$result[$i];
1840                                }
1841
1842                                $i++;
1843                        }
1844                }
1845
1846                if ( $params && !$params['noQuotaInfo'] ) {
1847                        //Get quota info of current folder
1848                        $current_folder = "INBOX";
1849                        if($params && $params['folder'])
1850                                $current_folder = $params['folder'];
1851
1852                        $arr_quota_info = $this->get_quota(array('folder_id' => $current_folder));
1853                } else {
1854                        $arr_quota_info = array();
1855                }
1856
1857                // Sorting resultMine
1858                foreach ($resultMine as $folder_info)
1859                {
1860                        $array_tmp[] = $folder_info['folder_id'];
1861                }
1862
1863                natcasesort($array_tmp);
1864               
1865                $result2 = array();
1866
1867                foreach ($array_tmp as $key => $folder_id)
1868                {
1869                        $result2[] = $resultMine[$key];
1870                }
1871               
1872                // Sorting resultDefault
1873                foreach ($resultDefault as $key => $folder_id)
1874                {
1875                        switch ($resultDefault[$key]['folder_id']) {
1876                                case $inbox:
1877                                        $resultDefault2[0] = $resultDefault[$key];
1878                                        break;
1879                                case $sent:
1880                                        $resultDefault2[1] = $resultDefault[$key];
1881                                        break;
1882                                case $drafts:
1883                                        $resultDefault2[2] = $resultDefault[$key];
1884                                        break;
1885                                case $spam:
1886                                        $resultDefault2[3] = $resultDefault[$key];
1887                                        break;
1888                                case $trash:
1889                                        $resultDefault2[4] = $resultDefault[$key];
1890                                        break;
1891                        }
1892                }
1893               
1894                if ( $params && $params['folderType'] && $params['folderType'] == 'default' )
1895                        return array_merge($resultDefault2, $arr_quota_info);
1896
1897                if ( $params && $params['folderType'] && $params['folderType'] == 'personal' )
1898                        return array_merge($result2, $arr_quota_info);
1899
1900                // Merge default folders and personal
1901                $result2 = array_merge($resultDefault2, $result2);
1902               
1903                return array_merge($result2, $arr_quota_info);
1904        }
1905
1906        function create_mailbox($arr)
1907        {
1908                $namebox        = $arr['newp'];
1909                $mbox_stream = $this->open_mbox();
1910                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1911                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
1912
1913                $result = "Ok";
1914                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
1915                {
1916                        $result = implode("<br />\n", imap_errors());
1917                }
1918
1919                if($mbox_stream)
1920                        imap_close($mbox_stream);
1921
1922                return $result;
1923
1924        }
1925
1926        function create_extra_mailbox($arr)
1927        {
1928                $nameboxs = explode(";",$arr['nw_folders']);
1929                $result = "";
1930                $mbox_stream = $this->open_mbox();
1931                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1932                foreach($nameboxs as $key=>$tmp){
1933                        if($tmp != ""){
1934                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1935                                        $result = implode("<br />\n", imap_errors());
1936                                        if($mbox_stream)
1937                                                imap_close($mbox_stream);
1938                                        return $result;
1939                                }
1940                        }
1941                }
1942                if($mbox_stream)
1943                        imap_close($mbox_stream);
1944                return true;
1945        }
1946
1947        function delete_mailbox($arr)
1948        {
1949                $namebox = $arr['del_past'];
1950                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1951                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
1952                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
1953
1954                $result = "Ok";
1955                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1956                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1957                {
1958                        $result = implode("<br />\n", imap_errors());
1959                }
1960                /*
1961                if($mbox_stream)
1962                        imap_close($mbox_stream);
1963                */
1964                return $result;
1965        }
1966
1967        function ren_mailbox($arr)
1968        {
1969                $namebox = $arr['current'];
1970                $new_box = $arr['rename'];
1971                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1972                $mbox_stream = $this->open_mbox();
1973                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
1974
1975                $result = "Ok";
1976                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1977                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
1978
1979                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1980                {
1981                        $result = imap_errors();
1982                }
1983                if($mbox_stream)
1984                        imap_close($mbox_stream);
1985                return $result;
1986
1987        }
1988
1989        function get_num_msgs($params)
1990        {
1991                $folder = $params['folder'];
1992                if(!$this->mbox || !is_resource($this->mbox)) {
1993                        $this->mbox = $this->open_mbox($folder);
1994                        if(!$this->mbox || !is_resource($this->mbox))
1995                        return imap_last_error();
1996                }
1997                $num_msgs = imap_num_msg($this->mbox);
1998                if($this->mbox && is_resource($this->mbox))
1999                        imap_close($this->mbox);
2000
2001                return $num_msgs;
2002        }
2003
2004        function folder_exists($folder){
2005                $mbox =  $this->open_mbox();
2006                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";           
2007                $list = imap_getmailboxes($mbox,$serverString, $folder);
2008                $return = is_array($list);             
2009                imap_close($mbox);
2010                return $return;
2011        }
2012       
2013        function send_mail($params)
2014        {
2015                include_once("class.phpmailer.php");
2016                $mail = new PHPMailer();
2017                include_once("class.db_functions.inc.php");
2018                $db = new db_functions();
2019                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
2020                ##
2021                # @AUTHOR Rodrigo Souza dos Santos
2022                # @DATE 2008/09/17$fileName
2023                # @BRIEF Checks if the user has permission to send an email with the email address used.
2024                ##
2025                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
2026                {
2027                        $deny = true;
2028                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
2029                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
2030                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
2031
2032                        if ( $deny )
2033                                return "The server denied your request to send a mail, you cannot use this mail address.";
2034                }
2035
2036                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
2037                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
2038                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
2039                $replytoaddress = $params['input_replyto'];
2040                $subject = $params['input_subject'];
2041                $msg_uid = $params['msg_id'];
2042                $return_receipt = $params['input_return_receipt'];
2043                $is_important = $params['input_important_message'];
2044        $encrypt = $params['input_return_cripto'];
2045                $signed = $params['input_return_digital'];
2046
2047                if($params['smime'])
2048        {
2049            $body = $params['smime'];
2050            $mail->SMIME = true;
2051            // A MSG assinada deve ser testada neste ponto.
2052            // Testar o certificado e a integridade da msg....
2053            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2054            $erros_acumulados = '';
2055            $certificado = new certificadoB();
2056            $validade = $certificado->verificar($body);
2057            if(!$validade)
2058            {
2059                foreach($certificado->erros_ssl as $linha_erro)
2060                {
2061                    $erros_acumulados .= $linha_erro;
2062                }
2063            }
2064            else
2065            {
2066                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
2067                if ($certificado->apresentado)
2068                {
2069                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
2070                    $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;
2071                    if($certificado->dados['CPF'] != $this->cpf) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
2072                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
2073                }
2074                else
2075                {
2076                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
2077                }
2078            }
2079            if(!$erros_acumulados =='')
2080            {
2081                return $erros_acumulados;
2082            }
2083        }
2084        else
2085        {
2086            $body = $params['body'];
2087            //Compatibilização com Outlook, ao encaminhar a mensagem
2088            $body = mb_ereg_replace('<!--\[','<!-- [',$body);
2089        }
2090                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
2091                $attachments = $_FILES;
2092                $forwarding_attachments = $params['forwarding_attachments'];
2093                $local_attachments = $params['local_attachments'];
2094
2095                //Test if must be saved in shared folder and change if necessary
2096                if( $fromaddress[2] == 'y' ){
2097                        //build shared folder path
2098                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
2099                        if( $this->folder_exists($newfolder) ) $folder = $newfolder;
2100                        else $folder =  $params['folder'];                     
2101                } else  {
2102                        $folder = $params['folder'];                   
2103                }
2104               
2105                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2106                $folder_name = $params['folder_name'];
2107                // Fix problem with cyrus delimiter changes.
2108                // Dots in names: enabled/disabled.
2109                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2110                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2111                // End Fix.
2112                if ($folder != 'null'){
2113                        $mail->SaveMessageInFolder = $folder;
2114                }
2115////////////////////////////////////////////////////////////////////////////////////////////////////
2116                $mail->SMTPDebug = false;
2117
2118                if($signed && !$params['smime'])
2119                {
2120            $mail->Mailer = "smime";
2121                        $mail->SignedBody = true;
2122                }
2123                else
2124            $mail->IsSMTP();
2125
2126                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2127                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2128                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2129                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2130                if($fromaddress){
2131                        $mail->Sender = $mail->From;
2132                        $mail->SenderName = $mail->FromName;
2133                        $mail->FromName = $fromaddress[0];
2134                        $mail->From = $fromaddress[1];
2135                }
2136
2137                $this->add_recipients("to", $toaddress, &$mail);
2138                $this->add_recipients("cc", $ccaddress, &$mail);
2139                $this->add_recipients("cco", $ccoaddress, &$mail);
2140                $mail->AddReplyTo($replytoaddress);
2141                $mail->Subject = $subject;
2142                $mail->IsHTML($params['type'] != 'textplain');
2143                $mail->Body = $body;
2144
2145        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
2146                {
2147                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2148            $email = explode(",",$email);
2149            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2150            // Deve ser verificado um numero limite de destinatarios.
2151            // Deve ser verificado se os certificados sao validos.
2152            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2153            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2154            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2155            $erros_acumulados = "";
2156            $aux_mails = array();
2157            $mail_list = array();
2158            if(count($email) > $numero_maximo)
2159            {
2160                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2161                return $erros_acumulados;
2162            }
2163            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2164            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2165            foreach($email as $item)
2166            {
2167                $certificate = $db->get_certificate(strtolower($item));
2168                if(!$certificate)
2169                {
2170                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2171                    return $erros_acumulados;
2172                }
2173
2174                if (array_key_exists("dberr1", $certificate))
2175                {
2176
2177                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2178                    return $erros_acumulados;
2179                                }
2180                if (array_key_exists("dberr2", $certificate))
2181                {
2182                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2183                    //continue;
2184                }
2185                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2186                if (!array_key_exists("certs", $certificate))
2187                {
2188                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2189                    continue;
2190                }
2191            */
2192                include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2193
2194                foreach ($certificate['certs'] as $registro)
2195                {
2196                    $c1 = new certificadoB();
2197                    $c1->certificado($registro['chave_publica']);
2198                    if ($c1->apresentado)
2199                    {
2200                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2201                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2202                        {
2203                            $aux_mails[] = $registro['chave_publica'];
2204                            $mail_list[] = strtolower($item);
2205                        }
2206                        else
2207                        {
2208                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2209                            {
2210                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2211                                    $c1->dados['EXPIRADO'],$c2->revogado);
2212                            }
2213
2214                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2215                            foreach($c2->erros_ssl as $linha)
2216                            {
2217                                $erros_acumulados .=  $linha . chr(0x0A);
2218                            }
2219                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2220                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2221                        }
2222                    }
2223                    else
2224                    {
2225                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2226                    }
2227                }
2228                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2229                                {
2230                                        return $erros_acumulados;
2231                        }
2232            }
2233
2234            $mail->Certs_crypt = $aux_mails;
2235        }
2236                // Build CID images
2237                $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2238
2239                //      Build Uploading Attachments!!!
2240                if (count($attachments)>0) //Caso seja forward normal...
2241                {
2242                        $total_uploaded_size = 0;
2243                        $upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
2244                        foreach ($attachments as $attach)
2245                        {
2246                                if($attach['error'] == UPLOAD_ERR_INI_SIZE)
2247                                    return $this->parse_error("message file too big");
2248                                if($attach['name']=='Unknown')
2249                                        continue;
2250                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2251                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2252                        }
2253                        if( $total_uploaded_size > $upload_max_filesize){
2254                                return $this->parse_error("message file too big");
2255                        }
2256                }
2257                if(count($local_attachments)>0) { //Caso seja forward de mensagens locais
2258
2259                        $total_uploaded_size = 0;
2260                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
2261                        foreach($local_attachments as $local_attachment) {
2262                                $file_description = unserialize(rawurldecode($local_attachment));
2263                                $tmp = array_values($file_description);
2264                                foreach($file_description as $i => $descriptor){
2265                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2266                                }
2267                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2268                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2269                        }
2270                        if( $total_uploaded_size > $upload_max_filesize)
2271                                return 'false';
2272                }
2273////////////////////////////////////////////////////////////////////////////////////////////////////
2274                //      Build Forwarding Attachments!!!
2275                if (count($forwarding_attachments) > 0)
2276                {
2277                        // Bug fixed for array_search function
2278                        $name_cid_files = array();
2279                        if(count($name_cid_files) > 0) {
2280                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2281                                $name_cid_files[0] = null;
2282                        }
2283
2284                        foreach($forwarding_attachments as $forwarding_attachment)
2285                        {
2286                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2287                                        $tmp = array_values($file_description);
2288                                        foreach($file_description as $i => $descriptor){
2289                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2290                                        }
2291                                        $file_description = $tmp;
2292                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2293                                        $fileName = $file_description[2];
2294                                        if(!array_search(trim($fileName),$name_cid_files)) {
2295                                                $mail->AddStringAttachment($fileContent,html_entity_decode(rawurldecode($fileName)), $file_description[4], $this->get_file_type($file_description[2]));
2296                                }
2297                        }
2298                }
2299
2300////////////////////////////////////////////////////////////////////////////////////////////////////
2301                // Important message
2302                if($is_important)
2303                        $mail->isImportant();
2304
2305////////////////////////////////////////////////////////////////////////////////////////////////////
2306                // Disposition-Notification-To
2307                if ($return_receipt)
2308                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2309////////////////////////////////////////////////////////////////////////////////////////////////////
2310
2311                $sent = $mail->Send();
2312
2313                if(!$sent)
2314                {
2315                        return $this->parse_error($mail->ErrorInfo);
2316                }
2317                else
2318                {
2319            if ($signed && !$params['smime'])
2320                        {
2321                                return $sent;
2322                        }
2323                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
2324                        {
2325                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2326                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
2327                                $now = date("d/m/y H:i:s");
2328                                $addrs = $toaddress.$ccaddress.$ccoaddress;
2329                                $sent = trim($sent);
2330                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2331                        }
2332                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
2333                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
2334                                $contacts = new dynamic_contacts();
2335                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2336                                return array("success" => true, "new_contacts" => $new_contacts);
2337                        }
2338                        return array("success" => true);
2339                }
2340        }
2341        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments)
2342        {
2343                //      Build CID for embedded Images!!!
2344                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2345                $cid_imgs = '';
2346                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2347                $cid_array = array();
2348                foreach($cid_imgs[6] as $j => $val){
2349                        if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2350                        {
2351                                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2352                        }
2353                        $cid = $cid_array[$cid_imgs[4][$j].$val]; 
2354                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2355
2356                        if ($msg_uid != $cid_imgs[4][$j]) // The image is not in the same mail?
2357                        {
2358                                $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2359                                //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
2360                                $fileName = "image_".($j).".jpg";
2361                                $fileCode = "base64";
2362                                $fileType = "image/jpg";
2363                                $file_attached[0] = $cid_imgs[2][$j];
2364                                $file_attached[1] = $cid_imgs[4][$j];
2365                                $file_attached[2] = $fileName;
2366                                $file_attached[3] = $cid_imgs[6][$j];
2367                                $file_attached[4] = 'base64';
2368                                $file_attached[5] = strlen($fileContent); //Size of file
2369                                $return_forward[] = $file_attached;
2370
2371                                $attachment_ = unserialize(rawurldecode($forwarding_attachments[$cid_imgs[6][$j]-2]));
2372                                if ($file_attached[3] == $attachment_[3])
2373                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);     
2374                        }
2375                        else
2376                        {
2377                                $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2378                                $file_description = unserialize(rawurldecode($attach_img));
2379                                if (is_array($file_description))
2380                                        foreach($file_description as $i => $descriptor){                                 
2381                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2382                                        }
2383                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2384                                $fileName = $file_description[2];
2385                                $fileCode = $file_description[4];
2386                                $fileType = $this->get_file_type($file_description[2]);
2387                                unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2388                                if (!empty($file_description))
2389                                {
2390                                        $file_description[5] = strlen($fileContent); //Size of file
2391                                        $return_forward[] = $file_description;
2392                                }
2393                        }
2394                        $tempDir = ini_get("session.save_path");
2395                        $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                       
2396                        $f = fopen($tempDir.'/'.$file,"w");
2397                        fputs($f,$fileContent);
2398                        fclose($f);
2399                        if ($fileContent)
2400                                $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2401                        //else
2402                        //      return "Error loading image attachment content";                                                 
2403
2404                }
2405                return $return_forward;
2406        }
2407        function add_recipients_cert($full_address)
2408        {
2409                $result = "";
2410                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2411                foreach ($parse_address as $val)
2412                {
2413                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2414                        if ($val->mailbox == "INVALID_ADDRESS")
2415                                continue;
2416                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2417                                continue;
2418                        if (empty($val->personal))
2419                                $result .= $val->mailbox."@".$val->host . ",";
2420                        else
2421                                $result .= $val->mailbox."@".$val->host . ",";
2422                }
2423
2424                return substr($result,0,-1);
2425        }
2426
2427        function add_recipients($recipient_type, $full_address, $mail)
2428        {
2429                //remove a comma if is given two unexpected commas
2430                $full_address = preg_replace("/, ?,/",",",$full_address);
2431                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2432                foreach ($parse_address as $val)
2433                {
2434                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2435                        if ($val->mailbox == "INVALID_ADDRESS")
2436                                continue;
2437
2438                        if (empty($val->personal))
2439                        {
2440                                switch($recipient_type)
2441                                {
2442                                        case "to":
2443                                                $mail->AddAddress($val->mailbox."@".$val->host);
2444                                                break;
2445                                        case "cc":
2446                                                $mail->AddCC($val->mailbox."@".$val->host);
2447                                                break;
2448                                        case "cco":
2449                                                $mail->AddBCC($val->mailbox."@".$val->host);
2450                                                break;
2451                                }
2452                        }
2453                        else
2454                        {
2455                                switch($recipient_type)
2456                                {
2457                                        case "to":
2458                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2459                                                break;
2460                                        case "cc":
2461                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2462                                                break;
2463                                        case "cco":
2464                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2465                                                break;
2466                                }
2467                        }
2468                }
2469                return true;
2470        }
2471
2472        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2473        {
2474                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
2475                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
2476                if($encoding == 'base64')
2477                        # The function imap_base64 adds a new line
2478                        # at ASCII text, with CRLF line terminators.
2479                        # So is being exchanged for base64_decode.
2480                        #
2481                        #$fileContent = imap_base64($fileContent);
2482                        $fileContent = base64_decode($fileContent);
2483                else if($encoding == 'quoted-printable')
2484                        $fileContent = quoted_printable_decode($fileContent);
2485                return $fileContent;
2486        }
2487
2488        function del_last_caracter($string)
2489        {
2490                $string = substr($string,0,(strlen($string) - 1));
2491                return $string;
2492        }
2493
2494        function del_last_two_caracters($string)
2495        {
2496                $string = substr($string,0,(strlen($string) - 2));
2497                return $string;
2498        }
2499
2500        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
2501        {
2502                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
2503                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2504                        foreach($imapsort as $iuid)
2505                                $sort[$iuid] = "";
2506                       
2507                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2508                                $slice_array = false;
2509                        else
2510                                $slice_array = true;
2511                }
2512                else
2513                {
2514                        $sort = array();
2515                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2516                        $num_msgs = imap_num_msg($this->mbox);
2517                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
2518                        $slice_array = true;
2519
2520                        for ($i=$num_msgs; $i>0; $i--)
2521                        {
2522                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2523                                        break;
2524                                $iuid = @imap_uid($this->mbox,$i);
2525                                $header = $this->get_header($iuid);
2526                                // List UNSEEN messages.
2527                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2528                                        continue;
2529                                }
2530                                // List SEEN messages.
2531                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2532                                        continue;
2533                                }
2534                                // List ANSWERED messages.
2535                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2536                                        continue;
2537                                }
2538                                // List FLAGGED messages.
2539                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2540                                        continue;
2541                                }
2542
2543                                if($sort_box_type=='SORTFROM') {
2544                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
2545                                                $from = $header->to;
2546                                        else
2547                                                $from = $header->from;
2548
2549                                        $tmp = imap_mime_header_decode($from[0]->personal);
2550
2551                                        if ($tmp[0]->text != "")
2552                                                $sort[$iuid] = $tmp[0]->text;
2553                                        else
2554                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2555                                }
2556                                else if($sort_box_type=='SORTSUBJECT') {
2557                                        $sort[$iuid] = $header->subject;
2558                                }
2559                                else if($sort_box_type=='SORTSIZE') {
2560                                        $sort[$iuid] = $header->Size;
2561                                }
2562                                else {
2563                                        $sort[$iuid] = $header->udate;
2564                                }
2565
2566                        }
2567                        natcasesort($sort);
2568
2569                        if ($sort_box_reverse)
2570                                $sort = array_reverse($sort,true);
2571                }
2572
2573                if(!is_array($sort))
2574                        $sort = array();
2575
2576
2577                if ($slice_array)
2578                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
2579
2580
2581                return $sort;
2582
2583        }
2584
2585
2586        function move_search_messages($params){
2587                $params['selected_messages'] = urldecode($params['selected_messages']);
2588                $params['new_folder'] = urldecode($params['new_folder']);
2589                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2590                $sel_msgs = explode(",", $params['selected_messages']);
2591                @reset($sel_msgs);
2592                $sorted_msgs = array();
2593                foreach($sel_msgs as $idx => $sel_msg) {
2594                        $sel_msg = explode(";", $sel_msg);
2595                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2596                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
2597                         }
2598                         else {
2599                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2600                         }
2601                }
2602                @ksort($sorted_msgs);
2603                $last_return = false;
2604                foreach($sorted_msgs as $folder => $msgs_number) {
2605                        $params['msgs_number'] = $msgs_number;
2606                        $params['folder'] = $folder;
2607                        if($params['new_folder'] && $folder != $params['new_folder']){
2608                                $last_return = $this -> move_messages($params);
2609                        }
2610                        elseif(!$params['new_folder'] || $params['delete'] ){
2611                                $last_return = $this -> delete_msgs($params);
2612                                $last_return['deleted'] = true;
2613                        }
2614                }
2615                return $last_return;
2616        }
2617
2618        function move_messages($params)
2619        {
2620                $folder = $params['folder'];
2621                $mbox_stream = $this->open_mbox($folder);
2622                $newmailbox = ($params['new_folder']);
2623                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
2624                $new_folder_name = $params['new_folder_name'];
2625                $msgs_number = $params['msgs_number'];
2626                $return = array('msgs_number' => $msgs_number,
2627                                                'folder' => $folder,
2628                                                'new_folder_name' => $new_folder_name,
2629                                                'border_ID' => $params['border_ID'],
2630                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
2631
2632                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2633        if (substr($folder,0,4) == 'user'){
2634                $acl = $this->getacltouser($folder);
2635                /*
2636                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2637                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2638                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2639                 *   w - write (STORE flags other than SEEN and DELETED)
2640                 *   i - insert (perform APPEND, COPY into mailbox)
2641                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2642                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2643                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2644                 *   a - administer (perform SETACL)
2645                        */
2646                        if (strpos($acl, "d") === false){
2647                                $return['status'] = false;
2648                                return $return;
2649                        }
2650        }
2651        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
2652        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
2653            if (substr($new_folder_name,0,4) == 'user'){
2654                $this->ldap = new ldap_functions();
2655                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
2656                $return['new_folder_name'] = array_pop($tmp_folder_name);
2657                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2658                {
2659                    $return['new_folder_name'] = $cn;
2660                }
2661            }
2662        }
2663
2664                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
2665                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
2666                {
2667                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2668                        // Fix problem in unserialize function JS.
2669                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2670                }
2671
2672                $mbox_stream = $this->open_mbox($folder);
2673                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2674                        imap_expunge($mbox_stream);
2675                        if($mbox_stream)
2676                                imap_close($mbox_stream);
2677                        return $return;
2678                }else {
2679                        if(strstr(imap_last_error(),'Over quota')) {
2680                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
2681                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
2682                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2683                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2684                                $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()))));
2685                                if(!$mbox)
2686                                        return imap_last_error();
2687                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
2688                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
2689                                        if($mbox_stream)
2690                                                imap_close($mbox_stream);
2691                                        if($mbox)
2692                                                imap_close($mbox);
2693                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
2694                                }
2695                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2696                                        imap_expunge($mbox_stream);
2697                                        if($mbox_stream)
2698                                                imap_close($mbox_stream);
2699                                        // return to original quota limit.
2700                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2701                                                if($mbox)
2702                                                        imap_close($mbox);
2703                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2704                                        }
2705                                        return $return;
2706                                }
2707                                else {
2708                                        if($mbox_stream)
2709                                                imap_close($mbox_stream);
2710                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2711                                                if($mbox)
2712                                                        imap_close($mbox);
2713                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2714                                        }
2715                                        return imap_last_error();
2716                                }
2717
2718                        }
2719                        else {
2720                                if($mbox_stream)
2721                                        imap_close($mbox_stream);
2722                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
2723                        }
2724                }
2725        }
2726
2727        function save_msg($params)
2728        {
2729
2730                include_once("class.phpmailer.php");
2731                $mail = new PHPMailer();
2732                include_once("class.db_functions.inc.php");
2733                $toaddress = $params['input_to'];
2734                $ccaddress = $params['input_cc'];
2735                $ccoaddress = $params['input_cco'];
2736                $return_receipt = $params['input_return_receipt'];
2737                $is_important = $params['input_important_message'];
2738                $subject = $params['input_subject'];
2739                $msg_uid = $params['msg_id'];
2740                $body = $params['body'];
2741                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
2742                $body = preg_replace("/\n/"," ",$body);
2743                $body = preg_replace("/\r/","",$body);
2744                $forwarding_attachments = $params['forwarding_attachments'];
2745                $attachments = $params['FILES'];
2746                $return_files = $params['FILES'];
2747
2748                $folder = $params['folder'];
2749                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2750                // Fix problem with cyrus delimiter changes.
2751                // Dots in names: enabled/disabled.
2752                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2753                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2754                // End Fix.
2755                if(strtoupper($folder) == 'INBOX/DRAFTS') $mail->SaveMessageAsDraft = $folder;
2756
2757                $mail->SaveMessageInFolder = $folder;
2758                $mail->SMTPDebug = false;
2759
2760                $mail->IsSMTP();
2761                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2762                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2763                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2764                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2765
2766                $mail->Sender = $mail->From;
2767                $mail->SenderName = $mail->FromName;
2768                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2769                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
2770
2771                $this->add_recipients("to", $toaddress, &$mail);
2772                $this->add_recipients("cc", $ccaddress, &$mail);
2773    $this->add_recipients("cco", $ccoaddress, &$mail);
2774                $mail->AddReplyTo($replytoaddress);
2775                $mail->Subject = $subject;
2776                $mail->IsHTML(true);
2777                $mail->Body = $body;
2778               
2779                // Important message
2780                if($is_important)
2781                        $mail->isImportant();
2782
2783                // Disposition-Notification-To
2784                if ($return_receipt)
2785                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2786
2787                $return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2788
2789        //      Build Forwarding Attachments!!!
2790                if (count($forwarding_attachments) > 0)
2791                {
2792                        foreach($forwarding_attachments as $forwarding_attachment)
2793                        {
2794                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2795                                $tmp = array_values($file_description);
2796                                foreach($file_description as $i => $descriptor){
2797                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2798                                }
2799                                $file_description = $tmp;
2800
2801                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2802                                $fileName = $file_description[2];
2803
2804                                $file_description[5] = strlen($fileContent); //Size of file
2805                                $return_forward[] = $file_description;
2806
2807                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2808                        }
2809                }
2810
2811                if ((count($return_forward) > 0) && (count($return_files) > 0))
2812                        $return_files = array_merge_recursive($return_forward,$return_files);
2813                else
2814                        if (count($return_files) < 1)
2815                                $return_files = $return_forward;
2816
2817                //      Build Uploading Attachments!!!
2818                $sizeof_attachments = count($attachments);
2819                if ($sizeof_attachments)
2820                        foreach ($attachments as $numb => $attach){
2821                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2822                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2823                                        switch ($image_type)
2824                                        {
2825                                        // Do not corrupt animated gif
2826                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
2827                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2828                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2829                                        case 6:
2830                                                require_once("gd_functions.php");
2831                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2832                                        default:
2833                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2834                                                break;
2835                                        }
2836                                        header('Content-type: image/jpeg');
2837                                        $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
2838                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2839                                        if ($width < $max_resolution && $height < $max_resolution){
2840                                                $new_width = $width;
2841                                                $new_height = $height;
2842                                        }
2843                                        else if ($width > $max_resolution){
2844                                                $new_width = $max_resolution;
2845                                                $new_height = $height*($new_width/$width);
2846                                        }
2847                                        else {
2848                                                $new_height = $max_resolution;
2849                                                $new_width = $width*($new_height/$height);
2850                                        }
2851                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2852                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2853                                        $tmpDir = ini_get("session.save_path");
2854                                        $_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
2855                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2856                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2857                                }
2858                                else
2859                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2860                                // optional name
2861                                }
2862
2863
2864
2865
2866                if(!empty($mail->AltBody))
2867            $mail->ContentType = "multipart/alternative";
2868
2869                $mail->error_count = 0; // reset errors
2870                $mail->SetMessageType();
2871                $header = $mail->CreateHeader();
2872                $body = $mail->CreateBody();
2873
2874                $mbox_stream = $this->open_mbox($folder);
2875                $new_header = str_replace("\n", "\r\n", $header);
2876                $new_body = str_replace("\n", "\r\n", $body);
2877                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2878                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2879                $return['msg_no'] = $status->uidnext - 1;
2880                $return['folder_id'] = $folder;
2881
2882                if($mbox_stream)
2883                        imap_close($mbox_stream);
2884                if (is_array($return_files))
2885                        foreach ($return_files as $index => $_attachment) {
2886                                if (array_key_exists("name",$_attachment)){
2887                                unset($return_files[$index]);
2888                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2889                        }
2890                        else
2891                        {
2892                                unset($return_files[$index]);
2893                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2894                        }
2895                }
2896
2897                $return['files'] = serialize($return_files);
2898                $return["subject"] = $subject;
2899
2900                if (!$return['append']) {
2901                        $return['append'] = imap_last_error();
2902                        $return['has_error'] = true;
2903                }
2904
2905                return $return;
2906        }
2907
2908        function set_messages_flag($params)
2909        {
2910                $folder = $params['folder'];
2911                $msgs_to_set = $params['msgs_to_set'];
2912                $flag = $params['flag'];
2913                $return = array();
2914                $return["msgs_to_set"] = $msgs_to_set;
2915                $return["flag"] = $flag;
2916
2917                if(!$this->mbox && !is_resource($this->mbox))
2918                        $this->mbox = $this->open_mbox($folder);
2919
2920                if ($flag == "unseen")
2921                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2922                elseif ($flag == "seen")
2923                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2924                elseif ($flag == "answered"){
2925                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2926                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2927                }
2928                elseif ($flag == "forwarded")
2929                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2930                elseif ($flag == "flagged")
2931                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2932                elseif ($flag == "unflagged") {
2933                        $flag_importance = false;
2934                        $msgs_number = explode(",",$msgs_to_set);
2935                        $unflagged_msgs = "";
2936                        foreach($msgs_number as $msg_number) {
2937                                preg_match('/importance *: *(.*)\r/i',
2938                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2939                                        ,$importance);
2940                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2941                                        $flag_importance=true;
2942                                }
2943                                else {
2944                                        $unflagged_msgs.=$msg_number.",";
2945                                }
2946                        }
2947
2948                        if($unflagged_msgs!="") {
2949                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2950                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2951                        }
2952                        else {
2953                                $return["msgs_unflageds"] = false;
2954                        }
2955
2956                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2957                                $return["status"] = false;
2958                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2959                        }
2960                        else {
2961                                $return["status"] = true;
2962                        }
2963                }
2964
2965                if($this->mbox && is_resource($this->mbox))
2966                        imap_close($this->mbox);
2967                return $return;
2968        }
2969
2970        function get_file_type($file_name)
2971        {
2972                $file_name = strtolower($file_name);
2973                $strFileType = strrev(substr(strrev($file_name),0,4));
2974                if ($strFileType == ".asf")
2975                        return "video/x-ms-asf";
2976                if ($strFileType == ".avi")
2977                        return "video/avi";
2978                if ($strFileType == ".doc")
2979                        return "application/msword";
2980                if ($strFileType == ".zip")
2981                        return "application/zip";
2982                if ($strFileType == ".xls")
2983                        return "application/vnd.ms-excel";
2984                if ($strFileType == ".gif")
2985                        return "image/gif";
2986                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2987                        return "image/jpeg";
2988                if ($strFileType == ".png")
2989                        return "image/png";
2990                if ($strFileType == ".wav")
2991                        return "audio/wav";
2992                if ($strFileType == ".mp3")
2993                        return "audio/mpeg3";
2994                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2995                        return "video/mpeg";
2996                if ($strFileType == ".rtf")
2997                        return "application/rtf";
2998                if ($strFileType == ".htm" || $strFileType == "html")
2999                        return "text/html";
3000                if ($strFileType == ".xml")
3001                        return "text/xml";
3002                if ($strFileType == ".xsl")
3003                        return "text/xsl";
3004                if ($strFileType == ".css")
3005                        return "text/css";
3006                if ($strFileType == ".php")
3007                        return "text/php";
3008                if ($strFileType == ".asp")
3009                        return "text/asp";
3010                if ($strFileType == ".pdf")
3011                        return "application/pdf";
3012                if ($strFileType == ".txt")
3013                        return "text/plain";
3014                if ($strFileType == ".wmv")
3015                        return "video/x-ms-wmv";
3016                if ($strFileType == ".sxc")
3017                        return "application/vnd.sun.xml.calc";
3018                if ($strFileType == ".stc")
3019                        return "application/vnd.sun.xml.calc.template";
3020                if ($strFileType == ".sxd")
3021                        return "application/vnd.sun.xml.draw";
3022                if ($strFileType == ".std")
3023                        return "application/vnd.sun.xml.draw.template";
3024                if ($strFileType == ".sxi")
3025                        return "application/vnd.sun.xml.impress";
3026                if ($strFileType == ".sti")
3027                        return "application/vnd.sun.xml.impress.template";
3028                if ($strFileType == ".sxm")
3029                        return "application/vnd.sun.xml.math";
3030                if ($strFileType == ".sxw")
3031                        return "application/vnd.sun.xml.writer";
3032                if ($strFileType == ".sxq")
3033                        return "application/vnd.sun.xml.writer.global";
3034                if ($strFileType == ".stw")
3035                        return "application/vnd.sun.xml.writer.template";
3036
3037
3038                return "application/octet-stream";
3039        }
3040
3041        function htmlspecialchars_encode($str)
3042        {
3043                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
3044        }
3045        function htmlspecialchars_decode($str)
3046        {
3047                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
3048        }
3049
3050        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
3051        {
3052                if(!$this->mbox || !is_resource($this->mbox))
3053                        $this->mbox = $this->open_mbox($folder);
3054
3055                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
3056        }
3057
3058        function get_info_next_msg($params)
3059        {
3060                $msg_number = $params['msg_number'];
3061                $folder = $params['msg_folder'];
3062                $sort_box_type = $params['sort_box_type'];
3063                $sort_box_reverse = $params['sort_box_reverse'];
3064                $reuse_border = $params['reuse_border'];
3065                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
3066                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
3067
3068                $success = false;
3069                if (is_array($sort_array_msg))
3070                {
3071                        foreach ($sort_array_msg as $i => $value){
3072                                if ($value == $msg_number)
3073                                {
3074                                        $success = true;
3075                                        break;
3076                                }
3077                        }
3078                }
3079
3080                if (! $success || $i >= sizeof($sort_array_msg)-1)
3081                {
3082                        $params['status'] = 'false';
3083                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3084                        return $params;
3085                }
3086
3087                $params = array();
3088                $params['msg_number'] = $sort_array_msg[($i+1)];
3089                $params['msg_folder'] = $folder;
3090
3091                $return = $this->get_info_msg($params);
3092                $return["reuse_border"] = $reuse_border;
3093                return $return;
3094        }
3095
3096        function get_info_previous_msg($params)
3097        {
3098                $msg_number = $params['msgs_number'];
3099                $folder = $params['folder'];
3100                $sort_box_type = $params['sort_box_type'];
3101                $sort_box_reverse = $params['sort_box_reverse'];
3102                $reuse_border = $params['reuse_border'];
3103                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
3104                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
3105
3106                $success = false;
3107                if (is_array($sort_array_msg))
3108                {
3109                        foreach ($sort_array_msg as $i => $value){
3110                                if ($value == $msg_number)
3111                                {
3112                                        $success = true;
3113                                        break;
3114                                }
3115                        }
3116                }
3117                if (! $success || $i == 0)
3118                {
3119                        $params['status'] = 'false';
3120                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3121                        return $params;
3122                }
3123
3124                $params = array();
3125                $params['msg_number'] = $sort_array_msg[($i-1)];
3126                $params['msg_folder'] = $folder;
3127
3128                $return = $this->get_info_msg($params);
3129                $return["reuse_border"] = $reuse_border;
3130                return $return;
3131        }
3132
3133        // This function updates the values: quota, paging and new messages menu.
3134        function get_menu_values($params){
3135                $return_array = array();
3136                $return_array = $this->get_quota($params);
3137
3138                $mbox_stream = $this->open_mbox($params['folder']);
3139                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
3140                if($mbox_stream)
3141                        imap_close($mbox_stream);
3142
3143                return $return_array;
3144        }
3145
3146        function get_quota($params){
3147                // folder_id = user/{uid} for shared folders
3148                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
3149                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
3150                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
3151                }
3152                // folder_id = INBOX for inbox folders
3153                else
3154                        $folder_id = "INBOX";
3155
3156                if(!$this->mbox || !is_resource($this->mbox))
3157                        $this->mbox = $this->open_mbox();
3158
3159                $quota = imap_get_quotaroot($this->mbox, $folder_id);
3160                if($this->mbox && is_resource($this->mbox))
3161                        imap_close($this->mbox);
3162
3163                if (!$quota){
3164                        return array(
3165                                'quota_percent' => 0,
3166                                'quota_used' => 0,
3167                                'quota_limit' =>  0
3168                        );
3169                }
3170
3171                if(count($quota) && $quota['limit']) {
3172                        $quota_limit = $quota['limit'];
3173                        $quota_used  = $quota['usage'];
3174                        if($quota_used >= $quota_limit)
3175                        {
3176                                $quotaPercent = 100;
3177                        }
3178                        else
3179                        {
3180                        $quotaPercent = ($quota_used / $quota_limit)*100;
3181                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
3182                        }
3183                        return array(
3184                                'quota_percent' => floor($quotaPercent),
3185                                'quota_used' => $quota_used,
3186                                'quota_limit' =>  $quota_limit
3187                        );
3188                }
3189                else
3190                        return array();
3191        }
3192
3193        function send_notification($params){
3194                include("../header.inc.php");
3195                require_once("class.phpmailer.php");
3196                $mail = new PHPMailer();
3197
3198                $toaddress = $params['notificationto'];
3199
3200                $subject = lang("Read receipt: %1",$params['subject']);
3201                $body = lang("Your message: %1",$params['subject']) . '<br>';
3202                $body .= lang("Received in: %1",$params['date']) . '<br>';
3203                $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"));
3204                $mail->SMTPDebug = false;
3205                $mail->IsSMTP();
3206                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
3207                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
3208                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3209                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
3210                $mail->AddAddress($toaddress);
3211                $mail->Subject = $this->htmlspecialchars_decode($subject);
3212
3213                $mail->IsHTML(true);
3214                $mail->Body = $body;
3215
3216                if(!$mail->Send()){
3217                        return $mail->ErrorInfo;
3218                }
3219                else
3220                        return true;
3221        }
3222
3223        function empty_folder($params)
3224        {
3225                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
3226                $mbox_stream = $this->open_mbox($folder);
3227                $return = imap_delete($mbox_stream,'1:*');
3228                if($mbox_stream)
3229                        imap_close($mbox_stream, CL_EXPUNGE);
3230                return $return;
3231        }
3232
3233        function search($params)
3234        {
3235                include("class.imap_attachment.inc.php");
3236                $imap_attachment = new imap_attachment();
3237                $criteria = $params['criteria'];
3238                $return = array();
3239                $folders = $this->get_folders_list();
3240
3241                $j = 0;
3242                foreach($folders as $folder)
3243                {
3244                        $mbox_stream = $this->open_mbox($folder);
3245                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
3246
3247                        if ($messages == '')
3248                                continue;
3249
3250                        $i = 0;
3251                        $return[$j] = array();
3252                        $return[$j]['folder_name'] = $folder['name'];
3253
3254                        foreach($messages as $msg_number)
3255                        {
3256                                $header = $this->get_header($msg_number);
3257                                if (!is_object($header))
3258                                        return false;
3259
3260                                $return[$j][$i]['msg_folder']   = $folder['name'];
3261                                $return[$j][$i]['msg_number']   = $msg_number;
3262                                $return[$j][$i]['Recent']               = $header->Recent;
3263                                $return[$j][$i]['Unseen']               = $header->Unseen;
3264                                $return[$j][$i]['Answered']     = $header->Answered;
3265                                $return[$j][$i]['Deleted']              = $header->Deleted;
3266                                $return[$j][$i]['Draft']                = $header->Draft;
3267                                $return[$j][$i]['Flagged']              = $header->Flagged;
3268
3269                                $date_msg = gmdate("d/m/Y",$header->udate);
3270                                if (gmdate("d/m/Y") == $date_msg)
3271                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
3272                                else
3273                                        $return[$j][$i]['udate'] = $date_msg;
3274
3275                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3276                                $return[$j][$i]['fromaddress'] = '';
3277                                foreach ($fromaddress as $tmp)
3278                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
3279
3280                                $from = $header->from;
3281                                $return[$j][$i]['from'] = array();
3282                                $tmp = imap_mime_header_decode($from[0]->personal);
3283                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3284                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
3285                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
3286
3287                                $to = $header->to;
3288                                $return[$j][$i]['to'] = array();
3289                                $tmp = imap_mime_header_decode($to[0]->personal);
3290                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3291                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
3292                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
3293
3294                                $subject = imap_mime_header_decode($header->fetchsubject);
3295                                $return[$j][$i]['subject'] = '';
3296                                foreach ($subject as $tmp)
3297                                        $return[$j][$i]['subject'] .= $tmp->text;
3298
3299                                $return[$j][$i]['Size'] = $header->Size;
3300                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
3301
3302                                $return[$j][$i]['attachment'] = array();
3303                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
3304
3305                                $i++;
3306                        }
3307                        $j++;
3308                        if($mbox_stream)
3309                                imap_close($mbox_stream);
3310                }
3311
3312                return $return;
3313        }
3314
3315
3316        function mobile_search($params)
3317        {
3318                include("class.imap_attachment.inc.php");
3319                $imap_attachment = new imap_attachment();
3320                $criterias = array ("TO","SUBJECT","FROM","CC");
3321                $return = array();
3322                if(!isset($params['folder'])) {
3323                        $folder_params = array("noSharedFolders"=>1);
3324                        if(isset($params['folderType']))
3325                                $folder_params['folderType'] = $params['folderType'];
3326                        $folders = $this->get_folders_list($folder_params);
3327                }
3328                else
3329                        $folders = array(0=>array('folder_id'=>$params['folder']));
3330                $num_msgs = 0;
3331                $max_msgs = $params['max_msgs'] + 1; //get one more because mobile paginate
3332                $return["msgs"] = array();
3333               
3334                //get max_msgs of each folder order by date and later order all messages together and retur only max_msgs msgs
3335                foreach($folders as $id =>$folder)
3336                {
3337                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3338                                foreach($criterias as $criteria_fixed)
3339                                {
3340                                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3341
3342                                        $mbox_stream = $this->open_mbox($folder['folder_id']);
3343
3344                                        $messages = imap_sort($mbox_stream,SORTARRIVAL,1,SE_UID,$_filter);
3345                                       
3346                                        if ($messages == ''){
3347                                                if($mbox_stream)
3348                                                        imap_close($mbox_stream);
3349                                                continue;       
3350                                        }
3351                                       
3352                                        foreach($messages as $msg_number)
3353                                        {
3354                                                $temp = $this->get_info_head_msg($msg_number);
3355                                                if(!$temp)
3356                                                        return false;
3357                                                $temp['msg_folder'] = $folder['folder_id'];
3358                                                $return["msgs"][$num_msgs] = $temp;
3359                                                $num_msgs++;
3360                                        }
3361
3362                                        if($mbox_stream)
3363                                                imap_close($mbox_stream);
3364                                }
3365                        }
3366                }
3367
3368                if(!function_exists("cmp_date")) {
3369                        function cmp_date($obj1, $obj2){
3370                    if($obj1['timestamp'] == $obj2['timestamp']) return 0;
3371                    return ($obj1['timestamp'] < $obj2['timestamp']) ? 1 : -1;
3372                        }
3373                }
3374                usort($return["msgs"], "cmp_date");
3375                $return["has_more_msg"] = (sizeof($return["msgs"]) > $max_msgs);
3376                $return["msgs"] = array_slice($return["msgs"], 0, $max_msgs);
3377               
3378                return $return;
3379        }
3380
3381        function delete_and_show_previous_message($params)
3382        {
3383                $return = $this->get_info_previous_msg($params);
3384
3385                $params_tmp1 = array();
3386                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3387                $params_tmp1['folder'] = $params['msg_folder'];
3388                $return_tmp1 = $this->delete_msg($params_tmp1);
3389
3390                $return['msg_number_deleted'] = $return_tmp1;
3391
3392                return $return;
3393        }
3394
3395
3396        function automatic_trash_cleanness($params)
3397        {
3398                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3399                $criteria =  'BEFORE "'.$before_date.'"';
3400                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
3401                // Free others requests
3402                session_write_close();
3403                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3404                if (is_array($messages)){
3405                        foreach ($messages as $msg_number){
3406                                imap_delete($mbox_stream, $msg_number, FT_UID);
3407                        }
3408                }
3409                if($mbox_stream)
3410                        imap_close($mbox_stream, CL_EXPUNGE);
3411                return $messages;
3412        }
3413//      Fix the search problem with special characters!!!!
3414        function remove_accents($string) {
3415                return strtr($string,
3416                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
3417                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3418        }
3419
3420        function make_search_date($date){
3421
3422            $months = array(
3423                1   => 'jan',
3424                2   => 'feb',
3425                3   => 'mar',
3426                4   => 'apr',
3427                5   => 'may',
3428                6   => 'jun',
3429                7   => 'jul',
3430                8   => 'aug',
3431                9   => 'sep',
3432                10  => 'oct',
3433                11  => 'nov',
3434                12  => 'dec'
3435            );
3436
3437            //TODO: Adaptar a data de acordo com o locale do sistema.
3438            list($day,$month,$year) = explode("/", $date);
3439            $search_date = $day."-".$months[intval($month)]."-".$year;
3440            return $search_date;
3441
3442        }
3443
3444        function search_msg( $params = false )
3445        {
3446                $mbox_stream = "";
3447               
3448                if(strpos($params['condition'],"#")===false)
3449                { //local messages
3450                        $search=false;
3451                }
3452                else
3453                {
3454                        $search = explode(",",$params['condition']);
3455                }
3456               
3457                $params['page'] = $params['page'] * 1;
3458
3459            if( is_array($search) )
3460            {
3461                        $search = array_unique($search); // Remove duplicated folders
3462                        $search_criteria = '';
3463                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
3464                        foreach($search as $tmp)
3465                        {
3466                                $tmp1 = explode("##",$tmp);
3467                                $sum = 0;
3468                                $name_box = $tmp1[0];
3469                                unset($filter);
3470                                foreach($tmp1 as $index => $criteria)
3471                                {
3472                                        if ($index != 0 && strlen($criteria) != 0)
3473                                        {
3474                                                $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
3475                                                $filter .= " ".$filter_array[0];
3476                                                if (strlen($filter_array[1]) != 0)
3477                                                {
3478                                                        if ( trim($filter_array[0]) != 'BEFORE' &&
3479                                                                 trim($filter_array[0]) != 'SINCE' &&
3480                                                                 trim($filter_array[0]) != 'ON')
3481                                                        {
3482                                                            $filter .= '"'.$filter_array[1].'"';
3483                                                        }
3484                                                        else
3485                                                        {
3486                                                                $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3487                                                        }
3488                                                }
3489                                        }
3490                                }
3491                               
3492                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3493                                $filter = $this->remove_accents($filter);
3494
3495                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
3496                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
3497                                {
3498                                        $folder_name = explode($this->imap_delimiter,$name_box);
3499                                        $this->ldap = new ldap_functions();
3500                                       
3501                                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3502                                        {
3503                                                $folder_name[1] = $cn;
3504                                        }
3505                                        $folder_name = implode($this->imap_delimiter,$folder_name);
3506                                }
3507                                else
3508                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3509                               
3510                                if(!is_resource($mbox_stream))
3511                                        $mbox_stream = $this->open_mbox($name_box);
3512                                else
3513                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
3514                               
3515                                if (preg_match("/^.?\bALL\b/", $filter))
3516                                {
3517                                        // Quick Search, note: this ALL isn't the same ALL from imap_search
3518                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3519                                           
3520                                        foreach($all_criterias as $criteria_fixed)
3521                                        {
3522                                                $_filter = $criteria_fixed . substr($filter,4);
3523                                               
3524                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
3525                                               
3526                                                if(is_array($search_criteria))
3527                                                {
3528                                                        foreach($search_criteria as $new_search)
3529                                                        {
3530                                                                $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3531                                                                $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
3532                                                                $elem['uid'] = $new_search;
3533                                                                $retorno[] = $elem;
3534                                                        }
3535                                                }
3536                                        }
3537                                }
3538                                else{
3539                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3540                                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
3541                                        {
3542                                            if((!strpos($filter,"FLAGGED") === false) || (!strpos($filter,"UNFLAGGED") === false))
3543                                            {
3544                                                $num_msgs = imap_num_msg($mbox_stream);
3545                                                $flagged_msgs = array();
3546                                                for ($i=$num_msgs; $i>0; $i--)
3547                                                {
3548                                                        $iuid = @imap_uid($this->mbox,$i);
3549                                                        $header = $this->get_header($iuid);
3550                                                        if(trim($header->Flagged))
3551                                                        {
3552                                                                $flagged_msgs[$i] = $iuid;
3553                                                        }
3554                                                }
3555                                                if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
3556                                                {
3557                                                    $arry_diff = is_array($search_criteria) ? array_diff($flagged_msgs,$search_criteria):$flagged_msgs;
3558                                                    foreach($arry_diff as $msg)
3559                                                    {
3560                                                        $search_criteria[] = $msg;
3561                                                    }
3562                                                }
3563                                                else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
3564                                                {
3565                                                    $search_criteria = array_diff($search_criteria,$flagged_msgs);
3566                                                }
3567                                            }
3568                                        }
3569
3570                                        if( is_array( $search_criteria) )
3571                                        {
3572                                                foreach($search_criteria as $new_search)
3573                                                {
3574                                                        $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3575                                                        $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
3576                                                        $elem['uid'] = $new_search;
3577                                                        $retorno[] = $elem;
3578                                                }
3579                                        }
3580                                }
3581                        }
3582                }
3583               
3584                if($mbox_stream)
3585                {
3586                        imap_close($mbox_stream);
3587            }
3588           
3589            $num_msgs = count($retorno);
3590
3591            /* Comparison functions, descendent is ascendent with parms inverted */
3592            function SORTDATE($a, $b){ return ($a['udate'] < $b['udate']); }
3593            function SORTDATE_REVERSE($b, $a) { return SORTDATE($a,$b); }
3594
3595            function SORTWHO($a, $b) { return (strtoupper($a['from']) > strtoupper($b['from'])); }
3596            function SORTWHO_REVERSE($b, $a) { return SORTWHO($a,$b); }
3597
3598            function SORTSUBJECT($a, $b) { return (strtoupper($a['subject']) > strtoupper($b['subject'])); }
3599            function SORTSUBJECT_REVERSE($b, $a) { return SORTSUBJECT($a,$b); }
3600
3601            function SORTBOX($a, $b) { return ($a['boxname'] > $b['boxname']); }
3602            function SORTBOX_REVERSE($b, $a) { return SORTBOX($a,$b); }
3603
3604            function SORTSIZE($a, $b) { return ($a['size'] > $b['size']); }
3605            function SORTSIZE_REVERSE($b, $a) { return SORTSIZE($a,$b); }
3606
3607            usort( $retorno, $params['sort_type']);
3608            $pageret = array_slice( $retorno, $params['page'] * $this->prefs['max_email_per_page'], $this->prefs['max_email_per_page']);
3609           
3610            $arrayRetorno['num_msgs']   =  $num_msgs;
3611            $arrayRetorno['data']               =  $pageret;
3612            $arrayRetorno['currentTab'] =  $params['current_tab'];
3613
3614                if ($pageret)
3615                {
3616                        return $arrayRetorno;
3617                }
3618                else
3619                {
3620                        return 'none';
3621                }
3622        }
3623
3624        function get_msg_detail($uid_msg,$name_box, $mbox_stream )
3625        {
3626                $header = $this->get_header($uid_msg);
3627                require_once("class.imap_attachment.inc.php");
3628                $imap_attachment = new imap_attachment();
3629                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3630                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3631                $flag = $header->Unseen
3632                        .$header->Recent
3633                        .$header->Flagged
3634                        .$header->Draft
3635                        .$header->Answered
3636                        .$header->Deleted
3637                        .$attachments;
3638
3639
3640                $subject = $this->decode_string($header->fetchsubject);
3641                $from = $header->from[0]->mailbox;
3642                if($header->from[0]->personal != "")
3643                        $from = $header->from[0]->personal;
3644                $ret_msg['from']        = $this->decode_string($from);
3645                $ret_msg['subject']     = $subject;
3646                $ret_msg['udate']       = gmdate("d/m/Y",$header->udate + $this->functions->CalculateDateOffset());
3647                $ret_msg['size']        = $header->Size;
3648                $ret_msg['flag']        = $flag;
3649                return $ret_msg;
3650        }
3651
3652
3653        function size_msg($size){
3654                $var = floor($size/1024);
3655                if($var >= 1){
3656                        return $var." kb";
3657                }else{
3658                        return $size ." b";
3659                }
3660        }
3661       
3662        function ob_array($the_object)
3663        {
3664           $the_array=array();
3665           if(!is_scalar($the_object))
3666           {
3667               foreach($the_object as $id => $object)
3668               {
3669                   if(is_scalar($object))
3670                   {
3671                       $the_array[$id]=$object;
3672                   }
3673                   else
3674                   {
3675                       $the_array[$id]=$this->ob_array($object);
3676                   }
3677               }
3678               return $the_array;
3679           }
3680           else
3681           {
3682               return $the_object;
3683           }
3684        }
3685
3686        function getacl()
3687        {
3688                $this->ldap = new ldap_functions();
3689
3690                $return = array();
3691                $mbox_stream = $this->open_mbox();
3692                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3693
3694                $i = 0;
3695                foreach ($mbox_acl as $user => $acl)
3696                {
3697                        if ($user != $this->username)
3698                        {
3699                                $return[$i]['uid'] = $user;
3700                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3701                        }
3702                        $i++;
3703                }
3704                return $return;
3705        }
3706
3707        function setacl($params)
3708        {
3709                $old_users = $this->getacl();
3710                if (!count($old_users))
3711                        $old_users = array();
3712
3713                $tmp_array = array();
3714                foreach ($old_users as $index => $user_info)
3715                {
3716                        $tmp_array[$index] = $user_info['uid'];
3717                }
3718                $old_users = $tmp_array;
3719
3720                $users = unserialize($params['users']);
3721                if (!count($users))
3722                        $users = array();
3723
3724                //$add_share = array_diff($users, $old_users);
3725                $remove_share = array_diff($old_users, $users);
3726
3727                $mbox_stream = $this->open_mbox();
3728
3729                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3730                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3731
3732                /*if (count($add_share))
3733                {
3734                        foreach ($add_share as $index=>$uid)
3735                        {
3736                        if (is_array($mailboxes_list))
3737                        {
3738                        foreach ($mailboxes_list as $key => $val)
3739                        {
3740                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3741                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3742                        }
3743                        }
3744                        }
3745                }*/
3746
3747                if (count($remove_share))
3748                {
3749                        foreach ($remove_share as $index=>$uid)
3750                        {
3751                        if (is_array($mailboxes_list))
3752                        {
3753                        foreach ($mailboxes_list as $key => $val)
3754                        {
3755                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3756                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3757                        }
3758                        }
3759                        }
3760                }
3761
3762                return true;
3763        }
3764
3765        function getaclfromuser($params)
3766        {
3767                $useracl = $params['user'];
3768
3769                $return = array();
3770                $return[$useracl] = 'false';
3771                $mbox_stream = $this->open_mbox();
3772                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3773
3774                foreach ($mbox_acl as $user => $acl)
3775                {
3776                        if (($user != $this->username) && ($user == $useracl))
3777                        {
3778                                $return[$user] = $acl;
3779                        }
3780                }
3781                return $return;
3782        }
3783
3784        function getacltouser($user)
3785        {
3786                $return = array();
3787                $mbox_stream = $this->open_mbox();
3788                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3789                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3790                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3791                if(substr($user,0,4) != 'user')
3792                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3793                else
3794                  $mbox_acl = imap_getacl($mbox_stream, $user);
3795                return $mbox_acl[$this->username];
3796        }
3797
3798
3799        function setaclfromuser($params)
3800        {
3801                $user = $params['user'];
3802                $acl = $params['acl'];
3803
3804                $mbox_stream = $this->open_mbox();
3805
3806                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3807                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3808
3809                if (is_array($mailboxes_list))
3810                {
3811                        foreach ($mailboxes_list as $key => $val)
3812                        {
3813                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3814                                $folder = str_replace("&-", "&", $folder);
3815                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3816                                {
3817                                        $return = imap_last_error();
3818                                }
3819                        }
3820                }
3821                if (isset($return))
3822                        return $return;
3823                else
3824                        return true;
3825        }
3826
3827        function download_attachment($msg,$msgno)
3828        {
3829                $array_parts_attachments = array();
3830                //$array_parts_attachments['names'] = '';
3831                include_once("class.imap_attachment.inc.php");
3832                $imap_attachment = new imap_attachment();
3833
3834                if (count($msg->fname[$msgno]) > 0)
3835                {
3836                        $i = 0;
3837                        foreach ($msg->fname[$msgno] as $index=>$fname)
3838                        {
3839                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3840                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
3841                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3842                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3843                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3844                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3845                                $i++;
3846                        }
3847                }
3848                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3849                return $array_parts_attachments;
3850        }
3851
3852        function spam($params)
3853        {
3854                $is_spam = $params['spam'];
3855                $folder = $params['folder'];
3856                $mbox_stream = $this->open_mbox($folder);
3857                $msgs_number = explode(',',$params['msgs_number']);
3858
3859                foreach($msgs_number as $msg_number) {
3860                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3861                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3862                        $body = imap_body($mbox_stream, $imap_msg_number);
3863                        $msg = $header . $body;
3864                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3865                        $username = $this->username;
3866                        strtok($email, '@');
3867                        $domain = strtok('@');
3868
3869                        //Encontrar a assinatura do dspam no cabecalho
3870                        $v = explode("\r\n", $header);
3871                        foreach ($v as $linha){
3872                                if (eregi("^Message-ID", $linha)) {
3873                                        $args = explode(" ", $linha);
3874                                        $msg_id = "'$args[1]'";
3875                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
3876                                        $args = explode(" ",$linha);
3877                                        $signature = $args[1];
3878                                }
3879                        }
3880
3881                        // Seleciona qual comando a ser executado
3882                        switch($is_spam){
3883                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
3884                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
3885                        }
3886
3887                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3888                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
3889                        system($cmd);
3890                }
3891                imap_close($mbox_stream);
3892                return false;
3893        }
3894        function get_header($msg_number){
3895                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3896                if (!is_object($header))
3897                        return false;
3898
3899                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3900                        $flag = preg_match('/importance *: *(.*)\r/i',
3901                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3902                                                ,$importance);
3903                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3904                }
3905
3906                return $header;
3907        }
3908
3909//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
3910///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.
3911
3912    function insert_email($source,$folder,$timestamp,$flags){
3913        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3914        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
3915        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3916        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
3917        $imap_options = '/notls/novalidate-cert';
3918        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3919        if(imap_last_error())
3920        {
3921            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3922        }
3923        if($timestamp){
3924            $tempDir = ini_get("session.save_path");
3925            $file = $tempDir."imap_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
3926                $f = fopen($file,"w");
3927                fputs($f,base64_encode($source));
3928            fclose($f);
3929            $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);
3930            $return['command']=exec(escapeshellcmd($command));
3931        }else{
3932            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3933        }
3934        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3935                       
3936        $return['msg_no'] = $status->uidnext - 1;
3937        $return['error'] = imap_last_error();
3938        if(!$return['error'] && $flags != '' ){
3939
3940                  $flags_array=explode(':',$flags);
3941                  //"Answered","Draft","Flagged","Unseen"
3942                  $flags_fixed = "";
3943                  if($flags_array[0] == 'A')
3944                        $flags_fixed.="\\Answered ";
3945                  if($flags_array[1] == 'X')
3946                        $flags_fixed.="\\Draft ";
3947                  if($flags_array[2] == 'F')
3948                        $flags_fixed.="\\Flagged ";
3949                  if($flags_array[3] != 'U')
3950                        $flags_fixed.="\\Seen ";
3951
3952                  imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
3953                }
3954        if($mbox_stream)
3955            imap_close($mbox_stream);
3956        return $return;
3957    }
3958
3959    function show_decript($params){
3960        $source = $params['source'];
3961        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3962        $source = str_replace(" ", "+", $source,$i);
3963
3964        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3965            if(!$source = base64_decode($source,true))
3966                return "error ".$source."Espaços ".$i;
3967
3968        }
3969        else {
3970            if(!$source = base64_decode($source))
3971                return "error ".$source."Espaços ".$i;
3972        }
3973
3974        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3975
3976                $get['msg_number'] = $insert['msg_no'];
3977                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
3978                $return = $this->get_info_msg($get);
3979                $get['msg_number'] = $params['ID'];
3980                $get['msg_folder'] = $params['folder'];
3981                $tmp = $this->get_info_msg($get);
3982                if(!$tmp['status_get_msg_info'])
3983                {
3984                        $return['msg_day']=$tmp['msg_day'];
3985                        $return['msg_hour']=$tmp['msg_hour'];
3986                        $return['fulldate']=$tmp['fulldate'];
3987                        $return['smalldate']=$tmp['smalldate'];
3988                }
3989                else
3990                {
3991                        $return['msg_day']='';
3992                        $return['msg_hour']='';
3993                        $return['fulldate']='';
3994                        $return['smalldate']='';
3995                }
3996        $return['msg_no'] =$insert['msg_no'];
3997        $return['error'] = $insert['error'];
3998        $return['folder'] = $params['folder'];
3999        //$return['acls'] = $insert['acls'];
4000        $return['original_ID'] =  $params['ID'];
4001
4002        return $return;
4003
4004    }
4005
4006//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
4007//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
4008
4009    function treat_base64_from_post($source){
4010            $offset = 0;
4011            do
4012            {
4013                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
4014                    {
4015                            $inicio = strpos($source, "\n\r", $inicio);
4016                            $fim = strpos($source, '--', $inicio);
4017                            if(!$fim)
4018                                    $fim = strpos($source,"\n\r", $inicio);
4019                            $length = $fim-$inicio;
4020                            $parte = substr( $source,$inicio,$length-1);
4021                            $parte = str_replace(" ", "+", $parte);
4022                            $source = substr_replace($source, $parte, $inicio, $length-1);
4023                    }
4024                    if($offset > $inicio)
4025                    $offset=FALSE;
4026                    else
4027                    $offset = $inicio;
4028            }
4029            while($offset);
4030            return $source;
4031    }
4032
4033//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.
4034
4035    function unarchive_mail($params)
4036    {
4037        $dest_folder = $params['folder'];
4038        $sources = explode("#@#@#@",$params['source']);
4039        $timestamps = explode("#@#@#@",$params['timestamp']);
4040        $flags = explode("#@#@#@",$params['flags']);
4041
4042        foreach($sources as $index=>$src)
4043        {
4044            if($src!="")
4045            {
4046                $source = $this->treat_base64_from_post($src);
4047                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]);
4048            }
4049        }
4050       
4051        return $insert;
4052    }
4053
4054    function download_all_local_attachments($params)
4055    {
4056        $source = $params['source'];
4057        $source = $this->treat_base64_from_post($source);
4058        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
4059        $exporteml = new ExportEml();
4060        $params['num_msg']=$insert['msg_no'];
4061        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
4062        return $exporteml->download_all_attachments($params);
4063    }
4064    function get_quota_folders(){
4065
4066            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
4067            include_once("class.imapfp.inc.php");           
4068            $imapfp = new imapfp();
4069
4070            if(!$imapfp->open($this->imap_server,$this->imap_port))
4071                    return $imapfp->get_error();             
4072            if (!$imapfp->login( $this->username,$this->password ))
4073                    return $imapfp->get_error();
4074
4075            $response_array = $imapfp->get_mailboxes_size();
4076            if ($imapfp->error)
4077                    return $imapfp->get_error();
4078
4079            $data = array();
4080            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
4081            $data["quota_root"] = $quota_root;
4082
4083            foreach ($response_array as $idx=>$line) {
4084                    $line2 = str_replace('"', "", $line);
4085                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
4086                    list($folder,$size) = explode(";",$line2);
4087                    $quota_used = str_replace(")","",$size);
4088                    $quotaPercent = (($quota_used / 1024) / $data["quota_root"]["quota_limit"])*100;
4089                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
4090                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
4091                            $folder = $this->functions->getLang("Inbox");
4092                    }
4093                    else
4094                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
4095
4096                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
4097            }
4098            $imapfp->close();
4099            return $data;
4100    } 
4101}
4102?>
Note: See TracBrowser for help on using the repository browser.