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

Revision 1824, 134.0 KB checked in by wmerlotto, 14 years ago (diff)

Ticket #557 - Foi alterado o cyrus delimiter de hardcoded para dinâmico.

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