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

Revision 3038, 127.0 KB checked in by niltonneto, 14 years ago (diff)

Ticket #1111 - Adicionado estilo white-space para corrigir problema no Firefox 2.0.

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