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

Revision 3049, 137.9 KB checked in by amuller, 14 years ago (diff)

Ticket #1047 - Não puxar o corpo quando a preferência não está habilitada

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