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

Revision 4025, 146.1 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1726 - Ajustes para a correção da lentidão na abertura dos mailboxes, r4014

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