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

Revision 3589, 145.2 KB checked in by eduardoalex, 13 years ago (diff)

Ticket #1407 - Adição de busca, remover msgs e marcar como lida

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2
3include_once("class.functions.inc.php");
4include_once("class.ldap_functions.inc.php");
5include_once("class.exporteml.inc.php");
6
7class imap_functions
8{
9        var $public_functions = array
10        (
11                'get_range_msgs'                                => True,
12                'get_info_msg'                                  => True,
13                'get_info_msgs'                                 => True,
14                'get_folders_list'                              => True,
15                'import_msgs'                                   => True,
16                'msgs_to_archive'                               => True
17        );
18
19        var $ldap;
20        var $mbox;
21        var $imap_port;
22        var $has_cid;
23        var $imap_options = '';
24        var $functions;
25        var $prefs;
26        var $foldersLimit;
27        var $imap_sentfolder;
28
29        function imap_functions (){
30                $this->foldersLimit = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] ?  $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] : 20000; //Limit of folders (mailboxes) user can see
31                $this->username           = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
32                $this->password           = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
33                $this->imap_server        = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
34                $this->imap_port          = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
35                $this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
36                $this->functions          = new functions();
37                $this->imap_sentfolder = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   ? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   : str_replace("*","", $this->functions->getLang("Sent"));
38                $this->has_cid = false;
39                $this->prefs = $_SESSION['phpgw_info']['user']['preferences']['expressoMail'];
40
41
42                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
43                {
44                        $this->imap_options = '/tls/novalidate-cert';
45                }
46                else
47                {
48                        $this->imap_options = '/notls/novalidate-cert';
49                }
50        }
51        // BEGIN of functions.
52        function open_mbox($folder = False,$force_die=true)
53        {
54                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
55                if (is_resource($this->mbox))
56                {
57                     if ($force_die)
58                     {
59                        @imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
60                     }
61                     else
62                        {
63                            @imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder);
64                        }
65                }
66                else
67                    {
68                        if($force_die)
69                        {
70                            $this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
71                        }
72                        else
73                            {
74                                $this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password);
75                            }
76                       
77                    }
78                    return $this->mbox;
79         }
80
81        function parse_error($error){
82                // This error is returned from Imap.
83                if(strstr($error,'Connection refused')) {
84                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
85                }
86                // This error is returned from Postfix.
87                elseif(strstr($error,'message file too big')) {
88                        return str_replace("%1",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'],$this->functions->getLang('The size of this message has exceeded  the limit (%1B).'));
89                }
90                elseif(strstr($error,'virus')) {
91                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
92                }
93                // This condition verifies if SESSION is expired.
94                elseif(!count($_SESSION))
95                        return "nosession";
96
97                return $error;
98        }
99
100        function get_range_msgs2($params)
101        {
102                // Free others requests
103                session_write_close();
104                $folder = $params['folder'];
105                $msg_range_begin = $params['msg_range_begin'];
106                $msg_range_end = $params['msg_range_end'];
107                $sort_box_type = $params['sort_box_type'];
108                $sort_box_reverse = $params['sort_box_reverse'];
109                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
110
111                if(!$this->mbox || !is_resource($this->mbox))
112                        $this->mbox = $this->open_mbox($folder);
113
114                $return = array();
115                // Para enviar o offset entre o timezone definido pelo usuário e GMT
116                $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
117               
118                if(!$search_box_type || $search_box_type=="UNSEEN" || $search_box_type=="SEEN") {
119                        $msgs_info = imap_status($this->mbox,"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder,SA_ALL);
120
121
122                        $return['tot_unseen'] = $search_box_type == "SEEN" ? 0 : $msgs_info->unseen;
123
124                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
125
126                        $num_msgs = ($search_box_type=="UNSEEN") ? $msgs_info->unseen : (($search_box_type=="SEEN") ? ($msgs_info->messages - $msgs_info->unseen) : $msgs_info->messages);
127
128                        $i = 0;
129                        if(is_array($sort_array_msg)){
130                                foreach($sort_array_msg as $msg_number => $value)
131                                {
132                                        $temp = $this->get_info_head_msg($msg_number);
133                                        if(!$temp)
134                                                return false;
135
136                                        $return[$i] = $temp;
137                                        $i++;
138                                }
139                        }
140                        $return['num_msgs'] =  $num_msgs;
141                }
142                else {
143                        $num_msgs = imap_num_msg($this->mbox); 
144                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$num_msgs);
145
146
147                        $return['tot_unseen'] = 0;
148                        $i = 0;         
149
150                        if(is_array($sort_array_msg)){
151                                foreach($sort_array_msg as $msg_number => $value)
152                                {
153                                        $temp = $this->get_info_head_msg($msg_number);
154                                        if(!$temp)
155                                                return false;
156                               
157                                        if($temp['Unseen'] == 'U' || $temp['Recent'] == 'N'){
158                                                $return['tot_unseen']++;
159                                        }
160                               
161                                        if($i <= ($msg_range_end-$msg_range_begin))
162                                                $return[$i] = $temp;
163                                        $i++;
164                                }
165                        }
166                        $return['num_msgs'] = count($sort_array_msg)+($msg_range_begin-1);
167
168                }
169                return $return;
170        }
171
172        function get_info_head_msg($msg_number) {
173                $head_array = array();
174                include_once("class.imap_attachment.inc.php");
175
176                $imap_attachment = new imap_attachment();
177                //if ($this->prefs['use_important_flag'] )
178                //{
179                        /*Como eu preciso do atributo Importance para saber se o email é
180                         * importante ou não, uso abaixo a função imap_fetchheader e busco
181                         * o atributo importance nela. Isso faz com que eu acesse o cabeçalho
182                         * duas vezes e de duas formas diferentes, mas em contrapartida, eu
183                         * não preciso reimplementar o método utilizando o fetchheader.
184                         * Como as mensagens são renderizadas em um número pequeno por vez,
185                         * não parece ter perda considerável de performance.
186                         */
187
188                        $tempHeader = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
189                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
190                //}
191                // Reimplementado código para identificação dos e-mails assinados e cifrados
192                // no método getMessageType(). Mário César Kolling <mario.kolling@serpro.gov.br>
193                $head_array['ContentType'] = $this->getMessageType($msg_number, $tempHeader);
194                $head_array['Importance'] = $flag==0?"Normal":$importance[1];
195
196                $header = $this->get_header($msg_number);
197                if (!is_object($header))
198                        return false;
199                $head_array['Recent'] = $header->Recent;
200                $head_array['Unseen'] = $header->Unseen;
201                if($header->Answered =='A' && $header->Draft == 'X'){
202                        $head_array['Forwarded'] = 'F';
203                }
204                else {
205                        $head_array['Answered'] = $header->Answered;
206                        $head_array['Draft']    = $header->Draft;
207                }
208                $head_array['Deleted'] = $header->Deleted;
209                $head_array['Flagged'] = $header->Flagged;
210                $head_array['msg_number'] = $msg_number;
211                $head_array['udate'] = $header->udate;
212                $head_array['offsetToGMT'] = $this->functions->CalculateDateOffset();
213
214                $msgTimestamp = $header->udate + $head_array['offsetToGMT'];
215                $date_msg = gmdate("d/m/Y",$msgTimestamp);
216//              if (date("d/m/Y") == $date_msg)
217//                      $return['udate'] = $header->udate;
218//              else
219
220                if (date("d/m/Y") == $date_msg) //no dia
221                {
222                        $head_array['smalldate'] = gmdate("H:i",$msgTimestamp);
223                }
224                else
225                {
226                        $head_array['smalldate'] = gmdate("d/m/Y",$msgTimestamp);
227                }
228
229                $from = $header->from;
230                $head_array['from'] = array();
231                $head_array['from']['name'] = ( isset( $from[0]->personal ) ) ? $this->decode_string($from[0]->personal) : NULL;
232                $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
233                if(!$head_array['from']['name'])
234                        $head_array['from']['name'] = $head_array['from']['email'];
235                $to = $header->to;
236                $head_array['to'] = array();
237                $tmp = ( isset( $to[0]->personal ) ) ? imap_mime_header_decode($to[0]->personal) : NULL;
238                $head_array['to']['name'] = ( isset( $tmp[0]->text ) ) ? $this->decode_string($this->decode_string($tmp[0]->text)) : NULL;
239                $head_array['to']['email'] = ( isset( $to[0]->mailbox ) ) ? ( $this->decode_string($to[0]->mailbox) . "@" . ( ( isset( $to[0]->host ) ) ? $to[0]->host : '' ) ) : NULL;
240                if(!$head_array['to']['name'])
241                        $head_array['to']['name'] = $head_array['to']['email'];
242                $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                if($tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas') {
1744                        //error_log('passou', 3,'/tmp/imap_get_list.log');
1745                        //imap_deletemailbox($mbox_stream,imap_utf7_encode("{".$this->imap_server."}".'INBOX/decifradas'));
1746                        continue;
1747                }
1748                $result[$i]['folder_unseen'] = $status->unseen;
1749                                $folder_id = $tmp_folder_id[1];
1750                                $result[$i]['folder_id'] = $folder_id;
1751
1752                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1753                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1754                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1755                                if ($uid2cn && substr($folder_id,0,4) == 'user') {
1756                                        //$this->ldap = new ldap_functions();
1757                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
1758                                                $result[$i]['folder_name'] = $cn;
1759                                        }
1760                                }
1761
1762                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1763                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
1764
1765                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1766                                        $result[$i]['folder_hasChildren'] = 1;
1767                                else
1768                                        $result[$i]['folder_hasChildren'] = 0;
1769
1770                                switch ($tmp_folder_id[1]) {
1771                                        case $inbox:
1772                                        case $sent:
1773                                        case $drafts:
1774                                        case $spam:
1775                                        case $trash:
1776                                                $resultDefault[]=$result[$i];
1777                                                break;
1778                                        default:
1779                                                $resultMine[]=$result[$i];
1780                                }
1781
1782                                $i++;
1783                        }
1784                }
1785
1786                if ( $params && !$params['noQuotaInfo'] ) {
1787                        //Get quota info of current folder
1788                        $current_folder = "INBOX";
1789                        if($params && $params['folder'])
1790                                $current_folder = $params['folder'];
1791                               
1792                        $arr_quota_info = $this->get_quota(array('folder_id' => $current_folder));
1793                } else {
1794                        $arr_quota_info = array();
1795                }
1796               
1797                // Sorting resultMine
1798                foreach ($resultMine as $folder_info)
1799                {
1800                        $array_tmp[] = $folder_info['folder_id'];
1801                }
1802
1803                natcasesort($array_tmp);
1804               
1805                $result2 = array();
1806
1807                foreach ($array_tmp as $key => $folder_id)
1808                {
1809                        $result2[] = $resultMine[$key];
1810                }
1811               
1812                // Sorting resultDefault
1813                foreach ($resultDefault as $key => $folder_id)
1814                {
1815                        switch ($resultDefault[$key]['folder_id']) {
1816                                case $inbox:
1817                                        $resultDefault2[0] = $resultDefault[$key];
1818                                        break;
1819                                case $sent:
1820                                        $resultDefault2[1] = $resultDefault[$key];
1821                                        break;
1822                                case $drafts:
1823                                        $resultDefault2[2] = $resultDefault[$key];
1824                                        break;
1825                                case $spam:
1826                                        $resultDefault2[3] = $resultDefault[$key];
1827                                        break;
1828                                case $trash:
1829                                        $resultDefault2[4] = $resultDefault[$key];
1830                                        break;
1831                        }
1832                }
1833               
1834                if ( $params && $params['folderType'] && $params['folderType'] == 'default' )
1835                        return array_merge($resultDefault2, $arr_quota_info);           
1836
1837                if ( $params && $params['folderType'] && $params['folderType'] == 'personal' )
1838                        return array_merge($result2, $arr_quota_info); 
1839                       
1840                // Merge default folders and personal
1841                        $result2 = array_merge($resultDefault2, $result2);
1842               
1843                return array_merge($result2, $arr_quota_info);
1844        }
1845
1846        function create_mailbox($arr)
1847        {
1848                $namebox        = $arr['newp'];
1849                $mbox_stream = $this->open_mbox();
1850                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1851                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
1852
1853                $result = "Ok";
1854                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
1855                {
1856                        $result = implode("<br />\n", imap_errors());
1857                }
1858
1859                if($mbox_stream)
1860                        imap_close($mbox_stream);
1861
1862                return $result;
1863
1864        }
1865
1866        function create_extra_mailbox($arr)
1867        {
1868                $nameboxs = explode(";",$arr['nw_folders']);
1869                $result = "";
1870                $mbox_stream = $this->open_mbox();
1871                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1872                foreach($nameboxs as $key=>$tmp){
1873                        if($tmp != ""){
1874                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1875                                        $result = implode("<br />\n", imap_errors());
1876                                        if($mbox_stream)
1877                                                imap_close($mbox_stream);
1878                                        return $result;
1879                                }
1880                        }
1881                }
1882                if($mbox_stream)
1883                        imap_close($mbox_stream);
1884                return true;
1885        }
1886
1887        function delete_mailbox($arr)
1888        {
1889                $namebox = $arr['del_past'];
1890                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1891                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
1892                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
1893
1894                $result = "Ok";
1895                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1896                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1897                {
1898                        $result = implode("<br />\n", imap_errors());
1899                }
1900                /*
1901                if($mbox_stream)
1902                        imap_close($mbox_stream);
1903                */
1904                return $result;
1905        }
1906
1907        function ren_mailbox($arr)
1908        {
1909                $namebox = $arr['current'];
1910                $new_box = $arr['rename'];
1911                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1912                $mbox_stream = $this->open_mbox();
1913                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
1914
1915                $result = "Ok";
1916                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1917                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
1918
1919                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1920                {
1921                        $result = imap_errors();
1922                }
1923                if($mbox_stream)
1924                        imap_close($mbox_stream);
1925                return $result;
1926
1927        }
1928
1929        function get_num_msgs($params)
1930        {
1931                $folder = $params['folder'];
1932                if(!$this->mbox || !is_resource($this->mbox)) {
1933                        $this->mbox = $this->open_mbox($folder);
1934                        if(!$this->mbox || !is_resource($this->mbox))
1935                        return imap_last_error();
1936                }
1937                $num_msgs = imap_num_msg($this->mbox);
1938                if($this->mbox && is_resource($this->mbox))
1939                        imap_close($this->mbox);
1940
1941                return $num_msgs;
1942        }
1943
1944        function folder_exists($folder){
1945                $mbox =  $this->open_mbox();
1946                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";           
1947                $list = imap_getmailboxes($mbox,$serverString, $folder);
1948                $return = is_array($list);             
1949                imap_close($mbox);
1950                return $return;
1951        }
1952       
1953        function send_mail($params)
1954        {
1955                include_once("class.phpmailer.php");
1956                $mail = new PHPMailer();
1957                include_once("class.db_functions.inc.php");
1958                $db = new db_functions();
1959                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
1960                ##
1961                # @AUTHOR Rodrigo Souza dos Santos
1962                # @DATE 2008/09/17$fileName
1963                # @BRIEF Checks if the user has permission to send an email with the email address used.
1964                ##
1965                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
1966                {
1967                        $deny = true;
1968                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
1969                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
1970                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
1971
1972                        if ( $deny )
1973                                return "The server denied your request to send a mail, you cannot use this mail address.";
1974                }
1975
1976                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1977                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1978                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1979                $replytoaddress = $params['input_replyto'];
1980                $subject = $params['input_subject'];
1981                $msg_uid = $params['msg_id'];
1982                $return_receipt = $params['input_return_receipt'];
1983                $is_important = $params['input_important_message'];
1984        $encrypt = $params['input_return_cripto'];
1985                $signed = $params['input_return_digital'];
1986
1987                if($params['smime'])
1988        {
1989            $body = $params['smime'];
1990            $mail->SMIME = true;
1991            // A MSG assinada deve ser testada neste ponto.
1992            // Testar o certificado e a integridade da msg....
1993            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1994            $erros_acumulados = '';
1995            $certificado = new certificadoB();
1996            $validade = $certificado->verificar($body);
1997            if(!$validade)
1998            {
1999                foreach($certificado->erros_ssl as $linha_erro)
2000                {
2001                    $erros_acumulados .= $linha_erro;
2002                }
2003            }
2004            else
2005            {
2006                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
2007                if ($certificado->apresentado)
2008                {
2009                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
2010                    if($certificado->dados['CPF'] != $this->username) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
2011                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
2012                }
2013                else
2014                {
2015                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
2016                }
2017            }
2018            if(!$erros_acumulados =='')
2019            {
2020                return $erros_acumulados;
2021            }
2022        }
2023        else
2024        {
2025            $body = $params['body'];
2026            //Compatibilização com Outlook, ao encaminhar a mensagem
2027            $body = mb_ereg_replace('<!--\[','<!-- [',$body);
2028        }
2029                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
2030                $attachments = $params['FILES'];
2031                $forwarding_attachments = $params['forwarding_attachments'];
2032                $local_attachments = $params['local_attachments'];
2033
2034                //Test if must be saved in shared folder and change if necessary
2035                if( $fromaddress[2] == 'y' ){
2036                        //build shared folder path
2037                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
2038                        if( $this->folder_exists($newfolder) ) $folder = $newfolder;
2039                        else $folder =  $params['folder'];                     
2040                } else  {
2041                        $folder = $params['folder'];                   
2042                }
2043               
2044                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2045                $folder_name = $params['folder_name'];
2046                // Fix problem with cyrus delimiter changes.
2047                // Dots in names: enabled/disabled.
2048                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2049                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2050                // End Fix.
2051                if ($folder != 'null'){
2052                        $mail->SaveMessageInFolder = $folder;
2053                }
2054////////////////////////////////////////////////////////////////////////////////////////////////////
2055                $mail->SMTPDebug = false;
2056
2057                if($signed && !$params['smime'])
2058                {
2059            $mail->Mailer = "smime";
2060                        $mail->SignedBody = true;
2061                }
2062                else
2063            $mail->IsSMTP();
2064
2065                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2066                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2067                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2068                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2069                if($fromaddress){
2070                        $mail->Sender = $mail->From;
2071                        $mail->SenderName = $mail->FromName;
2072                        $mail->FromName = $fromaddress[0];
2073                        $mail->From = $fromaddress[1];
2074                }
2075
2076                $this->add_recipients("to", $toaddress, &$mail);
2077                $this->add_recipients("cc", $ccaddress, &$mail);
2078                $this->add_recipients("cco", $ccoaddress, &$mail);
2079                $mail->AddReplyTo($replytoaddress);
2080                $mail->Subject = $subject;
2081                $mail->IsHTML($params['type'] != 'textplain');
2082                $mail->Body = $body;
2083
2084        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
2085                {
2086                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2087            $email = explode(",",$email);
2088            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2089            // Deve ser verificado um numero limite de destinatarios.
2090            // Deve ser verificado se os certificados sao validos.
2091            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2092            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2093            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2094            $erros_acumulados = "";
2095            $aux_mails = array();
2096            $mail_list = array();
2097            if(count($email) > $numero_maximo)
2098            {
2099                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2100                return $erros_acumulados;
2101            }
2102            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2103            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2104            foreach($email as $item)
2105            {
2106                $certificate = $db->get_certificate(strtolower($item));
2107                if(!$certificate)
2108                {
2109                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2110                    return $erros_acumulados;
2111                }
2112
2113                if (array_key_exists("dberr1", $certificate))
2114                {
2115
2116                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2117                    return $erros_acumulados;
2118                                }
2119                if (array_key_exists("dberr2", $certificate))
2120                {
2121                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2122                    //continue;
2123                }
2124                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2125                if (!array_key_exists("certs", $certificate))
2126                {
2127                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2128                    continue;
2129                }
2130            */
2131                include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2132
2133                foreach ($certificate['certs'] as $registro)
2134                {
2135                    $c1 = new certificadoB();
2136                    $c1->certificado($registro['chave_publica']);
2137                    if ($c1->apresentado)
2138                    {
2139                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2140                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2141                        {
2142                            $aux_mails[] = $registro['chave_publica'];
2143                            $mail_list[] = strtolower($item);
2144                        }
2145                        else
2146                        {
2147                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2148                            {
2149                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2150                                    $c1->dados['EXPIRADO'],$c2->revogado);
2151                            }
2152
2153                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2154                            foreach($c2->erros_ssl as $linha)
2155                            {
2156                                $erros_acumulados .=  $linha . chr(0x0A);
2157                            }
2158                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2159                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2160                        }
2161                    }
2162                    else
2163                    {
2164                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2165                    }
2166                }
2167                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2168                                {
2169                                        return $erros_acumulados;
2170                        }
2171            }
2172
2173            $mail->Certs_crypt = $aux_mails;
2174        }
2175                // Build CID images
2176                $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2177
2178                //      Build Uploading Attachments!!!
2179                if (count($attachments)>0) //Caso seja forward normal...
2180                {
2181                        $total_uploaded_size = 0;
2182                        $upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
2183                        foreach ($attachments as $attach)
2184                        {
2185                                if($attach['name']=='Unknown')
2186                                        continue;
2187                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2188                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2189                        }
2190                        if( $total_uploaded_size > $upload_max_filesize){
2191                                return $this->parse_error("message file too big");
2192                        }
2193                }
2194                if(count($local_attachments)>0) { //Caso seja forward de mensagens locais
2195
2196                        $total_uploaded_size = 0;
2197                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
2198                        foreach($local_attachments as $local_attachment) {
2199                                $file_description = unserialize(rawurldecode($local_attachment));
2200                                $tmp = array_values($file_description);
2201                                foreach($file_description as $i => $descriptor){
2202                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2203                                }
2204                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2205                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2206                        }
2207                        if( $total_uploaded_size > $upload_max_filesize)
2208                                return 'false';
2209                }
2210////////////////////////////////////////////////////////////////////////////////////////////////////
2211                //      Build Forwarding Attachments!!!
2212                if (count($forwarding_attachments) > 0)
2213                {
2214                        // Bug fixed for array_search function
2215                        $name_cid_files = array();
2216                        if(count($name_cid_files) > 0) {
2217                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2218                                $name_cid_files[0] = null;
2219                        }
2220
2221                        foreach($forwarding_attachments as $forwarding_attachment)
2222                        {
2223                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2224                                        $tmp = array_values($file_description);
2225                                        foreach($file_description as $i => $descriptor){
2226                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2227                                        }
2228                                        $file_description = $tmp;
2229                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2230                                        $fileName = $file_description[2];
2231                                        if(!array_search(trim($fileName),$name_cid_files)) {
2232                                                $mail->AddStringAttachment($fileContent,html_entity_decode(rawurldecode($fileName)), $file_description[4], $this->get_file_type($file_description[2]));
2233                                }
2234                        }
2235                }
2236
2237////////////////////////////////////////////////////////////////////////////////////////////////////
2238                // Important message
2239                if($is_important)
2240                        $mail->isImportant();
2241
2242////////////////////////////////////////////////////////////////////////////////////////////////////
2243                // Disposition-Notification-To
2244                if ($return_receipt)
2245                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2246////////////////////////////////////////////////////////////////////////////////////////////////////
2247
2248                $sent = $mail->Send();
2249
2250                if(!$sent)
2251                {
2252                        return $this->parse_error($mail->ErrorInfo);
2253                }
2254                else
2255                {
2256            if ($signed && !$params['smime'])
2257                        {
2258                                return $sent;
2259                        }
2260                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
2261                        {
2262                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2263                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
2264                                $now = date("d/m/y H:i:s");
2265                                $addrs = $toaddress.$ccaddress.$ccoaddress;
2266                                $sent = trim($sent);
2267                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2268                        }
2269                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
2270                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
2271                                $contacts = new dynamic_contacts();
2272                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2273                                return array("success" => true, "new_contacts" => $new_contacts);
2274                        }
2275                        return array("success" => true);
2276                }
2277        }
2278        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments)
2279        {
2280                //      Build CID for embedded Images!!!
2281                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2282                $cid_imgs = '';
2283                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2284                $cid_array = array();
2285                foreach($cid_imgs[6] as $j => $val){
2286                        if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2287                        {
2288                                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2289                        }
2290                        $cid = $cid_array[$cid_imgs[4][$j].$val]; 
2291                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2292
2293                        if ($msg_uid != $cid_imgs[4][$j]) // The image is not in the same mail?
2294                        {
2295                                $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2296                                //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
2297                                $fileName = "image_".($j).".jpg";
2298                                $fileCode = "base64";
2299                                $fileType = "image/jpg";
2300                                $file_attached[0] = $cid_imgs[2][$j];
2301                                $file_attached[1] = $cid_imgs[4][$j];
2302                                $file_attached[2] = $fileName;
2303                                $file_attached[3] = $cid_imgs[6][$j];
2304                                $file_attached[4] = 'base64';
2305                                $file_attached[5] = strlen($fileContent); //Size of file
2306                                $return_forward[] = $file_attached;
2307
2308                                $attachment_ = unserialize(rawurldecode($forwarding_attachments[$cid_imgs[6][$j]-2]));
2309                                if ($file_attached[3] == $attachment_[3])
2310                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);     
2311                        }
2312                        else
2313                        {
2314                                $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2315                                $file_description = unserialize(rawurldecode($attach_img));
2316                                if (is_array($file_description))
2317                                        foreach($file_description as $i => $descriptor){                                 
2318                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2319                                        }
2320                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2321                                $fileName = $file_description[2];
2322                                $fileCode = $file_description[4];
2323                                $fileType = $this->get_file_type($file_description[2]);
2324                                unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2325                                if (!empty($file_description))
2326                                {
2327                                        $file_description[5] = strlen($fileContent); //Size of file
2328                                        $return_forward[] = $file_description;
2329                                }
2330                        }
2331                        $tempDir = ini_get("session.save_path");
2332                        $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                       
2333                        $f = fopen($tempDir.'/'.$file,"w");
2334                        fputs($f,$fileContent);
2335                        fclose($f);
2336                        if ($fileContent)
2337                                $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2338                        //else
2339                        //      return "Error loading image attachment content";                                                 
2340
2341                }
2342                return $return_forward;
2343        }
2344        function add_recipients_cert($full_address)
2345        {
2346                $result = "";
2347                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2348                foreach ($parse_address as $val)
2349                {
2350                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2351                        if ($val->mailbox == "INVALID_ADDRESS")
2352                                continue;
2353                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2354                                continue;
2355                        if (empty($val->personal))
2356                                $result .= $val->mailbox."@".$val->host . ",";
2357                        else
2358                                $result .= $val->mailbox."@".$val->host . ",";
2359                }
2360
2361                return substr($result,0,-1);
2362        }
2363
2364        function add_recipients($recipient_type, $full_address, $mail)
2365        {
2366                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2367                foreach ($parse_address as $val)
2368                {
2369                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2370                        if ($val->mailbox == "INVALID_ADDRESS")
2371                                continue;
2372
2373                        if (empty($val->personal))
2374                        {
2375                                switch($recipient_type)
2376                                {
2377                                        case "to":
2378                                                $mail->AddAddress($val->mailbox."@".$val->host);
2379                                                break;
2380                                        case "cc":
2381                                                $mail->AddCC($val->mailbox."@".$val->host);
2382                                                break;
2383                                        case "cco":
2384                                                $mail->AddBCC($val->mailbox."@".$val->host);
2385                                                break;
2386                                }
2387                        }
2388                        else
2389                        {
2390                                switch($recipient_type)
2391                                {
2392                                        case "to":
2393                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2394                                                break;
2395                                        case "cc":
2396                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2397                                                break;
2398                                        case "cco":
2399                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2400                                                break;
2401                                }
2402                        }
2403                }
2404                return true;
2405        }
2406
2407        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2408        {
2409                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
2410                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
2411                if($encoding == 'base64')
2412                        # The function imap_base64 adds a new line
2413                        # at ASCII text, with CRLF line terminators.
2414                        # So is being exchanged for base64_decode.
2415                        #
2416                        #$fileContent = imap_base64($fileContent);
2417                        $fileContent = base64_decode($fileContent);
2418                else if($encoding == 'quoted-printable')
2419                        $fileContent = quoted_printable_decode($fileContent);
2420                return $fileContent;
2421        }
2422
2423        function del_last_caracter($string)
2424        {
2425                $string = substr($string,0,(strlen($string) - 1));
2426                return $string;
2427        }
2428
2429        function del_last_two_caracters($string)
2430        {
2431                $string = substr($string,0,(strlen($string) - 2));
2432                return $string;
2433        }
2434
2435        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
2436        {
2437                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
2438                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2439                        foreach($imapsort as $iuid)
2440                                $sort[$iuid] = "";
2441                       
2442                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2443                                $slice_array = false;
2444                        else
2445                                $slice_array = true;
2446                }
2447                else
2448                {
2449                        $sort = array();
2450                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2451                        $num_msgs = imap_num_msg($this->mbox);
2452                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
2453                        $slice_array = true;
2454
2455                        for ($i=$num_msgs; $i>0; $i--)
2456                        {
2457                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2458                                        break;
2459                                $iuid = @imap_uid($this->mbox,$i);
2460                                $header = $this->get_header($iuid);
2461                                // List UNSEEN messages.
2462                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2463                                        continue;
2464                                }
2465                                // List SEEN messages.
2466                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2467                                        continue;
2468                                }
2469                                // List ANSWERED messages.
2470                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2471                                        continue;
2472                                }
2473                                // List FLAGGED messages.
2474                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2475                                        continue;
2476                                }
2477
2478                                if($sort_box_type=='SORTFROM') {
2479                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
2480                                                $from = $header->to;
2481                                        else
2482                                                $from = $header->from;
2483
2484                                        $tmp = imap_mime_header_decode($from[0]->personal);
2485
2486                                        if ($tmp[0]->text != "")
2487                                                $sort[$iuid] = $tmp[0]->text;
2488                                        else
2489                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2490                                }
2491                                else if($sort_box_type=='SORTSUBJECT') {
2492                                        $sort[$iuid] = $header->subject;
2493                                }
2494                                else if($sort_box_type=='SORTSIZE') {
2495                                        $sort[$iuid] = $header->Size;
2496                                }
2497                                else {
2498                                        $sort[$iuid] = $header->udate;
2499                                }
2500
2501                        }
2502                        natcasesort($sort);
2503
2504                        if ($sort_box_reverse)
2505                                $sort = array_reverse($sort,true);
2506                }
2507
2508                if(!is_array($sort))
2509                        $sort = array();
2510
2511
2512                if ($slice_array)
2513                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
2514
2515
2516                return $sort;
2517
2518        }
2519
2520
2521        function move_search_messages($params){
2522                $params['selected_messages'] = urldecode($params['selected_messages']);
2523                $params['new_folder'] = urldecode($params['new_folder']);
2524                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2525                $sel_msgs = explode(",", $params['selected_messages']);
2526                @reset($sel_msgs);
2527                $sorted_msgs = array();
2528                foreach($sel_msgs as $idx => $sel_msg) {
2529                        $sel_msg = explode(";", $sel_msg);
2530                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2531                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
2532                         }
2533                         else {
2534                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2535                         }
2536                }
2537                @ksort($sorted_msgs);
2538                $last_return = false;
2539                foreach($sorted_msgs as $folder => $msgs_number) {
2540                        $params['msgs_number'] = $msgs_number;
2541                        $params['folder'] = $folder;
2542                        if($params['new_folder'] && $folder != $params['new_folder']){
2543                                $last_return = $this -> move_messages($params);
2544                        }
2545                        elseif(!$params['new_folder'] || $params['delete'] ){
2546                                $last_return = $this -> delete_msgs($params);
2547                                $last_return['deleted'] = true;
2548                        }
2549                }
2550                return $last_return;
2551        }
2552
2553        function move_messages($params)
2554        {
2555                $folder = $params['folder'];
2556                $mbox_stream = $this->open_mbox($folder);
2557                $newmailbox = ($params['new_folder']);
2558                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
2559                $new_folder_name = $params['new_folder_name'];
2560                $msgs_number = $params['msgs_number'];
2561                $return = array('msgs_number' => $msgs_number,
2562                                                'folder' => $folder,
2563                                                'new_folder_name' => $new_folder_name,
2564                                                'border_ID' => $params['border_ID'],
2565                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
2566
2567                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2568        if (substr($folder,0,4) == 'user'){
2569                $acl = $this->getacltouser($folder);
2570                /*
2571                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2572                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2573                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2574                 *   w - write (STORE flags other than SEEN and DELETED)
2575                 *   i - insert (perform APPEND, COPY into mailbox)
2576                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2577                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2578                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2579                 *   a - administer (perform SETACL)
2580                        */
2581                        if (strpos($acl, "d") === false){
2582                                $return['status'] = false;
2583                                return $return;
2584                        }
2585        }
2586        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
2587        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
2588            if (substr($new_folder_name,0,4) == 'user'){
2589                $this->ldap = new ldap_functions();
2590                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
2591                $return['new_folder_name'] = array_pop($tmp_folder_name);
2592                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2593                {
2594                    $return['new_folder_name'] = $cn;
2595                }
2596            }
2597        }
2598
2599                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
2600                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
2601                {
2602                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2603                        // Fix problem in unserialize function JS.
2604                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2605                }
2606
2607                $mbox_stream = $this->open_mbox($folder);
2608                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2609                        imap_expunge($mbox_stream);
2610                        if($mbox_stream)
2611                                imap_close($mbox_stream);
2612                        return $return;
2613                }else {
2614                        if(strstr(imap_last_error(),'Over quota')) {
2615                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
2616                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
2617                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2618                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2619                                $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()))));
2620                                if(!$mbox)
2621                                        return imap_last_error();
2622                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
2623                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
2624                                        if($mbox_stream)
2625                                                imap_close($mbox_stream);
2626                                        if($mbox)
2627                                                imap_close($mbox);
2628                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
2629                                }
2630                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2631                                        imap_expunge($mbox_stream);
2632                                        if($mbox_stream)
2633                                                imap_close($mbox_stream);
2634                                        // return to original quota limit.
2635                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2636                                                if($mbox)
2637                                                        imap_close($mbox);
2638                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2639                                        }
2640                                        return $return;
2641                                }
2642                                else {
2643                                        if($mbox_stream)
2644                                                imap_close($mbox_stream);
2645                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2646                                                if($mbox)
2647                                                        imap_close($mbox);
2648                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2649                                        }
2650                                        return imap_last_error();
2651                                }
2652
2653                        }
2654                        else {
2655                                if($mbox_stream)
2656                                        imap_close($mbox_stream);
2657                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
2658                        }
2659                }
2660        }
2661
2662        function save_msg($params)
2663        {
2664
2665                include_once("class.phpmailer.php");
2666                $mail = new PHPMailer();
2667                include_once("class.db_functions.inc.php");
2668                $toaddress = $params['input_to'];
2669                $ccaddress = $params['input_cc'];
2670                $ccoaddress = $params['input_cco'];
2671                $replytoaddress = $params['input_replyto'];
2672                $subject = $params['input_subject'];
2673                $msg_uid = $params['msg_id'];
2674                $body = $params['body'];
2675                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
2676                $body = preg_replace("/\n/"," ",$body);
2677                $body = preg_replace("/\r/","",$body);
2678                $forwarding_attachments = $params['forwarding_attachments'];
2679                $attachments = $params['FILES'];
2680                $return_files = $params['FILES'];
2681
2682                $folder = $params['folder'];
2683                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2684                // Fix problem with cyrus delimiter changes.
2685                // Dots in names: enabled/disabled.
2686                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2687                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2688                // End Fix.
2689                if(strtoupper($folder) == 'INBOX/DRAFTS')
2690                    {
2691                        $mail->SaveMessageAsDraft = $folder;
2692                    }
2693                $mail->SaveMessageInFolder = $folder;
2694                $mail->SMTPDebug = false;
2695
2696                $mail->IsSMTP();
2697                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2698                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2699                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2700                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2701
2702                $mail->Sender = $mail->From;
2703                $mail->SenderName = $mail->FromName;
2704                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2705                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
2706
2707                $this->add_recipients("to", $toaddress, &$mail);
2708                $this->add_recipients("cc", $ccaddress, &$mail);
2709                $this->add_recipients("cco", $ccoaddress, &$mail);
2710                $mail->AddReplyTo($replytoaddress);
2711                $mail->Subject = $subject;
2712                $mail->IsHTML(true);
2713                $mail->Body = $body;
2714
2715                $return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2716
2717        //      Build Forwarding Attachments!!!
2718                if (count($forwarding_attachments) > 0)
2719                {
2720                        foreach($forwarding_attachments as $forwarding_attachment)
2721                        {
2722                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2723                                $tmp = array_values($file_description);
2724                                foreach($file_description as $i => $descriptor){
2725                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2726                                }
2727                                $file_description = $tmp;
2728
2729                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2730                                $fileName = $file_description[2];
2731
2732                                $file_description[5] = strlen($fileContent); //Size of file
2733                                $return_forward[] = $file_description;
2734
2735                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2736                        }
2737                }
2738
2739                if ((count($return_forward) > 0) && (count($return_files) > 0))
2740                        $return_files = array_merge_recursive($return_forward,$return_files);
2741                else
2742                        if (count($return_files) < 1)
2743                                $return_files = $return_forward;
2744
2745                //      Build Uploading Attachments!!!
2746                $sizeof_attachments = count($attachments);
2747                if ($sizeof_attachments)
2748                        foreach ($attachments as $numb => $attach){
2749                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2750                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2751                                        switch ($image_type)
2752                                        {
2753                                        // Do not corrupt animated gif
2754                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
2755                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2756                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2757                                        case 6:
2758                                                require_once("gd_functions.php");
2759                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2760                                        default:
2761                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2762                                                break;
2763                                        }
2764                                        header('Content-type: image/jpeg');
2765                                        $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
2766                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2767                                        if ($width < $max_resolution && $height < $max_resolution){
2768                                                $new_width = $width;
2769                                                $new_height = $height;
2770                                        }
2771                                        else if ($width > $max_resolution){
2772                                                $new_width = $max_resolution;
2773                                                $new_height = $height*($new_width/$width);
2774                                        }
2775                                        else {
2776                                                $new_height = $max_resolution;
2777                                                $new_width = $width*($new_height/$height);
2778                                        }
2779                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2780                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2781                                        $tmpDir = ini_get("session.save_path");
2782                                        $_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
2783                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2784                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2785                                }
2786                                else
2787                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2788                                // optional name
2789                                }
2790
2791
2792
2793
2794                if(!empty($mail->AltBody))
2795            $mail->ContentType = "multipart/alternative";
2796
2797                $mail->error_count = 0; // reset errors
2798                $mail->SetMessageType();
2799                $header = $mail->CreateHeader();
2800                $body = $mail->CreateBody();
2801
2802                $mbox_stream = $this->open_mbox($folder);
2803                $new_header = str_replace("\n", "\r\n", $header);
2804                $new_body = str_replace("\n", "\r\n", $body);
2805                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2806                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2807                $return['msg_no'] = $status->uidnext - 1;
2808                $return['folder_id'] = $folder;
2809
2810                if($mbox_stream)
2811                        imap_close($mbox_stream);
2812                if (is_array($return_files))
2813                        foreach ($return_files as $index => $_attachment) {
2814                                if (array_key_exists("name",$_attachment)){
2815                                unset($return_files[$index]);
2816                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2817                        }
2818                        else
2819                        {
2820                                unset($return_files[$index]);
2821                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2822                        }
2823                }
2824
2825                $return['files'] = serialize($return_files);
2826                $return["subject"] = $subject;
2827
2828                if (!$return['append']) {
2829                        $return['append'] = imap_last_error();
2830                        $return['has_error'] = true;
2831                }
2832
2833                return $return;
2834        }
2835
2836        function set_messages_flag($params)
2837        {
2838                $folder = $params['folder'];
2839                $msgs_to_set = $params['msgs_to_set'];
2840                $flag = $params['flag'];
2841                $return = array();
2842                $return["msgs_to_set"] = $msgs_to_set;
2843                $return["flag"] = $flag;
2844
2845                if(!$this->mbox && !is_resource($this->mbox))
2846                        $this->mbox = $this->open_mbox($folder);
2847
2848                if ($flag == "unseen")
2849                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2850                elseif ($flag == "seen")
2851                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2852                elseif ($flag == "answered"){
2853                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2854                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2855                }
2856                elseif ($flag == "forwarded")
2857                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2858                elseif ($flag == "flagged")
2859                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2860                elseif ($flag == "unflagged") {
2861                        $flag_importance = false;
2862                        $msgs_number = explode(",",$msgs_to_set);
2863                        $unflagged_msgs = "";
2864                        foreach($msgs_number as $msg_number) {
2865                                preg_match('/importance *: *(.*)\r/i',
2866                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2867                                        ,$importance);
2868                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2869                                        $flag_importance=true;
2870                                }
2871                                else {
2872                                        $unflagged_msgs.=$msg_number.",";
2873                                }
2874                        }
2875
2876                        if($unflagged_msgs!="") {
2877                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2878                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2879                        }
2880                        else {
2881                                $return["msgs_unflageds"] = false;
2882                        }
2883
2884                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2885                                $return["status"] = false;
2886                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2887                        }
2888                        else {
2889                                $return["status"] = true;
2890                        }
2891                }
2892
2893                if($this->mbox && is_resource($this->mbox))
2894                        imap_close($this->mbox);
2895                return $return;
2896        }
2897
2898        function get_file_type($file_name)
2899        {
2900                $file_name = strtolower($file_name);
2901                $strFileType = strrev(substr(strrev($file_name),0,4));
2902                if ($strFileType == ".asf")
2903                        return "video/x-ms-asf";
2904                if ($strFileType == ".avi")
2905                        return "video/avi";
2906                if ($strFileType == ".doc")
2907                        return "application/msword";
2908                if ($strFileType == ".zip")
2909                        return "application/zip";
2910                if ($strFileType == ".xls")
2911                        return "application/vnd.ms-excel";
2912                if ($strFileType == ".gif")
2913                        return "image/gif";
2914                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2915                        return "image/jpeg";
2916                if ($strFileType == ".png")
2917                        return "image/png";
2918                if ($strFileType == ".wav")
2919                        return "audio/wav";
2920                if ($strFileType == ".mp3")
2921                        return "audio/mpeg3";
2922                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2923                        return "video/mpeg";
2924                if ($strFileType == ".rtf")
2925                        return "application/rtf";
2926                if ($strFileType == ".htm" || $strFileType == "html")
2927                        return "text/html";
2928                if ($strFileType == ".xml")
2929                        return "text/xml";
2930                if ($strFileType == ".xsl")
2931                        return "text/xsl";
2932                if ($strFileType == ".css")
2933                        return "text/css";
2934                if ($strFileType == ".php")
2935                        return "text/php";
2936                if ($strFileType == ".asp")
2937                        return "text/asp";
2938                if ($strFileType == ".pdf")
2939                        return "application/pdf";
2940                if ($strFileType == ".txt")
2941                        return "text/plain";
2942                if ($strFileType == ".wmv")
2943                        return "video/x-ms-wmv";
2944                if ($strFileType == ".sxc")
2945                        return "application/vnd.sun.xml.calc";
2946                if ($strFileType == ".stc")
2947                        return "application/vnd.sun.xml.calc.template";
2948                if ($strFileType == ".sxd")
2949                        return "application/vnd.sun.xml.draw";
2950                if ($strFileType == ".std")
2951                        return "application/vnd.sun.xml.draw.template";
2952                if ($strFileType == ".sxi")
2953                        return "application/vnd.sun.xml.impress";
2954                if ($strFileType == ".sti")
2955                        return "application/vnd.sun.xml.impress.template";
2956                if ($strFileType == ".sxm")
2957                        return "application/vnd.sun.xml.math";
2958                if ($strFileType == ".sxw")
2959                        return "application/vnd.sun.xml.writer";
2960                if ($strFileType == ".sxq")
2961                        return "application/vnd.sun.xml.writer.global";
2962                if ($strFileType == ".stw")
2963                        return "application/vnd.sun.xml.writer.template";
2964
2965
2966                return "application/octet-stream";
2967        }
2968
2969        function htmlspecialchars_encode($str)
2970        {
2971                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
2972        }
2973        function htmlspecialchars_decode($str)
2974        {
2975                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
2976        }
2977
2978        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2979        {
2980                if(!$this->mbox || !is_resource($this->mbox))
2981                        $this->mbox = $this->open_mbox($folder);
2982
2983                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2984        }
2985
2986        function get_info_next_msg($params)
2987        {
2988                $msg_number = $params['msg_number'];
2989                $folder = $params['msg_folder'];
2990                $sort_box_type = $params['sort_box_type'];
2991                $sort_box_reverse = $params['sort_box_reverse'];
2992                $reuse_border = $params['reuse_border'];
2993                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2994                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2995
2996                $success = false;
2997                if (is_array($sort_array_msg))
2998                {
2999                        foreach ($sort_array_msg as $i => $value){
3000                                if ($value == $msg_number)
3001                                {
3002                                        $success = true;
3003                                        break;
3004                                }
3005                        }
3006                }
3007
3008                if (! $success || $i >= sizeof($sort_array_msg)-1)
3009                {
3010                        $params['status'] = 'false';
3011                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3012                        return $params;
3013                }
3014
3015                $params = array();
3016                $params['msg_number'] = $sort_array_msg[($i+1)];
3017                $params['msg_folder'] = $folder;
3018
3019                $return = $this->get_info_msg($params);
3020                $return["reuse_border"] = $reuse_border;
3021                return $return;
3022        }
3023
3024        function get_info_previous_msg($params)
3025        {
3026                $msg_number = $params['msgs_number'];
3027                $folder = $params['folder'];
3028                $sort_box_type = $params['sort_box_type'];
3029                $sort_box_reverse = $params['sort_box_reverse'];
3030                $reuse_border = $params['reuse_border'];
3031                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
3032                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
3033
3034                $success = false;
3035                if (is_array($sort_array_msg))
3036                {
3037                        foreach ($sort_array_msg as $i => $value){
3038                                if ($value == $msg_number)
3039                                {
3040                                        $success = true;
3041                                        break;
3042                                }
3043                        }
3044                }
3045                if (! $success || $i == 0)
3046                {
3047                        $params['status'] = 'false';
3048                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3049                        return $params;
3050                }
3051
3052                $params = array();
3053                $params['msg_number'] = $sort_array_msg[($i-1)];
3054                $params['msg_folder'] = $folder;
3055
3056                $return = $this->get_info_msg($params);
3057                $return["reuse_border"] = $reuse_border;
3058                return $return;
3059        }
3060
3061        // This function updates the values: quota, paging and new messages menu.
3062        function get_menu_values($params){
3063                $return_array = array();
3064                $return_array = $this->get_quota($params);
3065
3066                $mbox_stream = $this->open_mbox($params['folder']);
3067                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
3068                if($mbox_stream)
3069                        imap_close($mbox_stream);
3070
3071                return $return_array;
3072        }
3073
3074        function get_quota($params){
3075                // folder_id = user/{uid} for shared folders
3076                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
3077                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
3078                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
3079                }
3080                // folder_id = INBOX for inbox folders
3081                else
3082                        $folder_id = "INBOX";
3083
3084                if(!$this->mbox || !is_resource($this->mbox))
3085                        $this->mbox = $this->open_mbox();
3086
3087                $quota = imap_get_quotaroot($this->mbox, $folder_id);
3088                if($this->mbox && is_resource($this->mbox))
3089                        imap_close($this->mbox);
3090
3091                if (!$quota){
3092                        return array(
3093                                'quota_percent' => 0,
3094                                'quota_used' => 0,
3095                                'quota_limit' =>  0
3096                        );
3097                }
3098
3099                if(count($quota) && $quota['limit']) {
3100                        $quota_limit = $quota['limit'];
3101                        $quota_used  = $quota['usage'];
3102                        if($quota_used >= $quota_limit)
3103                        {
3104                                $quotaPercent = 100;
3105                        }
3106                        else
3107                        {
3108                        $quotaPercent = ($quota_used / $quota_limit)*100;
3109                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
3110                        }
3111                        return array(
3112                                'quota_percent' => floor($quotaPercent),
3113                                'quota_used' => $quota_used,
3114                                'quota_limit' =>  $quota_limit
3115                        );
3116                }
3117                else
3118                        return array();
3119        }
3120
3121        function send_notification($params){
3122                include("../header.inc.php");
3123                require_once("class.phpmailer.php");
3124                $mail = new PHPMailer();
3125
3126                $toaddress = $params['notificationto'];
3127
3128                $subject = lang("Read receipt: %1",$params['subject']);
3129                $body = lang("Your message: %1",$params['subject']) . '<br>';
3130                $body .= lang("Received in: %1",$params['date']) . '<br>';
3131                $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"));
3132                $mail->SMTPDebug = false;
3133                $mail->IsSMTP();
3134                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
3135                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
3136                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3137                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
3138                $mail->AddAddress($toaddress);
3139                $mail->Subject = $this->htmlspecialchars_decode($subject);
3140
3141                $mail->IsHTML(true);
3142                $mail->Body = $body;
3143
3144                if(!$mail->Send()){
3145                        return $mail->ErrorInfo;
3146                }
3147                else
3148                        return true;
3149        }
3150
3151        function empty_folder($params)
3152        {
3153                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
3154                $mbox_stream = $this->open_mbox($folder);
3155                $return = imap_delete($mbox_stream,'1:*');
3156                if($mbox_stream)
3157                        imap_close($mbox_stream, CL_EXPUNGE);
3158                return $return;
3159        }
3160
3161        function search($params)
3162        {
3163                include("class.imap_attachment.inc.php");
3164                $imap_attachment = new imap_attachment();
3165                $criteria = $params['criteria'];
3166                $return = array();
3167                $folders = $this->get_folders_list();
3168
3169                $j = 0;
3170                foreach($folders as $folder)
3171                {
3172                        $mbox_stream = $this->open_mbox($folder);
3173                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
3174
3175                        if ($messages == '')
3176                                continue;
3177
3178                        $i = 0;
3179                        $return[$j] = array();
3180                        $return[$j]['folder_name'] = $folder['name'];
3181
3182                        foreach($messages as $msg_number)
3183                        {
3184                                $header = $this->get_header($msg_number);
3185                                if (!is_object($header))
3186                                        return false;
3187
3188                                $return[$j][$i]['msg_folder']   = $folder['name'];
3189                                $return[$j][$i]['msg_number']   = $msg_number;
3190                                $return[$j][$i]['Recent']               = $header->Recent;
3191                                $return[$j][$i]['Unseen']               = $header->Unseen;
3192                                $return[$j][$i]['Answered']     = $header->Answered;
3193                                $return[$j][$i]['Deleted']              = $header->Deleted;
3194                                $return[$j][$i]['Draft']                = $header->Draft;
3195                                $return[$j][$i]['Flagged']              = $header->Flagged;
3196
3197                                $date_msg = gmdate("d/m/Y",$header->udate);
3198                                if (gmdate("d/m/Y") == $date_msg)
3199                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
3200                                else
3201                                        $return[$j][$i]['udate'] = $date_msg;
3202
3203                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3204                                $return[$j][$i]['fromaddress'] = '';
3205                                foreach ($fromaddress as $tmp)
3206                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
3207
3208                                $from = $header->from;
3209                                $return[$j][$i]['from'] = array();
3210                                $tmp = imap_mime_header_decode($from[0]->personal);
3211                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3212                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
3213                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
3214
3215                                $to = $header->to;
3216                                $return[$j][$i]['to'] = array();
3217                                $tmp = imap_mime_header_decode($to[0]->personal);
3218                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3219                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
3220                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
3221
3222                                $subject = imap_mime_header_decode($header->fetchsubject);
3223                                $return[$j][$i]['subject'] = '';
3224                                foreach ($subject as $tmp)
3225                                        $return[$j][$i]['subject'] .= $tmp->text;
3226
3227                                $return[$j][$i]['Size'] = $header->Size;
3228                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
3229
3230                                $return[$j][$i]['attachment'] = array();
3231                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
3232
3233                                $i++;
3234                        }
3235                        $j++;
3236                        if($mbox_stream)
3237                                imap_close($mbox_stream);
3238                }
3239
3240                return $return;
3241        }
3242       
3243       
3244        function mobile_search($params)
3245        {
3246                include("class.imap_attachment.inc.php");
3247                $imap_attachment = new imap_attachment();
3248                $criterias = array ("TO","SUBJECT","FROM","CC");
3249                $return = array();
3250                if(!isset($params['folder'])) {
3251                        $folder_params = array("noSharedFolders"=>1);
3252                        if(isset($params['folderType']))
3253                                $folder_params['folderType'] = $params['folderType'];
3254                        $folders = $this->get_folders_list($folder_params);
3255                }
3256                else
3257                        $folders = array(0=>array('folder_id'=>$params['folder']));
3258                $num_msgs = 0;
3259                $max_msgs = $params['max_msgs'];
3260                $return["total_msgs"] = 0;
3261                foreach($folders as $id =>$folder)
3262                {
3263                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3264                                foreach($criterias as $criteria_fixed)
3265                    {
3266                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3267                                        $mbox_stream = $this->open_mbox($folder['folder_id']);
3268       
3269                                        $messages = imap_search($mbox_stream, $_filter, SE_UID);
3270                                       
3271                                        if ($messages == ''){
3272                                                if($mbox_stream)
3273                                                        imap_close($mbox_stream);
3274                                                continue;       
3275                                        }
3276                                                                       
3277                                        foreach($messages as $msg_number)
3278                                        {       
3279                                                if($num_msgs>=$max_msgs)
3280                                                        break;                         
3281                                                $temp = $this->get_info_head_msg($msg_number);
3282                                                if(!$temp)
3283                                                        return false;
3284                                                $temp['msg_folder'] = $folder['folder_id'];
3285                                                $return[$num_msgs] = $temp;
3286                                                $num_msgs++;
3287                                               
3288                                        }
3289                                        $return['num_msgs'] = $num_msgs;
3290                                        $return["total_msgs"]+=count($messages);
3291                                        if($mbox_stream)
3292                                                imap_close($mbox_stream);
3293                                        if($num_msgs>=$max_msgs)
3294                                                        continue;
3295                                }
3296                        }                       
3297                }
3298                return $return;
3299        }
3300
3301        function delete_and_show_previous_message($params)
3302        {
3303                $return = $this->get_info_previous_msg($params);
3304
3305                $params_tmp1 = array();
3306                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3307                $params_tmp1['folder'] = $params['msg_folder'];
3308                $return_tmp1 = $this->delete_msg($params_tmp1);
3309
3310                $return['msg_number_deleted'] = $return_tmp1;
3311
3312                return $return;
3313        }
3314
3315
3316        function automatic_trash_cleanness($params)
3317        {
3318                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3319                $criteria =  'BEFORE "'.$before_date.'"';
3320                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
3321                // Free others requests
3322                session_write_close();
3323                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3324                if (is_array($messages)){
3325                        foreach ($messages as $msg_number){
3326                                imap_delete($mbox_stream, $msg_number, FT_UID);
3327                        }
3328                }
3329                if($mbox_stream)
3330                        imap_close($mbox_stream, CL_EXPUNGE);
3331                return $messages;
3332        }
3333//      Fix the search problem with special characters!!!!
3334        function remove_accents($string) {
3335                return strtr($string,
3336                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
3337                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3338        }
3339
3340        function make_search_date($date){
3341
3342            $months = array(
3343                1   => 'jan',
3344                2   => 'feb',
3345                3   => 'mar',
3346                4   => 'apr',
3347                5   => 'may',
3348                6   => 'jun',
3349                7   => 'jul',
3350                8   => 'aug',
3351                9   => 'sep',
3352                10  => 'oct',
3353                11  => 'nov',
3354                12  => 'dec'
3355            );
3356
3357            //TODO: Adaptar a data de acordo com o locale do sistema.
3358            list($day,$month,$year) = explode("/", $date);
3359            $search_date = $day."-".$months[intval($month)]."-".$year;
3360            return $search_date;
3361
3362        }
3363
3364        function search_msg($params = ''){
3365                $retorno = "";
3366                $mbox_stream = "";
3367                if(strpos($params['condition'],"#")===false) { //local messages
3368                        $search=false;
3369                }
3370                else {
3371                        $search = explode(",",$params['condition']);
3372                }
3373
3374                $offsetToGMT = $this->functions->CalculateDateOffset();
3375
3376                if($search){
3377                        $search_criteria = '';
3378                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
3379                        foreach($search as $tmp)
3380                        {
3381                                $tmp1 = explode("##",$tmp);
3382                                $sum = 0;
3383                                $name_box = $tmp1[0];
3384                                unset($filter);
3385                                foreach($tmp1 as $index => $criteria)
3386                                {
3387                                    if ($index != 0 && strlen($criteria) != 0)
3388                                    {
3389                                        $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
3390                                        $filter .= " ".$filter_array[0];
3391                                        if (strlen($filter_array[1]) != 0){
3392                                            if (trim($filter_array[0]) != 'BEFORE' &&
3393                                                trim($filter_array[0]) != 'SINCE' &&
3394                                                trim($filter_array[0]) != 'ON')
3395                                            {
3396                                                // Remove accents from criteria, because method remove accents is broken.
3397                                                $filter .= '"'.strtr($filter_array[1],
3398                                                    "áàâãäéèêëíìîïóòôõöúùûüçÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ",
3399                                                    "aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC").'"';
3400                                            }
3401                                            else {
3402                                                $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3403                                            }
3404                                        }
3405                                    }
3406                                }
3407                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3408
3409                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
3410                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
3411                                {
3412                                        $folder_name = explode($this->imap_delimiter,$name_box);
3413                                        $this->ldap = new ldap_functions();
3414                                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3415                                        {
3416                                                $folder_name[1] = $cn;
3417                                        }
3418                                        $folder_name = implode($this->imap_delimiter,$folder_name);
3419                                }
3420                                else
3421                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3422
3423                                if(!is_resource($mbox_stream))
3424                                        $mbox_stream = $this->open_mbox($name_box);
3425                                else
3426                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
3427
3428                                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search
3429
3430                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3431
3432                                        foreach($all_criterias as $criteria_fixed)
3433                                        {
3434                                                $_filter = $criteria_fixed . substr($filter,4);
3435
3436                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
3437                                                // Testa aqui
3438                                                if($search_criteria) // && count($search_criteria) < $search_result_number)
3439                                                {
3440                                                        foreach($search_criteria as $new_search){
3441                                                                if ($search_result_number != '65536' && $sum == $search_result_number)
3442                                                                {
3443                                                                  return $retorno ? $sum . "=sumResults=" . $retorno : "none";
3444                                                                }
3445
3446                                                                $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");
3447                                                                if(!@strstr($retorno,$m_token))
3448                                                                {
3449                                                                    $retorno .= $m_token;
3450                                                                    $sum++;
3451                                                                }
3452                                                        }
3453                                                }
3454                                        }
3455                                }
3456                                else {
3457                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3458                                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
3459                                        {
3460                                if((!strpos($filter,"FLAGGED") === false) || (!strpos($filter,"UNFLAGGED") === false))
3461                                                {
3462                                        $num_msgs = imap_num_msg($mbox_stream);
3463                                                        $flagged_msgs = array();
3464                                                        for ($i=$num_msgs; $i>0; $i--)
3465                                                        {                                                               
3466                                                                $iuid = @imap_uid($this->mbox,$i);
3467                                                                $header = $this->get_header($iuid);                                                             
3468                                                                if(trim($header->Flagged))
3469                                                                {
3470                                                                        $flagged_msgs[$i] = $iuid;
3471                                                                }
3472                                                        }
3473                                                        if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
3474                                                        {
3475                                                                $arry_diff = array_diff($flagged_msgs,$search_criteria);
3476                                                                foreach($arry_diff as $msg)
3477                                                                {
3478                                                                        $search_criteria[] = $msg;
3479                                                                }
3480                                                        }
3481                                                        else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
3482                                                        {
3483                                                                $search_criteria = array_diff($search_criteria,$flagged_msgs);
3484                                                        }
3485                                                }
3486                                        }       
3487                                        if( is_array( $search_criteria) )
3488                                        {
3489                                                foreach($search_criteria as $new_search)
3490                                                {
3491                                                    if ($search_result_number != '65536' && $sum == $search_result_number)
3492                                                    {
3493                                                        return $retorno ? $sum . "=sumResults=" . $retorno : "none";
3494                                                    }
3495                                                    $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");
3496                                                    $sum++;
3497                                                }
3498                                        }
3499                                }
3500
3501//                                $acumulated_results += $sum;
3502//
3503//                                if ($search_result_number != '65536' && $acumulated_results >= $search_result_number)
3504//                                {
3505//                                    return "many results";
3506//                                }
3507                        }
3508                }
3509                if($mbox_stream)
3510                        imap_close($mbox_stream);
3511
3512                if ($retorno){
3513                    return $retorno;
3514                }
3515                else
3516                {
3517                    return 'none';
3518                }
3519                //return $retorno ? $retorno : "none";
3520        }
3521
3522        function get_msg($uid_msg,$name_box, $mbox_stream )
3523        {
3524                $header = $this->get_header($uid_msg);
3525                include_once("class.imap_attachment.inc.php");
3526                $imap_attachment = new imap_attachment();
3527                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3528                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3529                $flag = $header->Unseen
3530                        .$header->Recent
3531                        .$header->Flagged
3532                        .$header->Draft
3533                        .$header->Answered
3534                        .$header->Deleted
3535                        .$attachments;
3536
3537
3538                $subject = $this->decode_string($header->fetchsubject);
3539                $from = $header->from[0]->mailbox;
3540                if($header->from[0]->personal != "")
3541                        $from = $header->from[0]->personal;
3542                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate + $this->functions->CalculateDateOffset())."--". $this->size_msg($header->Size) ."--". $flag;
3543                return $ret_msg;
3544        }
3545
3546
3547        function size_msg($size){
3548                $var = floor($size/1024);
3549                if($var >= 1){
3550                        return $var." kb";
3551                }else{
3552                        return $size ." b";
3553                }
3554        }
3555       
3556        function ob_array($the_object)
3557        {
3558           $the_array=array();
3559           if(!is_scalar($the_object))
3560           {
3561               foreach($the_object as $id => $object)
3562               {
3563                   if(is_scalar($object))
3564                   {
3565                       $the_array[$id]=$object;
3566                   }
3567                   else
3568                   {
3569                       $the_array[$id]=$this->ob_array($object);
3570                   }
3571               }
3572               return $the_array;
3573           }
3574           else
3575           {
3576               return $the_object;
3577           }
3578        }
3579
3580        function getacl()
3581        {
3582                $this->ldap = new ldap_functions();
3583
3584                $return = array();
3585                $mbox_stream = $this->open_mbox();
3586                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3587
3588                $i = 0;
3589                foreach ($mbox_acl as $user => $acl)
3590                {
3591                        if ($user != $this->username)
3592                        {
3593                                $return[$i]['uid'] = $user;
3594                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3595                        }
3596                        $i++;
3597                }
3598                return $return;
3599        }
3600
3601        function setacl($params)
3602        {
3603                $old_users = $this->getacl();
3604                if (!count($old_users))
3605                        $old_users = array();
3606
3607                $tmp_array = array();
3608                foreach ($old_users as $index => $user_info)
3609                {
3610                        $tmp_array[$index] = $user_info['uid'];
3611                }
3612                $old_users = $tmp_array;
3613
3614                $users = unserialize($params['users']);
3615                if (!count($users))
3616                        $users = array();
3617
3618                //$add_share = array_diff($users, $old_users);
3619                $remove_share = array_diff($old_users, $users);
3620
3621                $mbox_stream = $this->open_mbox();
3622
3623                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3624                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3625
3626                /*if (count($add_share))
3627                {
3628                        foreach ($add_share as $index=>$uid)
3629                        {
3630                        if (is_array($mailboxes_list))
3631                        {
3632                        foreach ($mailboxes_list as $key => $val)
3633                        {
3634                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3635                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3636                        }
3637                        }
3638                        }
3639                }*/
3640
3641                if (count($remove_share))
3642                {
3643                        foreach ($remove_share as $index=>$uid)
3644                        {
3645                        if (is_array($mailboxes_list))
3646                        {
3647                        foreach ($mailboxes_list as $key => $val)
3648                        {
3649                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3650                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3651                        }
3652                        }
3653                        }
3654                }
3655
3656                return true;
3657        }
3658
3659        function getaclfromuser($params)
3660        {
3661                $useracl = $params['user'];
3662
3663                $return = array();
3664                $return[$useracl] = 'false';
3665                $mbox_stream = $this->open_mbox();
3666                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3667
3668                foreach ($mbox_acl as $user => $acl)
3669                {
3670                        if (($user != $this->username) && ($user == $useracl))
3671                        {
3672                                $return[$user] = $acl;
3673                        }
3674                }
3675                return $return;
3676        }
3677
3678        function getacltouser($user)
3679        {
3680                $return = array();
3681                $mbox_stream = $this->open_mbox();
3682                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3683                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3684                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3685                if(substr($user,0,4) != 'user')
3686                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3687                else
3688                  $mbox_acl = imap_getacl($mbox_stream, $user);
3689                return $mbox_acl[$this->username];
3690        }
3691
3692
3693        function setaclfromuser($params)
3694        {
3695                $user = $params['user'];
3696                $acl = $params['acl'];
3697
3698                $mbox_stream = $this->open_mbox();
3699
3700                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3701                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3702
3703                if (is_array($mailboxes_list))
3704                {
3705                        foreach ($mailboxes_list as $key => $val)
3706                        {
3707                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3708                                $folder = str_replace("&-", "&", $folder);
3709                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3710                                {
3711                                        $return = imap_last_error();
3712                                }
3713                        }
3714                }
3715                if (isset($return))
3716                        return $return;
3717                else
3718                        return true;
3719        }
3720
3721        function download_attachment($msg,$msgno)
3722        {
3723                $array_parts_attachments = array();
3724                //$array_parts_attachments['names'] = '';
3725                include_once("class.imap_attachment.inc.php");
3726                $imap_attachment = new imap_attachment();
3727
3728                if (count($msg->fname[$msgno]) > 0)
3729                {
3730                        $i = 0;
3731                        foreach ($msg->fname[$msgno] as $index=>$fname)
3732                        {
3733                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3734                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
3735                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3736                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3737                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3738                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3739                                $i++;
3740                        }
3741                }
3742                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3743                return $array_parts_attachments;
3744        }
3745
3746        function spam($params)
3747        {
3748                $is_spam = $params['spam'];
3749                $folder = $params['folder'];
3750                $mbox_stream = $this->open_mbox($folder);
3751                $msgs_number = explode(',',$params['msgs_number']);
3752
3753                foreach($msgs_number as $msg_number) {
3754                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3755                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3756                        $body = imap_body($mbox_stream, $imap_msg_number);
3757                        $msg = $header . $body;
3758                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3759                        $username = $this->username;
3760                        strtok($email, '@');
3761                        $domain = strtok('@');
3762
3763                        //Encontrar a assinatura do dspam no cabecalho
3764                        $v = explode("\r\n", $header);
3765                        foreach ($v as $linha){
3766                                if (eregi("^Message-ID", $linha)) {
3767                                        $args = explode(" ", $linha);
3768                                        $msg_id = "'$args[1]'";
3769                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
3770                                        $args = explode(" ",$linha);
3771                                        $signature = $args[1];
3772                                }
3773                        }
3774
3775                        // Seleciona qual comando a ser executado
3776                        switch($is_spam){
3777                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
3778                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
3779                        }
3780
3781                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3782                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
3783                        system($cmd);
3784                }
3785                imap_close($mbox_stream);
3786                return false;
3787        }
3788        function get_header($msg_number){
3789                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3790                if (!is_object($header))
3791                        return false;
3792
3793                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3794                        $flag = preg_match('/importance *: *(.*)\r/i',
3795                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3796                                                ,$importance);
3797                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3798                }
3799
3800                return $header;
3801        }
3802
3803//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
3804///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.
3805
3806    function insert_email($source,$folder,$timestamp){
3807        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3808        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
3809        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3810        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
3811        $imap_options = '/notls/novalidate-cert';
3812        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3813        if(imap_last_error())
3814        {
3815            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3816       }
3817        if($timestamp){
3818            $tempDir = ini_get("session.save_path");
3819            $file = $tempDir."imap_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
3820                $f = fopen($file,"w");
3821                fputs($f,base64_encode($source));
3822            fclose($f);
3823            $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);
3824            $return['command']=exec(escapeshellcmd($command));
3825        }else{
3826            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3827        }
3828        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3829        $return['msg_no'] = $status->uidnext - 1;
3830                $return['error'] = imap_last_error();
3831        if($mbox_stream)
3832                        imap_close($mbox_stream);
3833        return $return;
3834
3835    }
3836
3837    function show_decript($params,$dec=0){
3838       
3839        $source = $params['source'];
3840        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3841
3842        if ($dec == 0)
3843        {
3844            $source = str_replace(" ", "+", $source,$i);
3845            if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3846                if(!$source = base64_decode($source,true))
3847                    return "error ".$source."Espaços ".$i;
3848
3849            }
3850            else {
3851                if(!$source = base64_decode($source))
3852                    return "error ".$source."Espaços ".$i;
3853            }
3854        }
3855        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3856
3857                $get['msg_number'] = $insert['msg_no'];
3858                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
3859                $return = $this->get_info_msg($get);
3860                $get['msg_number'] = $params['ID'];
3861                $get['msg_folder'] = $params['folder'];
3862                $tmp = $this->get_info_msg($get);
3863                if(!$tmp['status_get_msg_info'])
3864                {
3865                        $return['msg_day']=$tmp['msg_day'];
3866                        $return['msg_hour']=$tmp['msg_hour'];
3867                        $return['fulldate']=$tmp['fulldate'];
3868                        $return['smalldate']=$tmp['smalldate'];
3869                }
3870                else
3871                {
3872                        $return['msg_day']='';
3873                        $return['msg_hour']='';
3874                        $return['fulldate']='';
3875                        $return['smalldate']='';
3876                }
3877        $return['msg_no'] =$insert['msg_no'];
3878        $return['error'] = $insert['error'];
3879        $return['folder'] = $params['folder'];
3880        //$return['acls'] = $insert['acls'];
3881        $return['original_ID'] =  $params['ID'];
3882
3883        return $return;
3884
3885    }
3886
3887//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
3888//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
3889
3890    function treat_base64_from_post($source){
3891            $offset = 0;
3892            do
3893            {
3894                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
3895                    {
3896                            $inicio = strpos($source, "\n\r", $inicio);
3897                            $fim = strpos($source, '--', $inicio);
3898                            if(!$fim)
3899                                    $fim = strpos($source,"\n\r", $inicio);
3900                            $length = $fim-$inicio;
3901                            $parte = substr( $source,$inicio,$length-1);
3902                            $parte = str_replace(" ", "+", $parte);
3903                            $source = substr_replace($source, $parte, $inicio, $length-1);
3904                    }
3905                    if($offset > $inicio)
3906                    $offset=FALSE;
3907                    else
3908                    $offset = $inicio;
3909            }
3910            while($offset);
3911            return $source;
3912    }
3913
3914//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.
3915
3916    function unarchive_mail($params)
3917    {
3918        $dest_folder = $params['folder'];
3919        $sources = explode("#@#@#@",$params['source']);
3920        $timestamps = explode("#@#@#@",$params['timestamp']);
3921        foreach($sources as $index=>$src) {
3922                        if($src!=""){
3923                                $source = $this->treat_base64_from_post($src);
3924                                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index]);
3925                        }
3926                }
3927        return $insert;
3928    }
3929
3930    function download_all_local_attachments($params)
3931    {
3932        $source = $params['source'];
3933        $source = $this->treat_base64_from_post($source);
3934        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3935        $exporteml = new ExportEml();
3936        $params['num_msg']=$insert['msg_no'];
3937        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
3938        return $exporteml->download_all_attachments($params);
3939    }
3940    function get_quota_folders(){
3941
3942            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
3943            include_once("class.imapfp.inc.php");           
3944            $imapfp = new imapfp();
3945
3946            if(!$imapfp->open($this->imap_server,$this->imap_port))
3947                    return $imapfp->get_error();             
3948            if (!$imapfp->login( $this->username,$this->password ))
3949                    return $imapfp->get_error();
3950
3951            $response_array = $imapfp->get_mailboxes_size();
3952            if ($imapfp->error)
3953                    return $imapfp->get_error();
3954
3955            $data = array();
3956            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
3957            $data["quota_root"] = $quota_root;
3958
3959            foreach ($response_array as $idx=>$line) {
3960                    $line2 = str_replace('"', "", $line);
3961                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
3962                    list($folder,$size) = explode(";",$line2);
3963                    $size = str_replace(")","",$size);
3964                    $quotaPercent = (($size / 1048576) / $data["quota_root"]["quota_limit"])*100;
3965                    if ($size < 1048576 && $size > 1024)
3966                            $quota_used = round($size / 1024, 0).' Kb';
3967                    else if($size > 1024)
3968                            $quota_used = round($size / (1024*1024), 1).' Mb';
3969                    else
3970                            $quota_used = $size." b";
3971                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
3972                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
3973                            $folder = $this->functions->getLang("Inbox");
3974                    }
3975                    else
3976                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
3977
3978                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
3979            }
3980            $imapfp->close();
3981            return $data;
3982    } 
3983}
3984?>
Note: See TracBrowser for help on using the repository browser.