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

Revision 1638, 128.0 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #753 - Efetuada alteração para salvar Cco no rascunho.....

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