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

Revision 1912, 135.3 KB checked in by valmir.sena, 14 years ago (diff)

Ticket #858 - Alterar o comportamento do envio de mensagens por um usuário de uma conta compartilhada

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