source: branches/2.1/expressoMail1_2/inc/class.imap_functions.inc.php @ 2456

Revision 2456, 136.5 KB checked in by rodsouza, 14 years ago (diff)

Ticket #1029 - Removendo expressão regular que tratava link notes.

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