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

Revision 1707, 128.2 KB checked in by amuller, 14 years ago (diff)

Ticket #788 - Substituição da expressão regular para varias mais legíveis

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