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

Revision 3527, 143.2 KB checked in by rodsouza, 13 years ago (diff)

Ticket #966 - Adicionando opção de 'Responder a'

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