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

Revision 3798, 145.6 KB checked in by thiagoaos, 13 years ago (diff)

Ticket #1567 - Corrigido edição do rascunho mantendo as opções dos checkbox.

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