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

Revision 1752, 132.6 KB checked in by rafaelraymundo, 15 years ago (diff)

Ticket #703 - Preview das mensagens configuravel. Por tool-tip e coluna de assunto

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