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

Revision 1828, 124.4 KB checked in by niltonneto, 14 years ago (diff)

Ticket #788 - Corrigido problema no método replace_links (regexp).

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