source: branches/2.3/expressoMail1_2/inc/class.imap_functions.inc.php @ 6474

Revision 6474, 164.1 KB checked in by brunocosta, 12 years ago (diff)

Ticket #2853 - Exibição de cotas de sub pastas IMAP.

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