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

Revision 3399, 141.0 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #847 - Ao desarquivar um email o horario diminui uma hora. Solucao da revisao [2314] reaplicada.

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