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

Revision 1965, 135.0 KB checked in by wmerlotto, 14 years ago (diff)

Ticket #900 - Adicionando funcionalidade de limpar a pasta Spam

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