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

Revision 1482, 124.1 KB checked in by niltonneto, 14 years ago (diff)

Ticket #672 - Correção crítica na RegExp? que transforma texto URL em link.

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