source: branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 3106

Revision 3106, 137.1 KB checked in by amuller, 14 years ago (diff)

Ticket #974 - Arruma problema de data quando atualiza a pasta

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