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

Revision 1384, 123.9 KB checked in by niltonneto, 15 years ago (diff)

Ticket #528 - Adição de novo método para correção desse ticket.

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