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

Revision 3761, 144.9 KB checked in by eduardoalex, 13 years ago (diff)

Ticket #1548 - Corrigido exibição de subpastas na arvore de editar pastas do expressoMail

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