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

Revision 3777, 145.4 KB checked in by diegomoreno, 13 years ago (diff)

Ticket #1528 - expressoMail1_2 - Ajuste exibindo corretamente o 'from' quando envio com copia.

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