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

Revision 2417, 142.0 KB checked in by amuller, 14 years ago (diff)

Ticket #1026 - Fechando a sessão em cada requisição do inicio do expressoMail

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