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

Revision 4162, 148.7 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1726 - Contagem de msgs em pasta acentuada sem degradar a performance. r4150

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