source: sandbox/2.3-MailArchiver/expressoMail1_2/inc/class.imap_functions.inc.php @ 6779

Revision 6779, 170.4 KB checked in by rafaelraymundo, 12 years ago (diff)

Ticket #2946 - Liberado Expresso(branch 2.3) integrado ao MailArchiver?.

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