source: trunk/expressoMail1_2/inc/class.imap_functions.inc.php @ 1382

Revision 1382, 124.0 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #457 - Ajuste na função get_info_msgs retornando o flag de não-lido

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