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

Revision 1792, 132.5 KB checked in by rodsouza, 14 years ago (diff)

Ticket #810 - Removida transformação de 7bits em quoted-printable caracteres.

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