source: branches/2.2.0.1/expressoMail1_2/inc/class.imap_functions.inc.php @ 4050

Revision 4050, 146.0 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1726 - Ajuste para funcionamento da paginação. r4048

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