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

Revision 1817, 133.9 KB checked in by wmerlotto, 14 years ago (diff)

Ticket #557 - Aplicado (e modificado para suportar internacionalizacao) o patch de ordenacao de pastas

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