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

Revision 4164, 147.6 KB checked in by roberto.santosjunior, 13 years ago (diff)

Ticket #1805 - Pré-Visualização de mensagem no campo assunto não funciona

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