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

Revision 2408, 141.7 KB checked in by rodsouza, 14 years ago (diff)

Ticket #1025 - Removido a expressão regular que busca por 'new_message_to' no momento de enviar o e-mail.

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