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

Revision 4020, 146.9 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1726 - Correção p lentidão na abertura dos mailboxes, r4014

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