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

Revision 2360, 142.2 KB checked in by amuller, 14 years ago (diff)

Ticket #1008 - Adicionando informações sobre licenças

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