source: branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 4150

Revision 4150, 147.5 KB checked in by roberto.santosjunior, 13 years ago (diff)

Ticket #1655 - #1751 - Solução p contagem de msgs em pasta acentuada sem degradar a performance

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