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

Revision 3499, 143.0 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1322 - Data incorreta nas mensagens na caixa de entrada (local e mobile).

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