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

Revision 3790, 145.3 KB checked in by thiagoaos, 13 years ago (diff)

Ticket #1559 - Corrigida listagem de pastas no expresso mini. Pasta rascunho não aparecia.

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