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

Revision 3770, 144.9 KB checked in by thiagoaos, 13 years ago (diff)

Ticket #1555 - Corrigida a edição do rascunho quando não tem um destinatário.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2
3include_once("class.functions.inc.php");
4include_once("class.ldap_functions.inc.php");
5include_once("class.exporteml.inc.php");
6
7class imap_functions
8{
9        var $public_functions = array
10        (
11                'get_range_msgs'                                => True,
12                'get_info_msg'                                  => True,
13                'get_info_msgs'                                 => True,
14                'get_folders_list'                              => True,
15                'import_msgs'                                   => True,
16                'msgs_to_archive'                               => True
17        );
18
19        var $ldap;
20        var $mbox;
21        var $imap_port;
22        var $has_cid;
23        var $imap_options = '';
24        var $functions;
25        var $prefs;
26        var $foldersLimit;
27        var $imap_sentfolder;
28
29        function imap_functions (){
30                $this->foldersLimit = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] ?  $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] : 20000; //Limit of folders (mailboxes) user can see
31                $this->username           = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
32                $this->password           = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
33                $this->imap_server        = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
34                $this->imap_port          = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
35                $this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
36                $this->functions          = new functions();
37                $this->imap_sentfolder = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   ? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']   : str_replace("*","", $this->functions->getLang("Sent"));
38                $this->has_cid = false;
39                $this->prefs = $_SESSION['phpgw_info']['user']['preferences']['expressoMail'];
40
41
42                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
43                {
44                        $this->imap_options = '/tls/novalidate-cert';
45                }
46                else
47                {
48                        $this->imap_options = '/notls/novalidate-cert';
49                }
50        }
51        // BEGIN of functions.
52        function open_mbox($folder = False,$force_die=true)
53        {
54                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
55                if (is_resource($this->mbox))
56                {
57                     if ($force_die)
58                     {
59                        @imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
60                     }
61                     else
62                        {
63                            @imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder);
64                        }
65                }
66                else
67                    {
68                        if($force_die)
69                        {
70                            $this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
71                        }
72                        else
73                            {
74                                $this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password);
75                            }
76                       
77                    }
78                    return $this->mbox;
79         }
80
81        function parse_error($error){
82                // This error is returned from Imap.
83                if(strstr($error,'Connection refused')) {
84                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
85                }
86                // This error is returned from Postfix.
87                elseif(strstr($error,'message file too big')) {
88                        return str_replace("%1",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'],$this->functions->getLang('The size of this message has exceeded  the limit (%1B).'));
89                }
90                elseif(strstr($error,'virus')) {
91                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
92                }
93                // This condition verifies if SESSION is expired.
94                elseif(!count($_SESSION))
95                        return "nosession";
96
97                return $error;
98        }
99
100        function get_range_msgs2($params)
101        {
102                // Free others requests
103                session_write_close();
104                $folder = $params['folder'];
105                $msg_range_begin = $params['msg_range_begin'];
106                $msg_range_end = $params['msg_range_end'];
107                $sort_box_type = $params['sort_box_type'];
108                $sort_box_reverse = $params['sort_box_reverse'];
109                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
110
111                if(!$this->mbox || !is_resource($this->mbox))
112                        $this->mbox = $this->open_mbox($folder);
113
114                $return = array();
115                // Para enviar o offset entre o timezone definido pelo usuário e GMT
116                $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
117               
118                if(!$search_box_type || $search_box_type=="UNSEEN" || $search_box_type=="SEEN") {
119                        $msgs_info = imap_status($this->mbox,"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder,SA_ALL);
120
121
122                        $return['tot_unseen'] = $search_box_type == "SEEN" ? 0 : $msgs_info->unseen;
123
124                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
125
126                        $num_msgs = ($search_box_type=="UNSEEN") ? $msgs_info->unseen : (($search_box_type=="SEEN") ? ($msgs_info->messages - $msgs_info->unseen) : $msgs_info->messages);
127
128                        $i = 0;
129                        if(is_array($sort_array_msg)){
130                                foreach($sort_array_msg as $msg_number => $value)
131                                {
132                                        $temp = $this->get_info_head_msg($msg_number);
133                                        if(!$temp)
134                                                return false;
135
136                                        $return[$i] = $temp;
137                                        $i++;
138                                }
139                        }
140                        $return['num_msgs'] =  $num_msgs;
141                }
142                else {
143                        $num_msgs = imap_num_msg($this->mbox); 
144                        $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$num_msgs);
145
146
147                        $return['tot_unseen'] = 0;
148                        $i = 0;         
149
150                        if(is_array($sort_array_msg)){
151                                foreach($sort_array_msg as $msg_number => $value)
152                                {
153                                        $temp = $this->get_info_head_msg($msg_number);
154                                        if(!$temp)
155                                                return false;
156                               
157                                        if($temp['Unseen'] == 'U' || $temp['Recent'] == 'N'){
158                                                $return['tot_unseen']++;
159                                        }
160                               
161                                        if($i <= ($msg_range_end-$msg_range_begin))
162                                                $return[$i] = $temp;
163                                        $i++;
164                                }
165                        }
166                        $return['num_msgs'] = count($sort_array_msg)+($msg_range_begin-1);
167
168                }
169                return $return;
170        }
171
172        function get_info_head_msg($msg_number) {
173                $head_array = array();
174                include_once("class.imap_attachment.inc.php");
175
176                $imap_attachment = new imap_attachment();
177                //if ($this->prefs['use_important_flag'] )
178                //{
179                        /*Como eu preciso do atributo Importance para saber se o email é
180                         * importante ou não, uso abaixo a função imap_fetchheader e busco
181                         * o atributo importance nela. Isso faz com que eu acesse o cabeçalho
182                         * duas vezes e de duas formas diferentes, mas em contrapartida, eu
183                         * não preciso reimplementar o método utilizando o fetchheader.
184                         * Como as mensagens são renderizadas em um número pequeno por vez,
185                         * não parece ter perda considerável de performance.
186                         */
187
188                        $tempHeader = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
189                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
190                //}
191                // Reimplementado código para identificação dos e-mails assinados e cifrados
192                // no método getMessageType(). Mário César Kolling <mario.kolling@serpro.gov.br>
193                $head_array['ContentType'] = $this->getMessageType($msg_number, $tempHeader);
194                $head_array['Importance'] = $flag==0?"Normal":$importance[1];
195
196                $header = $this->get_header($msg_number);
197                if (!is_object($header))
198                        return false;
199                $head_array['Recent'] = $header->Recent;
200                $head_array['Unseen'] = $header->Unseen;
201                if($header->Answered =='A' && $header->Draft == 'X'){
202                        $head_array['Forwarded'] = 'F';
203                }
204                else {
205                        $head_array['Answered'] = $header->Answered;
206                        $head_array['Draft']    = $header->Draft;
207                }
208                $head_array['Deleted'] = $header->Deleted;
209                $head_array['Flagged'] = $header->Flagged;
210                $head_array['msg_number'] = $msg_number;
211                $head_array['udate'] = $header->udate;
212                $head_array['offsetToGMT'] = $this->functions->CalculateDateOffset();
213
214                $msgTimestamp = $header->udate + $head_array['offsetToGMT'];
215                $date_msg = gmdate("d/m/Y",$msgTimestamp);
216//              if (date("d/m/Y") == $date_msg)
217//                      $return['udate'] = $header->udate;
218//              else
219
220                if (date("d/m/Y") == $date_msg) //no dia
221                {
222                        $head_array['smalldate'] = gmdate("H:i",$msgTimestamp);
223                }
224                else
225                {
226                        $head_array['smalldate'] = gmdate("d/m/Y",$msgTimestamp);
227                }
228
229                $from = $header->from;
230                $head_array['from'] = array();
231                $head_array['from']['name'] = ( isset( $from[0]->personal ) ) ? $this->decode_string($from[0]->personal) : NULL;
232                $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
233                if(!$head_array['from']['name'])
234                        $head_array['from']['name'] = $head_array['from']['email'];
235                $to = $header->to;
236                $head_array['to'] = array();
237                $tmp = ( isset( $to[0]->personal ) ) ? imap_mime_header_decode($to[0]->personal) : NULL;
238                $head_array['to']['name'] = ( isset( $tmp[0]->text ) ) ? $this->decode_string($this->decode_string($tmp[0]->text)) : $head_array['from']['name'];//NULL;
239                $head_array['to']['email'] = ( isset( $to[0]->mailbox ) ) ? ( $this->decode_string($to[0]->mailbox) . "@" . ( ( isset( $to[0]->host ) ) ? $to[0]->host : '' ) ) : $head_array['from']['email']; //NULL;
240                if(!$head_array['to']['name'])
241                        $head_array['to']['name'] = $head_array['to']['email'];
242                $head_array['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
243
244                $head_array['Size'] = $header->Size;
245
246                $head_array['attachment'] = array();
247                $head_array['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
248
249                return $head_array;
250        }
251
252        function decode_string($string)
253        {
254
255                if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
256                {
257                        $return = '';
258                        $tmp = imap_mime_header_decode($string);
259                        foreach ($tmp as $tmp1)
260                                $return .= $this->htmlspecialchars_encode($tmp1->text);
261
262                        $return = str_replace("\t", "", $return);
263                        return $return;
264                }
265                else if (strpos(strtolower($string), '=?utf-8') !== false)
266                {
267                        $elements = imap_mime_header_decode($string);
268
269                        for($i = 0;$i < count($elements);$i++)
270                        {
271                                $charset = strtolower($elements[$i]->charset);
272                                $text = $elements[$i]->text;
273
274                                if(!strcasecmp($charset, "utf-8") || !strcasecmp($charset, "utf-7"))
275                                {
276                                $decoded .= $this->functions->utf8_to_ncr($text);
277                        }
278                                else
279                                {
280                                        if( strcasecmp($charset,"default") )
281                                                $decoded .= $this->htmlspecialchars_encode(iconv($charset, "iso-8859-1", $text));
282                                        else
283                                                $decoded .= $this->htmlspecialchars_encode($text);
284                                }
285                        }
286                        return $decoded;
287                }
288                else
289                        return $this->htmlspecialchars_encode($string);
290        }
291        /**
292        * Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
293        * com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
294        */
295        function import_msgs($params) {
296                if(!$this->mbox)
297                        $this->mbox = $this->open_mbox();
298
299                if( preg_match('/local_/',$params["folder"]) )
300                {
301                        // PLEASE, BE CAREFULL!!! YOU SHOULD USE EMAIL CONFIGURATION VALUES (EMAILADMIN MODULE)
302                        $tmp_box = mb_convert_encoding('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'].$this->imap_delimiter.'tmpMoveToLocal', "UTF7-IMAP", "UTF-8");
303                        if ( ! imap_createmailbox( $this -> mbox,"{".$this -> imap_server."}$tmp_box" ) )
304                                return $this->functions->getLang( 'Import to Local : fail...' );
305                        imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$tmp_box);
306                        $params["folder"] = $tmp_box;
307                }
308                $errors = array();
309                $invalid_format = false;
310                $filename = $params['FILES'][0]['name'];
311                $params["folder"] = mb_convert_encoding($params["folder"], "UTF7-IMAP","ISO_8859-1");
312                $quota = imap_get_quotaroot($this->mbox, $params["folder"]);
313                if((($quota['limit'] - $quota['usage'])*1024) <= $params['FILES'][0]['size']){
314                        return array( 'error' => $this->functions->getLang("fail in import:").
315                                                        " ".$this->functions->getLang("Over quota"));
316                }
317                if(substr($filename,strlen($filename)-4)==".zip") {
318                        $zip = zip_open($params['FILES'][0]['tmp_name']);
319
320                        if ($zip) {
321                                while ($zip_entry = zip_read($zip)) {
322
323                                        if (zip_entry_open($zip, $zip_entry, "r")) {
324                                                $email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
325                                                $status = @imap_append($this->mbox,
326                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
327                                                                        $email
328                                                                        );
329                                                if(!$status)
330                                                        array_push($errors,zip_entry_name($zip_entry));
331                                                zip_entry_close($zip_entry);
332                                        }
333                                }
334                                zip_close($zip);
335                        }
336
337                        if ( isset( $tmp_box ) && ! sizeof( $errors ) )
338                        {
339
340                                $mc = imap_check($this->mbox);
341
342                                $result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 );
343
344                                $ids = array( );
345                                foreach ($result as $overview)
346                                        $ids[ ] = $overview -> uid;
347
348                                return implode( ',', $ids );
349                        }
350                        }
351                else if(substr($filename,strlen($filename)-4)==".eml") {
352                        $email = implode("",file($params['FILES'][0]['tmp_name']));
353                        $status = @imap_append($this->mbox,
354                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
355                                                                        $email
356                                                                        );
357                        if(!$status){
358                                array_push($errors,zip_entry_name($zip_entry));
359                                zip_entry_close($zip_entry);
360                        }
361                }
362                else
363                {
364                        if ( isset( $tmp_box ) )
365                                imap_deletemailbox( $this->mbox,"{".$this -> imap_server."}$tmp_box" );
366
367                        return array("error" => $this->functions->getLang("wrong file format"));
368                        $invalid_format = true;
369                }
370
371                if(!$invalid_format) {
372                        if(count($errors)>0) {
373                                $message = $this->functions->getLang("fail in import:")."\n";
374                                foreach($errors as $arquivo) {
375                                        $message.=$arquivo."\n";
376                                }
377                                return array("error" => $message);
378                        }
379                        else
380                                return ("The import was executed successfully.");
381                }
382        }
383        /*
384                Remove os anexos de uma mensagem. A estratégia para isso é criar uma mensagem nova sem os anexos, mantendo apenas
385                a primeira parte do e-mail, que é o texto, sem anexos.
386                O método considera que o email é multpart.
387        */
388        function remove_attachments($params) {
389                include_once("class.message_components.inc.php");
390                if(!$this->mbox || !is_resource($this->mbox))
391                        $this->mbox = $this->open_mbox($params["folder"]);
392                $return["status"] = true;
393                $header = "";
394
395                $headertemp = explode("\n",imap_fetchheader($this->mbox, imap_msgno($this->mbox, $params["msg_num"])));
396                foreach($headertemp as $head) {//Se eu colocar todo o header do email dá pau no append, então procuro apenas o que interessa.
397                        $head1 = explode(":",$head);
398                        if ( (strtoupper($head1[0]) == "TO") ||
399                                        (strtoupper($head1[0]) == "FROM") ||
400                                        (strtoupper($head1[0]) == "SUBJECT") ||
401                                        (strtoupper($head1[0]) == "DATE") )
402                                $header .= $head."\r\n";
403                }
404
405                $msg = &new message_components($this->mbox);
406                $msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
407                                                             Então uso essa classe para verificar a codificação e o charset,
408                                                             para que o método decodeBody do expresso possa trazer tudo certinho*/
409
410                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][0]);
411                $all_body_encoding = $msg->encoding[$params["msg_num"]][0];
412                $all_body_charset = $msg->charset[$params["msg_num"]][0];
413               
414                if($all_body_type=='multipart/alternative') {
415                        if(strtolower($msg->file_type[$params["msg_num"]][2]=='text/html') &&
416                                        $msg->pid[$params["msg_num"]][2] == '1.2') {
417                                $body_part_to_show = '1.2';
418                                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][2]);
419                                $all_body_encoding = $msg->encoding[$params["msg_num"]][2];
420                                $all_body_charset = $msg->charset[$params["msg_num"]][2];
421                        }
422                        else {
423                                $body_part_to_show = '1.1';
424                                $all_body_type = strtolower($msg->file_type[$params["msg_num"]][1]);
425                                $all_body_encoding = $msg->encoding[$params["msg_num"]][1];
426                                $all_body_charset = $msg->charset[$params["msg_num"]][1];
427                        }
428                }
429                else
430                        $body_part_to_show = '1';
431
432                $status = imap_append($this->mbox,
433                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
434                                        $header.
435                                        "Content-Type: ".$all_body_type."; charset = \"".$all_body_charset."\"".
436                                        "\r\n".
437                                        "Content-Transfer-Encoding: ".$all_body_encoding.
438                                        "\r\n".
439                                        "\r\n".
440                                        str_replace("\n","\r\n",$this->decodeBody(
441                                                        imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),$body_part_to_show),
442                                                        $all_body_encoding, $all_body_charset
443                                                        )
444                                        ), "\\Seen"); //Append do novo email, só com header e conteúdo sem anexos.
445
446                if(!$status)
447                {
448                        $return["status"] = false;
449                        $return["msg"] = lang("error appending mail on delete attachments");
450                }
451                else
452                {
453                        $status = imap_status($this->mbox, "{".$this->imap_server.":".$this->imap_port."}".$params['folder'], SA_UIDNEXT);
454                        $return['msg_no'] = $status->uidnext - 1;
455                        imap_delete($this->mbox, imap_msgno($this->mbox, $params["msg_num"]));
456                        imap_expunge($this->mbox);
457                }
458
459                return $return;
460
461        }
462       
463        function msgs_to_archive($params) {
464               
465                $folder = $params['folder'];
466                $all_ids = $this-> get_msgs($folder, 'SORTARRIVAL', false, 0,-1,-1);
467
468                $messages_not_to_copy = explode(",",$params['mails']);
469                $ids = array();
470               
471                $cont = 0;
472               
473                foreach($all_ids as $each_id=>$value) {
474                        if(!in_array($each_id,$messages_not_to_copy)) {
475                                array_push($ids,$each_id);
476                                $cont++;
477                        }
478                        if($cont>=100)
479                                break;
480                }
481
482                if (empty($ids))
483                        return array();
484
485                $params = array("folder"=>$folder,"msgs_number"=>implode(",",$ids));
486               
487               
488                return $this->get_info_msgs($params);
489               
490               
491        }
492
493/**
494         *
495         * @return
496         * @param $params Object
497         */
498        function get_info_msgs($params) {
499                include_once("class.exporteml.inc.php");
500                $return = array();
501                $new_params = array();
502                $attach_params = array();
503                $new_params["msg_folder"]=$params["folder"];
504                $attach_params["folder"] = $params["folder"];
505                $msgs = explode(",",$params["msgs_number"]);
506                $exporteml = new ExportEml();
507                $unseen_msgs = array();
508                foreach($msgs as $msg_number) {
509                        $new_params["msg_number"] = $msg_number;
510                        //ini_set("display_errors","1");
511                        $msg_info = $this->get_info_msg($new_params);
512
513                        $this->mbox = $this->open_mbox($params['folder']); //Não sei porque, mas se não abrir de novo a caixa dá erro.
514                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
515
516                        $attach_params["num_msg"] = $msg_number;
517                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
518                        $msg_info['url_export_file'] = $exporteml->export_to_archive($msg_number,$params["folder"]);
519                        imap_close($this->mbox);
520                        $this->mbox=false;
521                        array_push($return,serialize($msg_info));
522
523                        if($msg_info['Unseen'] == "U" || $msg_info['Recent'] == "N"){
524                                        array_push($unseen_msgs,$msg_number);
525                        }
526                }
527                if($unseen_msgs){
528                        $msgs_list = implode(",",$unseen_msgs);
529                        $array_msgs = array('folder' => $new_params["msg_folder"], "msgs_to_set" => $msgs_list, "flag" => "unseen");
530                        $this->set_messages_flag($array_msgs);
531                }
532
533                return $return;
534        }
535
536        function get_info_msg($params)
537        {
538                $return = array();
539                $msg_number = $params['msg_number'];
540                if(@preg_match('(.+)(_[a-zA-Z0-9]+)',$msg_number,$matches)) { //Verifies if it comes from a tab diferent of the main one.
541                        $msg_number = $matches[1];
542                        $plus_id = $matches[2];
543                }
544                else {
545                        $plus_id = '';
546                }
547                $msg_folder = urldecode($params['msg_folder']);
548
549                if(!$this->mbox || !is_resource($this->mbox))
550                        $this->mbox = $this->open_mbox($msg_folder);
551                $header = $this->get_header($msg_number);
552                if (!$header) {
553                        $return['status_get_msg_info'] = "false";
554                        return $return;
555                }
556
557                $header_ = imap_fetchheader($this->mbox, $msg_number, FT_UID);
558
559                $return_get_body = $this->get_body_msg($msg_number, $msg_folder);
560               
561                $body = $return_get_body['body'];
562
563                if($return_get_body['body']=='isCripted'){
564                        $exporteml = new ExportEml();
565                        $return['source']=$exporteml->export_msg_data($msg_number,$msg_folder);
566                        $return['body']                 = "";
567                        $return['attachments']  =  "";
568                        $return['thumbs']               =  "";
569                        $return['signature']    =  "";
570                        //return $return;
571                }else{
572            $return['body']             = $body;
573            $return['attachments']      = $return_get_body['attachments'];
574            $return['thumbs']           = $return_get_body['thumbs'];
575            $return['signature']        = $return_get_body['signature'];
576                }
577
578                $pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
579                if (preg_match($pattern, $header_, $fields))
580                {
581                        if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches)){
582                                $return['DispositionNotificationTo'] = "<".$matches[0].">";
583                        }
584                }
585
586                $return['Recent']       = $header->Recent;
587                $return['Unseen']       = $header->Unseen;
588                $return['Deleted']      = $header->Deleted;
589                $return['Flagged']      = $header->Flagged;
590
591                if($header->Answered =='A' && $header->Draft == 'X'){
592                        $return['Forwarded'] = 'F';
593                }
594
595                else {
596                        $return['Answered']     = $header->Answered;
597                        $return['Draft']        = $header->Draft;
598                }
599
600                $return['msg_number'] = $msg_number.$plus_id;
601                $return['msg_folder'] = $msg_folder;
602
603                $offset = $this->functions->CalculateDateOffset();
604                $msgTimestamp = $header->udate + $offset;
605
606                $date_msg = gmdate("d/m/Y",$msgTimestamp);
607//              if (date("d/m/Y") == $date_msg)
608//                      $return['udate'] = $header->udate;
609//              else
610                $return['udate'] = $header->udate;
611
612                $return['msg_day'] = $date_msg;
613                $return['msg_hour'] = gmdate("H:i",$msgTimestamp);
614
615                if (date("d/m/Y") == $date_msg) //no dia
616                {
617                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimestamp);
618                        $return['smalldate'] = gmdate("H:i",$msgTimestamp);
619
620                        $timestamp_now = strtotime("now");
621                        $timestamp_msg_time = $msgTimestamp;
622                        // $timestamp_now and $timestamp_msg_time are GMT.
623                        // The variable $timestamp_diff is calculated without MailDate TZ.
624                        $timestamp_diff = $timestamp_now - $timestamp_msg_time;
625
626                        if (gmdate("H",$timestamp_diff) > 0)
627                        {
628                                $return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
629                        }
630                        else
631                        {
632                                if (gmdate("i",$timestamp_diff) == 0){
633                                        $return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
634                                }
635                                elseif (gmdate("i",$timestamp_diff) == 1){
636                                        $return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
637                                }
638                                else{
639                                        $return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
640                                }
641                        }
642                }
643                else{
644                        $return['fulldate'] = gmdate("d/m/Y H:i",$msgTimestamp);
645                        $return['smalldate'] = gmdate("d/m/Y",$msgTimestamp);
646                }
647
648                $from = $header->from;
649                $return['from'] = array();
650                $return['from']['name'] = $this->decode_string($from[0]->personal);
651                $return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
652                if ($return['from']['name'])
653                {
654                        if (substr($return['from']['name'], 0, 1) == '"')
655                                $return['from']['full'] = $return['from']['name'] . ' ' . '&lt;' . $return['from']['email'] . '&gt;';
656                        else
657                                $return['from']['full'] = '"' . $return['from']['name'] . '" ' . '&lt;' . $return['from']['email'] . '&gt;';
658                }
659                else
660                        $return['from']['full'] = $return['from']['email'];
661
662                // Sender attribute
663                $sender = $header->sender;
664                $return['sender'] = array();
665                $return['sender']['name'] = $this->decode_string($sender[0]->personal);
666                $return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
667                if ($return['sender']['name'])
668                {
669                        if (substr($return['sender']['name'], 0, 1) == '"')
670                                $return['sender']['full'] = $return['sender']['name'] . ' ' . '&lt;' . $return['sender']['email'] . '&gt;';
671                        else
672                                $return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '&lt;' . $return['sender']['email'] . '&gt;';
673                }
674                else
675                        $return['sender']['full'] = $return['sender']['email'];
676
677                if($return['from']['full'] == $return['sender']['full'])
678                        $return['sender'] = null;
679                $to = $header->to;
680                $return['toaddress2'] = "";
681                if (!empty($to))
682                {
683                        foreach ($to as $tmp)
684                        {
685                                if (!empty($tmp->personal))
686                                {
687                                        $personal_tmp = imap_mime_header_decode($tmp->personal);
688                                        $return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
689                                        $return['toaddress2'] .= " ";
690                                        $return['toaddress2'] .= "&lt;";
691                                        if ($tmp->host != 'unspecified-domain')
692                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
693                                        else
694                                                $return['toaddress2'] .= $tmp->mailbox;
695                                        $return['toaddress2'] .= "&gt;";
696                                        $return['toaddress2'] .= ", ";
697                                }
698                                else
699                                {
700                                        if ($tmp->host != 'unspecified-domain')
701                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
702                                        else
703                                                $return['toaddress2'] .= $tmp->mailbox;
704                                        $return['toaddress2'] .= ", ";
705                                }
706                        }
707                        $return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
708                }
709
710                $cc = $header->cc;
711                $return['cc'] = "";
712                if (!empty($cc))
713                {
714                        foreach ($cc as $tmp_cc)
715                        {
716                                if (!empty($tmp_cc->personal))
717                                {
718                                        $personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
719                                        $return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
720                                        $return['cc'] .= " ";
721                                        $return['cc'] .= "&lt;";
722                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
723                                        $return['cc'] .= "&gt;";
724                                        $return['cc'] .= ", ";
725                                }
726                                else
727                                {
728                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
729                                        $return['cc'] .= ", ";
730                                }
731                        }
732                        $return['cc'] = $this->del_last_two_caracters($return['cc']);
733                }
734                else
735                {
736                        $return['cc'] = "";
737                }
738
739                ##
740                # @AUTHOR Rodrigo Souza dos Santos
741                # @DATE 2008/09/12
742                # @BRIEF Adding the BCC field.
743                ##
744                $bcc = $header->bcc;
745                $return['bcc'] = "";
746                if (!empty($bcc))
747                {
748                        foreach ($bcc as $tmp_bcc)
749                        {
750                                if (!empty($tmp_bcc->personal))
751                                {
752                                        $personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
753                                        $return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
754                                        $return['bcc'] .= " ";
755                                        $return['bcc'] .= "&lt;";
756                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
757                                        $return['bcc'] .= "&gt;";
758                                        $return['bcc'] .= ", ";
759                                }
760                                else
761                                {
762                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
763                                        $return['bcc'] .= ", ";
764                                }
765                        }
766                        $return['bcc'] = $this->del_last_two_caracters($return['bcc']);
767                }
768                else
769                {
770                        $return['bcc'] = "";
771                }
772
773                $reply_to = $header->reply_to;
774                $return['reply_to'] = "";
775                if (is_object($reply_to[0]))
776                {
777                        if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
778                        {
779                                if (!empty($reply_to[0]->personal))
780                                {
781                                        $personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
782                                        if(!empty($personal_reply_to[0]->text)) {
783                                                $return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
784                                                $return['reply_to'] .= " ";
785                                                $return['reply_to'] .= "&lt;";
786                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
787                                                $return['reply_to'] .= "&gt;";
788                                        }
789                                        else {
790                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
791                                        }
792                                }
793                                else
794                                {
795                                        $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
796                                }
797                        }
798                }
799                $return['reply_to'] = $this->decode_string($return['reply_to']);
800                $return['subject'] = $this->decode_string($header->fetchsubject);
801                $return['Size'] = $header->Size;
802                $return['reply_toaddress'] = $header->reply_toaddress;
803
804                //All this is to help in local messages
805                //$return['timestamp'] = $header->udate;
806                $return['timestamp'] = $header->udate;
807                $return['login'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];//$GLOBALS['phpgw_info']['user']['account_id'];
808                $return['reply_toaddress'] = $header->reply_toaddress;
809               
810                if($return_get_body['body']=='isSigned'){
811                    imap_close($this->mbox);
812                    $new_mail = $this->show_decript($return_get_body,$dec = 1);
813                    //$new_mail['signature'] =  $return_get_body['signature'];
814                    $return['body']             = $new_mail['body'];
815                    $return['attachments']      = $new_mail['attachments'];
816                    $return['thumbs']           = $new_mail['thumbs'];
817                    $return['folder'] = $return['msg_folder'];
818                    $return['original_ID'] =  $return['msg_number'];
819                    $return['msg_folder']       = 'INBOX'.$this->imap_delimiter.'decifradas';
820                    $return['msg_number']       = $new_mail['msg_no'];
821                    //$return['signature']      = $return_get_body['signature'];
822                }
823                return $return;
824        }
825
826        function get_msg_sample($msg_number)
827        {
828
829                $return = "";
830                if( (!isset($this->preferences['preview_msg_subject']) || ($this->preferences['preview_msg_subject'] != "1")) && 
831                        (!isset($this->preferences['preview_msg_tip']    ) || ($this->preferences['preview_msg_tip']     != "1")) )
832                {
833                        $return['body'] = "";
834                        return $return;
835                }
836
837                include_once("class.message_components.inc.php");
838                $msg = &new message_components($this->mbox);
839                $msg->fetch_structure($msg_number); 
840
841                if(!$msg->structure[$msg_number]->parts)
842                {
843                        $content = '';
844                        if (strtolower($msg->structure[$msg_number]->subtype) == "plain" || strtolower($msg->structure[$msg_number]->subtype) == "html")
845                        {
846                                $content = $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID|FT_PEEK), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
847                        }
848                }
849                else
850                {
851                        foreach($msg->pid[$msg_number] as $values => $msg_part)
852                        {
853
854                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
855                                if($file_type == "text/plain" || $file_type == "text/html") {
856                                        $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]);
857                                        break;
858                                }
859                        }
860                }
861                $content = $this->replace_special_characters($content);
862                $tags_replace = array("<br>","<br/>","<br />");
863                $content = str_replace($tags_replace," ", $content);
864                $content = strip_tags($content);
865                $content = str_replace(array("{","}","&nbsp;"), " ", $content);
866                $content = trim($content);
867                $content = html_entity_decode(substr($content,0,300));
868                $content != "" ? $return['body'] = " - " . $content: $return['body'] = "";
869                return $return;
870        }
871
872        function get_body_msg($msg_number, $msg_folder)
873        {
874                include_once("class.message_components.inc.php");
875                $msg = &new message_components($this->mbox);
876                $msg->fetch_structure($msg_number);
877                $return = array();
878                $return['attachments'] = $this-> download_attachment($msg,$msg_number);
879                if(!$this->has_cid)
880                {
881                        $return['thumbs']  = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
882                        $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
883                }
884
885                if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
886                {
887                        if((strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime') && (count($return['signature']) == 0 ) ){
888                                $return['body']='isCripted';
889                                return $return;
890                        }
891
892                        $attachment = array(); //No attachments
893
894                        if (strtolower($msg->structure[$msg_number]->subtype) == "x-pkcs7-mime")
895                        {
896                                $return['body']='isSigned';
897                                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
898                                $header_body_array = explode('MIME-Version: 1.0', $headers);
899                                $show_pkcs7 = $header_body_array[0] . 'MIME-Version: 1.0' . chr(0x0D) .chr(0x0A). $return['signature'][0];
900                                $return['source']=$show_pkcs7;
901                                array_shift($return['signature']);
902                                $return['signature'];
903                                //$return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
904                                imap_close($this->mbox);
905                                return $return;
906                        }
907
908                        $content = '';
909                        // If simple message is subtype 'html' or 'plain', then get content body.
910                        if(strtolower($msg->structure[$msg_number]->subtype) == "html" || 
911                                strtolower( $msg -> structure[ $msg_number ] -> subtype ) == 'plain'){
912
913                                        $content = $this->decodeBody(
914                                                imap_body( $this -> mbox, $msg_number, FT_UID ),
915                                                $msg -> encoding[ $msg_number ][ 0 ],
916                                                $msg -> charset[ $msg_number ][ 0 ]
917                                        );
918
919                                        if ( strtolower( $msg -> structure[ $msg_number ] -> subtype ) == 'plain' )
920                                        {
921                                                $content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content );
922                                                $content = htmlentities( $content );
923                                                $content = $this -> replace_links( $content );
924                                                $content = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $content );
925                                                $content = '<pre>' . $content . '</pre>';
926
927                                                $return[ 'body' ] = $content;
928
929                                                return $return;
930                                        }
931                                }
932                }
933                else
934                { //Complicated message, multiple parts
935                        $html_body = '';
936                        $content = '';
937                        $has_multipart = true;
938                        $this->has_cid = false;
939                        array_shift($return['signature']);
940                        if (strtolower($msg->structure[$msg_number]->subtype) == "related")
941                                $this->has_cid = true;
942
943                        if (strtolower($msg->structure[$msg_number]->subtype) == "alternative") {
944                                $show_only_html = false;
945                                foreach($msg->pid[$msg_number] as $values => $msg_part) {
946                                        $file_type = strtolower($msg->file_type[$msg_number][$values]);
947                                        if($file_type == "text/html")
948                                                $show_only_html = true;
949                                }
950                        }
951                        else
952                                $show_only_html = false;
953
954                        foreach($msg->pid[$msg_number] as $values => $msg_part)
955                        {
956
957                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
958                                if($file_type == "message/rfc822" || $file_type == "multipart/alternative")
959                                {
960                                        // Show only 'text/html' part, when message/rfc822 format contains 'text/plain' alternative part.
961                                        if(array_key_exists($values+1, $msg->file_type[$msg_number]) &&
962                                                strtolower($msg->file_type[$msg_number][$values+1]) == 'text/plain' &&
963                                                array_key_exists($values+2, $msg->file_type[$msg_number]) &&
964                                                strtolower($msg->file_type[$msg_number][$values+2]) == 'text/html') {
965                                                        $has_multipart = false;
966                                                }
967                                }       
968
969                                if(($file_type == "text/plain"
970                                        || $file_type == "text/html")
971                                                && $file_type != 'attachment')
972                                {
973
974                                       
975                                       if($this->prefs['max_msg_size'] == "1")
976                                            $max_size = 1048576;
977                                        else
978                                            $max_size = 102400;
979
980                                        if($file_type == "text/plain" && !$show_only_html && $has_multipart)
981                                        {
982                                                // if TXT file size > 100kb, then it will not expand.
983                                                if(!($file_type == "text/plain" && $msg->fsize[$msg_number][$values] > $max_size)) {
984                                                         $content .= htmlentities($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));
985                                                        $content = '<pre>' . $content . '</pre>';
986                                                }
987                                        }
988                                        // if HTML attachment file size > 300kb, then it will not expand.
989                                        else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < $max_size*3)
990                                        {
991                                                $content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
992                                                $show_only_html = true;
993                                        }
994                                }
995                                 else if($file_type == "message/delivery-status" || $file_type == "message/feedback-report"){
996                                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
997                                        $content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
998                    $content = '<pre>' . $content . '</pre>';
999                                }
1000                                else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
1001
1002                                        include_once("class.imap_attachment.inc.php");
1003                                        $att = new imap_attachment();
1004                                        $attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
1005                                        if($attachments['number_attachments'] > 0) {
1006                                                foreach($attachments ['attachment'] as $index => $attachment)
1007                                                {
1008                                                        if ( in_array( strtolower( $attachment[ 'type' ] ), array( 'delivery-status', 'rfc822', 'rfc822-headers', 'plain' ) ) )
1009                                                        {
1010                                                                $obj = imap_rfc822_parse_headers( imap_fetchbody( $this -> mbox, $msg_number, $msg_part, FT_UID ), $msg -> encoding[ $msg_number ][ $values ] );
1011
1012                                                                $content .= '<hr align="left" width="95%" style="border:1px solid #DCDCDC">';
1013                                                                $content .= '<br><table  style="margin:2px;border:1px solid black;background:#EAEAEA">';
1014
1015                                                                $content .= '<tr><td><b>' . $this->functions->getLang("Subject")
1016                                                                        . ':</b></td><td>' .$this->decode_string($obj->subject) . '</td></tr>';
1017
1018                                                                $content .= '<tr><td><b>' . $this -> functions -> getLang( 'From' ) . ':</b></td><td>'
1019                                                                        . $this -> replace_links( $this -> decode_string( $obj -> from[ 0 ] -> mailbox . '@' . $obj -> from[ 0 ] -> host) )
1020                                                                        . '</td></tr>';
1021
1022                                                                $content .= '<tr><td><b>' . $this->functions->getLang("Date") . ':</b></td><td>' . $obj->date . '</td></tr>';
1023
1024                                                                $content .= '<tr><td><b>' . $this -> functions -> getLang( 'TO' ) . ':</b></td><td>'
1025                                                                        . $this -> replace_links( $this -> decode_string( $obj -> to[ 0 ] -> mailbox . '@' . $obj -> to[ 0 ] -> host ) )
1026                                                                        . '</td></tr>';
1027
1028                                                                if ( $obj->cc )
1029                                                                        $content .= '<tr><td><b>' . $this -> functions -> getLang( 'CC' ) . ':</b></td><td>'
1030                                                                                . $this -> replace_links( $this -> decode_string( $obj -> cc[ 0 ] -> mailbox . '@' . $obj -> cc[ 0 ] -> host ) )
1031                                                                                . '</td></tr>';
1032
1033                                                                $content .= '</table><br>';
1034
1035
1036                                                                $id = ( ( strtolower( $attachment[ 'type' ] ) == 'delivery-status' ) ? false : true );
1037                                                                if ( strtolower( $msg->structure[$msg_number]->parts[1]->parts[0]->subtype ) == 'plain' )
1038                                                                {
1039                                                                        $id = !$id;
1040                                                                        if ( $msg->structure[$msg_number]->parts[1]->parts[0]->encoding == 4 )
1041                                                                                $msg->encoding[ $msg_number ][ $values ] = 'quoted-printable';
1042                                                                }
1043
1044                                                                $body = $this->decodeBody(
1045                                                                        imap_fetchbody(
1046                                                                                $this->mbox,
1047                                                                                $msg_number,
1048                                                                                ( $attachment['part_in_msg'] + ( ( int ) $id ) ) . ".1",
1049                                                                                FT_UID
1050                                                                        ),
1051                                                                        $msg->encoding[ $msg_number ][ $values ],
1052                                                                        $msg->charset[ $msg_number ][ $values ]
1053                                                                );
1054
1055                                                                if ( strtolower( $msg->structure[$msg_number]->parts[1]->parts[0]->subtype ) == 'plain' )
1056                                                                {
1057                                                                        $body = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $body );
1058                                                                        $body = htmlentities( $body );
1059                                                                        $body = $this -> replace_links( $body );
1060                                                                        $body = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $body );
1061                                                                        $body = '<pre>' . $body . '</pre>';
1062                                                                }
1063
1064                                                                $content .= $body;
1065                                                                break;
1066                                                        }
1067                                                }
1068                                        }
1069                                }
1070                        }
1071                        if($file_type == "text/plain" && ($show_only_html &&  $msg_part == 1) ||  (!$show_only_html &&  $msg_part == 3)){
1072                                if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" &&  $msg_part == 1)
1073                                        $content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
1074                                else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
1075                                        $content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));
1076                        }
1077                }
1078                // Force message with flag Seen (imap_fetchbody not works correctly)
1079                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");
1080                $this->set_messages_flag($params);
1081                $content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
1082                $content = $this->replace_special_characters($content);
1083                $return['body'] = $content;
1084                return $return;
1085        }
1086
1087        function htmlfilter($body)
1088        {
1089                require_once('htmlfilter.inc');
1090
1091                $tag_list = Array(
1092                                false,
1093                                'blink',
1094                                'object',
1095                                'meta',
1096                                'html',
1097                                'link',
1098                                'frame',
1099                                'iframe',
1100                                'layer',
1101                                'ilayer',
1102                                'plaintext'
1103                );
1104
1105                /**
1106                * A very exclusive set:
1107                */
1108                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
1109                $rm_tags_with_content = Array(
1110                                'script',
1111                                'style',
1112                                'applet',
1113                                'embed',
1114                                'head',
1115                                'frameset',
1116                                'xml',
1117                                'xmp'
1118                );
1119
1120                $self_closing_tags =  Array(
1121                                'img',
1122                                'br',
1123                                'hr',
1124                                'input'
1125                );
1126
1127                $force_tag_closing = true;
1128
1129                $rm_attnames = Array(
1130                        '/.*/' =>
1131                                Array(
1132                                        '/target/i',
1133                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
1134                                        '/^dynsrc/i',
1135                                        '/^datasrc/i',
1136                                        '/^data.*/i',
1137                                        '/^lowsrc/i'
1138                                )
1139                );
1140
1141                /**
1142                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
1143                 * some idea of what's going on here. :)
1144                 */
1145
1146                $bad_attvals = Array(
1147                '/.*/' =>
1148                Array(
1149                      '/.*/' =>
1150                              Array(
1151                                Array(
1152                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
1153                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
1154                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
1155                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
1156                                      ),
1157                            Array(
1158                                              '\\1oddjob:\\2\\1',
1159                                          //'\\1uucp:\\2\\1', -> doclinks notes
1160                                      '\\1amaretto:\\2\\1',
1161                                          '\\1round:\\2\\1'
1162                                        )
1163                                    ),
1164
1165                          '/^style/i' =>
1166                              Array(
1167                                        Array(
1168                                          '/expression/i',
1169                                              '/behaviou*r/i',
1170                                          '/binding/i',
1171                                              '/include-source/i',
1172                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
1173                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
1174                                         ),
1175                                        Array(
1176                                          'idiocy',
1177                                              'idiocy',
1178                                          'idiocy',
1179                                              'idiocy',
1180                                          'url(\\1http://securityfocus.com/\\1)',
1181                                          'url(\\1http://securityfocus.com/\\1)'
1182                                         )
1183                                )
1184                          )
1185                    );
1186
1187                $add_attr_to_tag = Array(
1188                                '/^a$/i' => Array('target' => '"_new"')
1189                );
1190
1191
1192                $trusted_body = sanitize($body,
1193                                $tag_list,
1194                                $rm_tags_with_content,
1195                                $self_closing_tags,
1196                                $force_tag_closing,
1197                                $rm_attnames,
1198                                $bad_attvals,
1199                                $add_attr_to_tag
1200                );
1201
1202            return $trusted_body;
1203        }
1204
1205        function decodeBody($body, $encoding, $charset=null)
1206        {
1207                /**
1208                * replace e-mail by anchor.
1209                */
1210                // HTML Filter
1211                //$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);
1212        //$body = str_replace("\r\n", "\n", $body);
1213                if ($encoding == 'quoted-printable')
1214                {
1215                        /*
1216
1217                        for($i=0;$i<256;$i++) {
1218                                $c1=dechex($i);
1219                                if(strlen($c1)==1){$c1="0".$c1;}
1220                                $c1="=".$c1;
1221                                $myqprinta[]=$c1;
1222                                $myqprintb[]=chr($i);
1223                        }
1224                         */
1225                        $body = str_replace($myqprinta,$myqprintb,($body));
1226                        $body = quoted_printable_decode($body);
1227                while (ereg("=\n", $body))
1228                {
1229                        $body = ereg_replace ("=\n", '', $body);
1230                }
1231        }
1232        else if ($encoding == 'base64')
1233        {
1234                $body = base64_decode($body);
1235        }
1236
1237                // All other encodings are returned raw.
1238                if (strtolower($charset) == "utf-8")
1239                        return utf8_decode($body);
1240        else
1241                        return $body;
1242        }
1243
1244        function process_embedded_images($msg, $msgno, $body, $msg_folder)
1245        {
1246                if (count($msg->inline_id[$msgno]) > 0)
1247                {
1248                        foreach ($msg->inline_id[$msgno] as $index => $cid)
1249                        {
1250                                $cid = eregi_replace("<", "", $cid);
1251                                $cid = eregi_replace(">", "", $cid);
1252                                $msg_part = $msg->pid[$msgno][$index];
1253                                //$body = eregi_replace("alt=\"\"", "", $body);
1254                                $body = eregi_replace("<br/>", "", $body);
1255                                $body = str_replace("src=\"cid:".$cid."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1256                                $body = str_replace("src='cid:".$cid."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1257                                $body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1258                        }
1259                }
1260
1261                return $body;
1262        }
1263
1264        function replace_special_characters($body)
1265        {
1266                // Suspected TAGS!
1267                /*$tag_list = Array(
1268                        'blink','object','meta',
1269                        'html','link','frame',
1270                        'iframe','layer','ilayer',
1271                        'plaintext','script','style','img',
1272                        'applet','embed','head',
1273                        'frameset','xml','xmp');
1274                */
1275
1276                // Layout problem: Change html elements
1277                // with absolute position to relate position, CASE INSENSITIVE.
1278                $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
1279
1280                $tag_list = Array('head','blink','object','frame',
1281                        'iframe','layer','ilayer','plaintext','script',
1282                        'applet','embed','frameset','xml','xmp','style');
1283
1284                $blocked_tags = array();
1285                foreach($tag_list as $index => $tag) {
1286                        $new_body = @mb_eregi_replace("<$tag", "<!--$tag", $body);
1287                        if($body != $new_body) {
1288                                $blocked_tags[] = $tag;
1289                        }
1290                        $body = @mb_eregi_replace("</$tag>", "</$tag-->", $new_body);
1291                }
1292                // Malicious Code Remove
1293                $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";
1294                preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
1295                foreach($rest[0] as $i => $val)
1296                        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
1297                                $body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
1298
1299                $body = $this-> replace_links($body);
1300
1301                //Remoção de tags <span></span> para correção de erro no firefox
1302                $body = mb_eregi_replace("<span><span>","",$body);
1303                $body = mb_eregi_replace("</span></span>","",$body);
1304                //Correção para compatibilização com Outlook, ao visualizar a mensagem
1305                $body = mb_ereg_replace('<!--\[','<!-- [',$body);
1306                $body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
1307                $body = str_replace("\x00", '', $body);
1308                                         
1309                return  "<span>".$body;
1310        }
1311
1312        function replace_links( $body )
1313        {
1314                // Domains and IPs addresses found in the text and which is not a link yet should be replaced by one.
1315                // See more informations in www.iana.org
1316                $octets = array(
1317                        'first' => '(2[0-3][0-9]|1[0-9]{2}|[1-9][0-9]?)',
1318                        'middle' => '(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})',
1319                        'last' => '(25[0-4]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)'
1320                );
1321
1322                $ip = "\b{$octets[ 'first' ]}\.({$octets[ 'middle' ]}\.){2}{$octets[ 'last' ]}\b";
1323
1324                $top_level_domains = '(\.(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|as|asia|at|au|aw|ax|az|'
1325                        . 'ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bl|bm|bn|bo|br|bs|bt|bv|bw|by|bz|'
1326                        . 'ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|'
1327                        . 'de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|'
1328                        . 'ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|'
1329                        . 'hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|'
1330                        . 'ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|'
1331                        . 'ma|mc|md|me|mf|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|'
1332                        . 'mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|'
1333                        . 'pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|'
1334                        . 'sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|'
1335                        . 'tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|'
1336                        . 'ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))+\b';
1337
1338                $path = '(?>\/[\w\d\/\.\'\(\)\-\+~?!&#@$%|:;,*=_]+)?';
1339                $port = '(?>:\d{2,5})?';
1340                $domain = '(?>[\w\d_\-]+)';
1341                $subdomain = "(?>{$domain}\.)*";
1342                $protocol = '(?>(http|ftp)(s)?:\/\/)?';
1343                $url = "(?>{$protocol}((?>{$subdomain}{$domain}{$top_level_domains}|{$ip}){$port}{$path}))";
1344
1345                $pattern = "/(<\w[^>]+|[\/\"'@=])?{$url}/";
1346                ini_set( 'pcre.backtrack_limit', 300000 );
1347
1348                /*
1349                // PHP 5.3
1350                $replace = function( $matches )
1351                {
1352                        if ( $matches[ 1 ] )
1353                                return $matches[ 0 ];
1354
1355                        $url = ( $matches[ 2 ] ) ? $matches[ 2 ] : 'http';
1356                        $url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";
1357                        return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";
1358                };
1359                $body = preg_replace_callback( $pattern, $replace, $body );
1360                 */
1361
1362                // PHP 5.2.x - Remover assim que possível
1363                $body = preg_replace_callback( $pattern,
1364                        create_function(
1365                                '$matches',
1366                                'if ( $matches[ 1 ] ) return $matches[ 0 ];'
1367                                . '$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : "http";'
1368                                . '$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";'
1369                                . 'return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";'
1370                        ), $body
1371                );
1372                ini_set( 'pcre.backtrack_limit', 100000 );
1373                // E-mail address in the text should create a new e-mail on ExpressoMail
1374                $pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im';
1375                $replacement = '$1<a href="mailto:$2">$2</a>$3';
1376                $body = preg_replace( $pattern, $replacement, $body );
1377
1378                return $body;
1379        }
1380
1381        function get_signature($msg, $msg_number, $msg_folder)
1382        {
1383            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1384            include_once("class.db_functions.inc.php");
1385            foreach ($msg->file_type[$msg_number] as $index => $file_type)
1386            {
1387                $sign = array();
1388                $temp = $this->get_info_head_msg($msg_number);
1389                if($temp['ContentType'] =='normal') return $sign;
1390                $file_type = strtolower($file_type);
1391                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
1392                {
1393                    if ($temp['ContentType'] == 'signature')
1394                    {
1395                        if(!$this->mbox || !is_resource($this->mbox))
1396                        $this->mbox = $this->open_mbox($msg_folder);
1397
1398                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
1399
1400                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1401                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
1402
1403                        $certificado = new certificadoB();
1404                        $validade = $certificado->verificar($imap_msg);
1405                                        $sign[] = $certificado->msg_sem_assinatura;
1406                        if ($certificado->apresentado)
1407                        {
1408                            $from = $header->from;
1409                            foreach ($from as $id => $object)
1410                            {
1411                                $fromname = $object->personal;
1412                                $fromaddress = $object->mailbox . "@" . $object->host;
1413                            }
1414                            foreach ($certificado->erros_ssl as $item)
1415                            {
1416                                $sign[] = $item . "#@#";
1417                            }
1418
1419                            if (count($certificado->erros_ssl) < 1)
1420                            {
1421                                $check_msg = 'Message untouched';
1422                                if(strtoupper($fromaddress) == strtoupper($certificado->dados['EMAIL']))
1423                                {
1424                                    $check_msg .= ' and authentic###';
1425                                }
1426                                else
1427                                {
1428                                    $check_msg .= ' with signer different from sender#@#';
1429                                }
1430                                $sign[] = $check_msg;
1431                            }
1432                                               
1433                            $sign[] = 'Message signed by: ###' . $certificado->dados['NOME'];
1434                            $sign[] = 'Certificate email: ###' . $certificado->dados['EMAIL'];
1435                            $sign[] = 'Mail from: ###' . $fromaddress;
1436                            $sign[] = 'Certificate Authority: ###' . $certificado->dados['EMISSOR'];
1437                            $sign[] = 'Validity of certificate: ###' . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
1438                            $sign[] = 'Message date: ###' . $header->Date;
1439
1440                            $cert = openssl_x509_parse($certificado->cert_assinante);
1441
1442                            $sign_alert = array();
1443                            $sign_alert[] = 'Certificate Owner###:\n';
1444                            $sign_alert[] = 'Common Name (CN)###  ' . $cert[subject]['CN'] .  '\n';
1445                            $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1446                            $sign_alert[]= 'Organization (O)###  ' . $cert[subject]['O'] .  '\n';
1447                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[subject]['OU'][0] .  '\n';
1448                            //$sign_alert[] = 'Serial Number### ' . $cert['serialNumber'] . '\n';
1449                            $sign_alert[] = 'Personal Data###:' . '\n';
1450                            $sign_alert[] = 'Birthday### ' . $X .  '\n';
1451                            $sign_alert[]= 'Fiscal Id### ' . $certificado->dados['CPF'] .  '\n';
1452                            $sign_alert[]= 'Identification### ' . $certificado->dados['RG'] .  '\n\n';
1453                            $sign_alert[]= 'Certificate Issuer###:\n';
1454                            $sign_alert[]= 'Common Name (CN)###  ' . $cert[issuer]['CN'] . '\n';
1455                            $sign_alert[]= 'Organization (O)###  ' . $cert[issuer]['O'] .  '\n';
1456                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[issuer]['OU'][0] .  '\n\n';
1457                            $sign_alert[]= 'Validity###:\n';
1458                            $H = data_hora($cert[validFrom]);
1459                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1460                            $sign_alert[]= 'Valid From### ' . $X .  '\n';
1461                            $H = data_hora($cert[validTo]);
1462                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1463                            $sign_alert[]= 'Valid Until### ' . $X;
1464                            $sign[] = $sign_alert;
1465
1466                            $this->db = new db_functions();
1467                           
1468                            // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
1469                            if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
1470                                $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
1471                        }
1472                        else
1473                        {
1474                            $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
1475                            foreach($certificado->erros_ssl as $item)
1476                                $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
1477                        }
1478                    }
1479                }
1480            }
1481            return $sign;
1482        }
1483
1484        function get_thumbs($msg, $msg_number, $msg_folder)
1485        {
1486                $thumbs_array = array();
1487                $i = 0;
1488        foreach ($msg->file_type[$msg_number] as $index => $file_type)
1489        {
1490                $file_type = strtolower($file_type);
1491                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
1492                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
1493                                $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].">";
1494                                $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>";
1495                                        $thumbs_array[] = $href;
1496                        }
1497                        $i++;
1498                }
1499        }
1500        return $thumbs_array;
1501        }
1502
1503        /*function delete_msg($params)
1504        {
1505                $folder = $params['folder'];
1506                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
1507
1508                $mbox_stream = $this->open_mbox($folder);
1509
1510                foreach ($msgs_to_delete as $msg_number){
1511                        imap_delete($mbox_stream, $msg_number, FT_UID);
1512                }
1513                imap_close($mbox_stream, CL_EXPUNGE);
1514                return $params['msgs_to_delete'];
1515        }*/
1516
1517        // Novo
1518        function delete_msgs($params)
1519        {
1520
1521                $folder = $params['folder'];
1522                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
1523                $msgs_number = explode(",",$params['msgs_number']);
1524                $border_ID = $params['border_ID'];
1525
1526                $return = array();
1527
1528                if ($params['get_previous_msg']){
1529                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1530                        // Fix problem in unserialize function JS.
1531                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1532                }
1533
1534                //$mbox_stream = $this->open_mbox($folder);
1535                $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()))));
1536
1537                foreach ($msgs_number as $msg_number)
1538                {
1539                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1540                                $return['msgs_number'][] = $msg_number;
1541                }
1542
1543                $return['folder'] = $folder;
1544                $return['border_ID'] = $border_ID;
1545
1546                if($mbox_stream)
1547                        imap_close($mbox_stream, CL_EXPUNGE);
1548                return $return;
1549        }
1550
1551
1552        function refresh($params)
1553        {
1554
1555                $folder = $params['folder'];
1556                $msg_range_begin = $params['msg_range_begin'];
1557                $msg_range_end = $params['msg_range_end'];
1558                $msgs_existent = $params['msgs_existent'];
1559                $sort_box_type = $params['sort_box_type'];
1560                $sort_box_reverse = $params['sort_box_reverse'];
1561                $msgs_in_the_server = array();
1562                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1563                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1564                $msgs_in_the_server = array_keys($msgs_in_the_server);
1565                if(!count($msgs_in_the_server))
1566                        return array();
1567
1568                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
1569                $msgs_in_the_client = explode(",", $msgs_existent);
1570
1571                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
1572                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
1573
1574                $msgs_to_exec = array();
1575                foreach($msg_to_insert as $msg_number)
1576                        $msgs_to_exec[] = $msg_number;
1577                sort($msgs_to_exec);
1578
1579                $return = array();
1580                $i = 0;
1581                foreach($msgs_to_exec as $msg_number)
1582                {
1583                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
1584                        * atributos do cabeçalho. Como eu preciso do atributo Importance
1585                        * para saber se o email é importante ou não, uso abaixo a função
1586                        * imap_fetchheader e busco o atributo importance nela para passar
1587                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1588                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1589                        * não preciso reimplementar o método utilizando o fetchheader.
1590                        */
1591                   
1592                        $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1593                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
1594                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
1595
1596                        $msg_sample = $this->get_msg_sample($msg_number);
1597                        $return[$i]['msg_sample'] = $msg_sample;
1598
1599                        $header = $this->get_header($msg_number);
1600                        if (!is_object($header))
1601                                continue;
1602
1603                        $return[$i]['msg_number']       = $msg_number;
1604
1605                        $return[$i]['msg_folder']       = $folder;
1606                        // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1607                        $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
1608                        $return[$i]['Recent']           = $header->Recent;
1609                        $return[$i]['Unseen']           = $header->Unseen;
1610                        $return[$i]['Answered']         = $header->Answered;
1611                        $return[$i]['Deleted']          = $header->Deleted;
1612                        $return[$i]['Draft']            = $header->Draft;
1613                        $return[$i]['Flagged']          = $header->Flagged;
1614
1615                        $return[$i]['udate'] = $header->udate;
1616               
1617                        $from = $header->from;
1618                        $return[$i]['from'] = array();
1619                        $tmp = imap_mime_header_decode($from[0]->personal);
1620                        $return[$i]['from']['name'] = $tmp[0]->text;
1621                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
1622                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
1623                        if(!$return[$i]['from']['name'])
1624                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
1625
1626                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1627                        $return[$i]['toaddress'] = '';
1628                        foreach ($toaddress as $tmp)
1629                                $return[$i]['toaddress'] .= $tmp->text;*/
1630                        $to = $header->to;
1631                        $return[$i]['to'] = array();
1632                        $tmp = imap_mime_header_decode($to[0]->personal);
1633                        $return[$i]['to']['name'] = $tmp[0]->text;
1634                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1635                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
1636
1637                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1638
1639                        $return[$i]['Size'] = $header->Size;
1640                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
1641
1642                        $return[$i]['attachment'] = array();
1643                        if (!isset($imap_attachment))
1644                        {
1645                                include_once("class.imap_attachment.inc.php");
1646                                $imap_attachment = new imap_attachment();
1647                        }
1648                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
1649                        $i++;
1650                }
1651                $return['quota'] = $this->get_quota(array('folder_id' => $folder));
1652                $return['sort_box_type'] = $params['sort_box_type'];
1653                if(!$this->mbox || !is_resource($this->mbox))
1654                {
1655                    $this->open_mbox($folder);
1656                }
1657                $return['new_msgs'] = imap_num_recent($this->mbox);
1658                $return['msgs_to_delete'] = $msg_to_delete;
1659                $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
1660                if($this->mbox && is_resource($this->mbox))
1661                        imap_close($this->mbox);
1662
1663                return $return;
1664        }
1665
1666     /**
1667     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1668     * assinado ou cifrado.
1669     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1670     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1671     * @param $msg_number O número da mesagem
1672     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1673     */
1674    function getMessageType($msg_number, $headers = false){
1675            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1676            $contentType = "normal";
1677            if (!$headers){
1678                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1679            }
1680           
1681            if (preg_match("/pkcs7-signature/i", $headers) == 1){
1682                $contentType = "signature";
1683            } else if (preg_match("/pkcs7-mime/i", $headers) == 1){
1684                $contentType = testa_p7m( imap_body($this->mbox, imap_msgno($this->mbox, $msg_number)) );
1685            }
1686
1687            return $contentType;
1688    }
1689
1690         /**
1691     * Metodo que retorna todas as pastas do usuario logado.
1692     * @param $params array opcional para repassar os argumentos ao metodo.
1693     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
1694     * excluindo as compartilhadas para ele.
1695     * Se usar $params['folderType'] = "default" irá retornar somente as pastas defaults
1696     * Se usar $params['folderType'] = "personal" irá retornar somente as pastas pessoais
1697     * Se usar $params['folderType'] = null irá retornar todas as pastas
1698     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
1699     * folder_id, folder_name, folder_parent e folder_hasChildren.
1700     */
1701        function get_folders_list($params = null)
1702        {
1703                $mbox_stream = $this->open_mbox();
1704                if($params && $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
1705                        $this->delete_mailbox(array("del_past" => "INBOX/decifradas"));
1706                }
1707
1708
1709                $inbox = 'INBOX';
1710                $trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
1711                $drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
1712                $spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
1713                $sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
1714                $uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'];
1715                // Free others requests
1716                session_write_close();
1717
1718                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
1719                $folders_list = imap_getmailboxes($mbox_stream, $serverString, ($params && $params['noSharedFolders']) ? "INBOX/*" : "*");
1720                if ( $params && $params['noSharedFolders'] )
1721                        $folders_list = imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ) + $folders_list;
1722
1723                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1724
1725                $tmp = array();
1726                $resultMine = array();
1727                $resultDefault = array();
1728
1729                if (is_array($folders_list)) {
1730                        reset($folders_list);
1731                        $this->ldap = new ldap_functions();
1732
1733                        $i = 0;
1734                        while (list($key, $val) = each($folders_list)) {
1735                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
1736
1737                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1738                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
1739
1740                                if($tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas') {
1741                                        //error_log('passou', 3,'/tmp/imap_get_list.log');
1742                                        //imap_deletemailbox($mbox_stream,imap_utf7_encode("{".$this->imap_server."}".'INBOX/decifradas'));
1743                                        continue;
1744                                }
1745                                $result[$i]['folder_unseen'] = $status->unseen;
1746                                $folder_id = $tmp_folder_id[1];
1747                                $result[$i]['folder_id'] = $folder_id;
1748
1749                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1750                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1751                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1752                       
1753                                if ($uid2cn && substr($folder_id,0,4) == 'user') {
1754                                        //$this->ldap = new ldap_functions();
1755                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
1756                                                $result[$i]['folder_name'] = $cn;
1757                                        }
1758                                }
1759
1760                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1761                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
1762
1763                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1764                                        $result[$i]['folder_hasChildren'] = 1;
1765                                else
1766                                        $result[$i]['folder_hasChildren'] = 0;
1767
1768                                switch ($tmp_folder_id[1]) {
1769                                        case $inbox:
1770                                        case $sent:
1771                                        case $drafts:
1772                                        case $spam:
1773                                        case $trash:
1774                                                $resultDefault[]=$result[$i];
1775                                                break;
1776                                        default:
1777                                                $resultMine[]=$result[$i];
1778                                }
1779
1780                                $i++;
1781                        }
1782                }
1783
1784                if ( $params && !$params['noQuotaInfo'] ) {
1785                        //Get quota info of current folder
1786                        $current_folder = "INBOX";
1787                        if($params && $params['folder'])
1788                                $current_folder = $params['folder'];
1789                               
1790                        $arr_quota_info = $this->get_quota(array('folder_id' => $current_folder));
1791                } else {
1792                        $arr_quota_info = array();
1793                }
1794               
1795                // Sorting resultMine
1796                foreach ($resultMine as $folder_info)
1797                {
1798                        $array_tmp[] = $folder_info['folder_id'];
1799                }
1800
1801                natcasesort($array_tmp);
1802               
1803                $result2 = array();
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                if(!isset($params['folder'])) {
3249                        $folder_params = array("noSharedFolders"=>1);
3250                        if(isset($params['folderType']))
3251                                $folder_params['folderType'] = $params['folderType'];
3252                        $folders = $this->get_folders_list($folder_params);
3253                }
3254                else
3255                        $folders = array(0=>array('folder_id'=>$params['folder']));
3256                $num_msgs = 0;
3257                $max_msgs = $params['max_msgs'];
3258                $return["total_msgs"] = 0;
3259                foreach($folders as $id =>$folder)
3260                {
3261                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3262                                foreach($criterias as $criteria_fixed)
3263                    {
3264                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3265                                        $mbox_stream = $this->open_mbox($folder['folder_id']);
3266       
3267                                        $messages = imap_search($mbox_stream, $_filter, SE_UID);
3268                                       
3269                                        if ($messages == ''){
3270                                                if($mbox_stream)
3271                                                        imap_close($mbox_stream);
3272                                                continue;       
3273                                        }
3274                                                                       
3275                                        foreach($messages as $msg_number)
3276                                        {       
3277                                                if($num_msgs>=$max_msgs)
3278                                                        break;                         
3279                                                $temp = $this->get_info_head_msg($msg_number);
3280                                                if(!$temp)
3281                                                        return false;
3282                                                $temp['msg_folder'] = $folder['folder_id'];
3283                                                $return[$num_msgs] = $temp;
3284                                                $num_msgs++;
3285                                               
3286                                        }
3287                                        $return['num_msgs'] = $num_msgs;
3288                                        $return["total_msgs"]+=count($messages);
3289                                        if($mbox_stream)
3290                                                imap_close($mbox_stream);
3291                                        if($num_msgs>=$max_msgs)
3292                                                        continue;
3293                                }
3294                        }                       
3295                }
3296                return $return;
3297        }
3298
3299        function delete_and_show_previous_message($params)
3300        {
3301                $return = $this->get_info_previous_msg($params);
3302
3303                $params_tmp1 = array();
3304                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3305                $params_tmp1['folder'] = $params['msg_folder'];
3306                $return_tmp1 = $this->delete_msg($params_tmp1);
3307
3308                $return['msg_number_deleted'] = $return_tmp1;
3309
3310                return $return;
3311        }
3312
3313
3314        function automatic_trash_cleanness($params)
3315        {
3316                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3317                $criteria =  'BEFORE "'.$before_date.'"';
3318                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
3319                // Free others requests
3320                session_write_close();
3321                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3322                if (is_array($messages)){
3323                        foreach ($messages as $msg_number){
3324                                imap_delete($mbox_stream, $msg_number, FT_UID);
3325                        }
3326                }
3327                if($mbox_stream)
3328                        imap_close($mbox_stream, CL_EXPUNGE);
3329                return $messages;
3330        }
3331//      Fix the search problem with special characters!!!!
3332        function remove_accents($string) {
3333                return strtr($string,
3334                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
3335                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3336        }
3337
3338        function make_search_date($date){
3339
3340            $months = array(
3341                1   => 'jan',
3342                2   => 'feb',
3343                3   => 'mar',
3344                4   => 'apr',
3345                5   => 'may',
3346                6   => 'jun',
3347                7   => 'jul',
3348                8   => 'aug',
3349                9   => 'sep',
3350                10  => 'oct',
3351                11  => 'nov',
3352                12  => 'dec'
3353            );
3354
3355            //TODO: Adaptar a data de acordo com o locale do sistema.
3356            list($day,$month,$year) = explode("/", $date);
3357            $search_date = $day."-".$months[intval($month)]."-".$year;
3358            return $search_date;
3359
3360        }
3361
3362        function search_msg($params = ''){
3363                $retorno = "";
3364                $mbox_stream = "";
3365                if(strpos($params['condition'],"#")===false) { //local messages
3366                        $search=false;
3367                }
3368                else {
3369                        $search = explode(",",$params['condition']);
3370                }
3371
3372                $offsetToGMT = $this->functions->CalculateDateOffset();
3373
3374                if($search){
3375                        $search_criteria = '';
3376                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
3377                        foreach($search as $tmp)
3378                        {
3379                                $tmp1 = explode("##",$tmp);
3380                                $sum = 0;
3381                                $name_box = $tmp1[0];
3382                                unset($filter);
3383                                foreach($tmp1 as $index => $criteria)
3384                                {
3385                                    if ($index != 0 && strlen($criteria) != 0)
3386                                    {
3387                                        $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
3388                                        $filter .= " ".$filter_array[0];
3389                                        if (strlen($filter_array[1]) != 0){
3390                                            if (trim($filter_array[0]) != 'BEFORE' &&
3391                                                trim($filter_array[0]) != 'SINCE' &&
3392                                                trim($filter_array[0]) != 'ON')
3393                                            {
3394                                                // Remove accents from criteria, because method remove accents is broken.
3395                                                $a = 'áàâãäéèêëíìîïóòôõöúùûüçÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ';
3396                                                $b = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';
3397                                                $filter .= '"'.strtr($filter_array[1], $a, $b).'"';
3398                                            }
3399                                            else {
3400                                                $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3401                                            }
3402                                        }
3403                                    }
3404                                }
3405                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3406
3407                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
3408                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
3409                                {
3410                                        $folder_name = explode($this->imap_delimiter,$name_box);
3411                                        $this->ldap = new ldap_functions();
3412                                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3413                                        {
3414                                                $folder_name[1] = $cn;
3415                                        }
3416                                        $folder_name = implode($this->imap_delimiter,$folder_name);
3417                                }
3418                                else
3419                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3420
3421                                if(!is_resource($mbox_stream))
3422                                        $mbox_stream = $this->open_mbox($name_box);
3423                                else
3424                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
3425
3426                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search
3427
3428                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3429
3430                                        foreach($all_criterias as $criteria_fixed)
3431                                        {
3432                                                $_filter = $criteria_fixed . substr($filter,4);
3433
3434                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
3435                                                // Testa aqui
3436                                                if($search_criteria) // && count($search_criteria) < $search_result_number)
3437                                                {
3438                                                        foreach($search_criteria as $new_search){
3439                                if ($search_result_number != '65536' && $sum == $search_result_number)
3440                                {
3441                                  return $retorno ? $sum . "=sumResults=" . $retorno : "none";
3442                                }
3443
3444                                                                $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");
3445                                                                if(!@strstr($retorno,$m_token))
3446                                {
3447                                    $retorno .= $m_token;
3448                                    $sum++;
3449                                }
3450                                                        }
3451                                                }
3452                                        }
3453                                }
3454                                else {
3455                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3456                                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
3457                                        {
3458                                if((!strpos($filter,"FLAGGED") === false) || (!strpos($filter,"UNFLAGGED") === false))
3459                                                {
3460                                        $num_msgs = imap_num_msg($mbox_stream);
3461                                                        $flagged_msgs = array();
3462                                                        for ($i=$num_msgs; $i>0; $i--)
3463                                                        {                                                               
3464                                                                $iuid = @imap_uid($this->mbox,$i);
3465                                                                $header = $this->get_header($iuid);                                                             
3466                                                                if(trim($header->Flagged))
3467                                                                {
3468                                                                        $flagged_msgs[$i] = $iuid;
3469                                                                }
3470                                                        }
3471                                                        if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
3472                                                        {
3473                                                                $arry_diff = array_diff($flagged_msgs,$search_criteria);
3474                                                                foreach($arry_diff as $msg)
3475                                                                {
3476                                                                        $search_criteria[] = $msg;
3477                                                                }
3478                                                        }
3479                                                        else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
3480                                                        {
3481                                                                $search_criteria = array_diff($search_criteria,$flagged_msgs);
3482                                                        }
3483                                                }
3484                                        }       
3485                                        if( is_array( $search_criteria) )
3486                                        {
3487                                                foreach($search_criteria as $new_search)
3488                                                {
3489                                                    if ($search_result_number != '65536' && $sum == $search_result_number)
3490                                                    {
3491                                                        return $retorno ? $sum . "=sumResults=" . $retorno : "none";
3492                                                    }
3493                                                    $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");
3494                                                    $sum++;
3495                                                }
3496                                        }
3497                                }
3498
3499//                                $acumulated_results += $sum;
3500//
3501//                                if ($search_result_number != '65536' && $acumulated_results >= $search_result_number)
3502//                                {
3503//                                    return "many results";
3504//                                }
3505                        }
3506                }
3507                if($mbox_stream)
3508                        imap_close($mbox_stream);
3509
3510                if ($retorno){
3511                    return $retorno;
3512                }
3513                else
3514                {
3515                    return 'none';
3516                }
3517                //return $retorno ? $retorno : "none";
3518        }
3519
3520        function get_msg($uid_msg,$name_box, $mbox_stream )
3521        {
3522                $header = $this->get_header($uid_msg);
3523                include_once("class.imap_attachment.inc.php");
3524                $imap_attachment = new imap_attachment();
3525                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3526                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3527                $flag = $header->Unseen
3528                        .$header->Recent
3529                        .$header->Flagged
3530                        .$header->Draft
3531                        .$header->Answered
3532                        .$header->Deleted
3533                        .$attachments;
3534
3535
3536                $subject = $this->decode_string($header->fetchsubject);
3537                $from = $header->from[0]->mailbox;
3538                if($header->from[0]->personal != "")
3539                        $from = $header->from[0]->personal;
3540                $ret_msg = $this->decode_string($from) . "--" . htmlentities(rawurlencode($subject)) . "--". gmdate("d/m/Y",$header ->udate + $this->functions->CalculateDateOffset())."--". $this->size_msg($header->Size) ."--". $flag;
3541                return $ret_msg;
3542        }
3543
3544
3545        function size_msg($size){
3546                $var = floor($size/1024);
3547                if($var >= 1){
3548                        return $var." kb";
3549                }else{
3550                        return $size ." b";
3551                }
3552        }
3553       
3554        function ob_array($the_object)
3555        {
3556           $the_array=array();
3557           if(!is_scalar($the_object))
3558           {
3559               foreach($the_object as $id => $object)
3560               {
3561                   if(is_scalar($object))
3562                   {
3563                       $the_array[$id]=$object;
3564                   }
3565                   else
3566                   {
3567                       $the_array[$id]=$this->ob_array($object);
3568                   }
3569               }
3570               return $the_array;
3571           }
3572           else
3573           {
3574               return $the_object;
3575           }
3576        }
3577
3578        function getacl()
3579        {
3580                $this->ldap = new ldap_functions();
3581
3582                $return = array();
3583                $mbox_stream = $this->open_mbox();
3584                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3585
3586                $i = 0;
3587                foreach ($mbox_acl as $user => $acl)
3588                {
3589                        if ($user != $this->username)
3590                        {
3591                                $return[$i]['uid'] = $user;
3592                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3593                        }
3594                        $i++;
3595                }
3596                return $return;
3597        }
3598
3599        function setacl($params)
3600        {
3601                $old_users = $this->getacl();
3602                if (!count($old_users))
3603                        $old_users = array();
3604
3605                $tmp_array = array();
3606                foreach ($old_users as $index => $user_info)
3607                {
3608                        $tmp_array[$index] = $user_info['uid'];
3609                }
3610                $old_users = $tmp_array;
3611
3612                $users = unserialize($params['users']);
3613                if (!count($users))
3614                        $users = array();
3615
3616                //$add_share = array_diff($users, $old_users);
3617                $remove_share = array_diff($old_users, $users);
3618
3619                $mbox_stream = $this->open_mbox();
3620
3621                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3622                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3623
3624                /*if (count($add_share))
3625                {
3626                        foreach ($add_share as $index=>$uid)
3627                        {
3628                        if (is_array($mailboxes_list))
3629                        {
3630                        foreach ($mailboxes_list as $key => $val)
3631                        {
3632                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3633                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3634                        }
3635                        }
3636                        }
3637                }*/
3638
3639                if (count($remove_share))
3640                {
3641                        foreach ($remove_share as $index=>$uid)
3642                        {
3643                        if (is_array($mailboxes_list))
3644                        {
3645                        foreach ($mailboxes_list as $key => $val)
3646                        {
3647                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3648                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3649                        }
3650                        }
3651                        }
3652                }
3653
3654                return true;
3655        }
3656
3657        function getaclfromuser($params)
3658        {
3659                $useracl = $params['user'];
3660
3661                $return = array();
3662                $return[$useracl] = 'false';
3663                $mbox_stream = $this->open_mbox();
3664                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3665
3666                foreach ($mbox_acl as $user => $acl)
3667                {
3668                        if (($user != $this->username) && ($user == $useracl))
3669                        {
3670                                $return[$user] = $acl;
3671                        }
3672                }
3673                return $return;
3674        }
3675
3676        function getacltouser($user)
3677        {
3678                $return = array();
3679                $mbox_stream = $this->open_mbox();
3680                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3681                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3682                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3683                if(substr($user,0,4) != 'user')
3684                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3685                else
3686                  $mbox_acl = imap_getacl($mbox_stream, $user);
3687                return $mbox_acl[$this->username];
3688        }
3689
3690
3691        function setaclfromuser($params)
3692        {
3693                $user = $params['user'];
3694                $acl = $params['acl'];
3695
3696                $mbox_stream = $this->open_mbox();
3697
3698                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3699                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3700
3701                if (is_array($mailboxes_list))
3702                {
3703                        foreach ($mailboxes_list as $key => $val)
3704                        {
3705                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3706                                $folder = str_replace("&-", "&", $folder);
3707                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3708                                {
3709                                        $return = imap_last_error();
3710                                }
3711                        }
3712                }
3713                if (isset($return))
3714                        return $return;
3715                else
3716                        return true;
3717        }
3718
3719        function download_attachment($msg,$msgno)
3720        {
3721                $array_parts_attachments = array();
3722                //$array_parts_attachments['names'] = '';
3723                include_once("class.imap_attachment.inc.php");
3724                $imap_attachment = new imap_attachment();
3725
3726                if (count($msg->fname[$msgno]) > 0)
3727                {
3728                        $i = 0;
3729                        foreach ($msg->fname[$msgno] as $index=>$fname)
3730                        {
3731                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3732                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
3733                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3734                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3735                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3736                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3737                                $i++;
3738                        }
3739                }
3740                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3741                return $array_parts_attachments;
3742        }
3743
3744        function spam($params)
3745        {
3746                $is_spam = $params['spam'];
3747                $folder = $params['folder'];
3748                $mbox_stream = $this->open_mbox($folder);
3749                $msgs_number = explode(',',$params['msgs_number']);
3750
3751                foreach($msgs_number as $msg_number) {
3752                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3753                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3754                        $body = imap_body($mbox_stream, $imap_msg_number);
3755                        $msg = $header . $body;
3756                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3757                        $username = $this->username;
3758                        strtok($email, '@');
3759                        $domain = strtok('@');
3760
3761                        //Encontrar a assinatura do dspam no cabecalho
3762                        $v = explode("\r\n", $header);
3763                        foreach ($v as $linha){
3764                                if (eregi("^Message-ID", $linha)) {
3765                                        $args = explode(" ", $linha);
3766                                        $msg_id = "'$args[1]'";
3767                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
3768                                        $args = explode(" ",$linha);
3769                                        $signature = $args[1];
3770                                }
3771                        }
3772
3773                        // Seleciona qual comando a ser executado
3774                        switch($is_spam){
3775                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
3776                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
3777                        }
3778
3779                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3780                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
3781                        system($cmd);
3782                }
3783                imap_close($mbox_stream);
3784                return false;
3785        }
3786        function get_header($msg_number){
3787                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3788                if (!is_object($header))
3789                        return false;
3790
3791                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3792                        $flag = preg_match('/importance *: *(.*)\r/i',
3793                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3794                                                ,$importance);
3795                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3796                }
3797
3798                return $header;
3799        }
3800
3801//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
3802///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.
3803
3804    function insert_email($source,$folder,$timestamp){
3805        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3806        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
3807        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3808        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
3809        $imap_options = '/notls/novalidate-cert';
3810        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3811        if(imap_last_error())
3812        {
3813            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3814       }
3815        if($timestamp){
3816            $tempDir = ini_get("session.save_path");
3817            $file = $tempDir."imap_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
3818                $f = fopen($file,"w");
3819                fputs($f,base64_encode($source));
3820            fclose($f);
3821            $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);
3822            $return['command']=exec(escapeshellcmd($command));
3823        }else{
3824            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3825        }
3826        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3827        $return['msg_no'] = $status->uidnext - 1;
3828                $return['error'] = imap_last_error();
3829        if($mbox_stream)
3830                        imap_close($mbox_stream);
3831        return $return;
3832
3833    }
3834
3835    function show_decript($params,$dec=0){
3836       
3837        $source = $params['source'];
3838        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3839
3840        if ($dec == 0)
3841        {
3842            $source = str_replace(" ", "+", $source,$i);
3843            if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3844                if(!$source = base64_decode($source,true))
3845                    return "error ".$source."Espaços ".$i;
3846
3847            }
3848            else {
3849                if(!$source = base64_decode($source))
3850                    return "error ".$source."Espaços ".$i;
3851            }
3852        }
3853        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3854
3855                $get['msg_number'] = $insert['msg_no'];
3856                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
3857                $return = $this->get_info_msg($get);
3858                $get['msg_number'] = $params['ID'];
3859                $get['msg_folder'] = $params['folder'];
3860                $tmp = $this->get_info_msg($get);
3861                if(!$tmp['status_get_msg_info'])
3862                {
3863                        $return['msg_day']=$tmp['msg_day'];
3864                        $return['msg_hour']=$tmp['msg_hour'];
3865                        $return['fulldate']=$tmp['fulldate'];
3866                        $return['smalldate']=$tmp['smalldate'];
3867                }
3868                else
3869                {
3870                        $return['msg_day']='';
3871                        $return['msg_hour']='';
3872                        $return['fulldate']='';
3873                        $return['smalldate']='';
3874                }
3875        $return['msg_no'] =$insert['msg_no'];
3876        $return['error'] = $insert['error'];
3877        $return['folder'] = $params['folder'];
3878        //$return['acls'] = $insert['acls'];
3879        $return['original_ID'] =  $params['ID'];
3880
3881        return $return;
3882
3883    }
3884
3885//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
3886//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
3887
3888    function treat_base64_from_post($source){
3889            $offset = 0;
3890            do
3891            {
3892                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
3893                    {
3894                            $inicio = strpos($source, "\n\r", $inicio);
3895                            $fim = strpos($source, '--', $inicio);
3896                            if(!$fim)
3897                                    $fim = strpos($source,"\n\r", $inicio);
3898                            $length = $fim-$inicio;
3899                            $parte = substr( $source,$inicio,$length-1);
3900                            $parte = str_replace(" ", "+", $parte);
3901                            $source = substr_replace($source, $parte, $inicio, $length-1);
3902                    }
3903                    if($offset > $inicio)
3904                    $offset=FALSE;
3905                    else
3906                    $offset = $inicio;
3907            }
3908            while($offset);
3909            return $source;
3910    }
3911
3912//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.
3913
3914    function unarchive_mail($params)
3915    {
3916        $dest_folder = $params['folder'];
3917        $sources = explode("#@#@#@",$params['source']);
3918        $timestamps = explode("#@#@#@",$params['timestamp']);
3919        foreach($sources as $index=>$src) {
3920                        if($src!=""){
3921                                $source = $this->treat_base64_from_post($src);
3922                                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index]);
3923                        }
3924                }
3925        return $insert;
3926    }
3927
3928    function download_all_local_attachments($params)
3929    {
3930        $source = $params['source'];
3931        $source = $this->treat_base64_from_post($source);
3932        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3933        $exporteml = new ExportEml();
3934        $params['num_msg']=$insert['msg_no'];
3935        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
3936        return $exporteml->download_all_attachments($params);
3937    }
3938    function get_quota_folders(){
3939
3940            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
3941            include_once("class.imapfp.inc.php");           
3942            $imapfp = new imapfp();
3943
3944            if(!$imapfp->open($this->imap_server,$this->imap_port))
3945                    return $imapfp->get_error();             
3946            if (!$imapfp->login( $this->username,$this->password ))
3947                    return $imapfp->get_error();
3948
3949            $response_array = $imapfp->get_mailboxes_size();
3950            if ($imapfp->error)
3951                    return $imapfp->get_error();
3952
3953            $data = array();
3954            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
3955            $data["quota_root"] = $quota_root;
3956
3957            foreach ($response_array as $idx=>$line) {
3958                    $line2 = str_replace('"', "", $line);
3959                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
3960                    list($folder,$size) = explode(";",$line2);
3961                    $size = str_replace(")","",$size);
3962                    $quotaPercent = (($size / 1048576) / $data["quota_root"]["quota_limit"])*100;
3963                    if ($size < 1048576 && $size > 1024)
3964                            $quota_used = round($size / 1024, 0).' Kb';
3965                    else if($size > 1024)
3966                            $quota_used = round($size / (1024*1024), 1).' Mb';
3967                    else
3968                            $quota_used = $size." b";
3969                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
3970                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
3971                            $folder = $this->functions->getLang("Inbox");
3972                    }
3973                    else
3974                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
3975
3976                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
3977            }
3978            $imapfp->close();
3979            return $data;
3980    } 
3981}
3982?>
Note: See TracBrowser for help on using the repository browser.