source: trunk/expressoMail1_2/inc/class.imap_functions.inc.php @ 4997

Revision 4997, 159.2 KB checked in by roberto.santosjunior, 13 years ago (diff)

Ticket #1820 - Corrigido problema ao mover mensagens para pastas acentuadas.4982

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