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

Revision 4168, 148.8 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1726 - Pré-Visualização de msgs no campo assunto. r4164

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