source: branches/2.0/expressoMail1_2/inc/class.imap_functions.inc.php @ 3547

Revision 3547, 126.5 KB checked in by wmerlotto, 13 years ago (diff)

Ticket #1389 - Os espaços e tabssão removidos do assunto do e-mail.

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