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

Revision 1059, 122.5 KB checked in by amuller, 15 years ago (diff)

Ticket #559 - Removendo inclusão de header.inc.php nas classes e colocando no controler

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