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

Revision 1797, 124.3 KB checked in by niltonneto, 14 years ago (diff)

Ticket #691 - Corrigido problema de mensagens com tag SPAN vazias.

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