source: trunk/expressoMail1_2/inc/class.imap_functions.inc.php @ 3131

Revision 3131, 137.9 KB checked in by niltonneto, 14 years ago (diff)

Ticket #1111 - Corrigido problema ao editar/imprimir mensagens com tags <pre>.

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