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

Revision 1380, 123.6 KB checked in by amuller, 15 years ago (diff)

Ticket #635 - Corrigindo, retirando o tipo gif da normalização de imagens

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