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

Revision 1518, 123.8 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #656 - funcionalidade de arquivamento programado no expressoMail

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