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

Revision 2480, 140.1 KB checked in by amuller, 14 years ago (diff)

Ticket #1026 - Deixando toda a classe imap concorrente

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