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

Revision 3571, 144.8 KB checked in by eduardoalex, 13 years ago (diff)

Ticket #1408 - Modificado o layout da tela de enviar email do expresso mini.

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