source: branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 4022

Revision 4022, 146.1 KB checked in by roberto.santosjunior, 13 years ago (diff)

Ticket #1751 - Lentidão na abertura da caixa dentro do ExpressoMail?

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