source: branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 4626

Revision 4626, 151.3 KB checked in by roberto.santosjunior, 13 years ago (diff)

Ticket #2028 - Erro ao desanexar mensagem com encoding base64

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