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

Revision 3024, 138.0 KB checked in by amuller, 14 years ago (diff)

Ticket #1079 - corrige problema do sugestões text/plain

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