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

Revision 5153, 151.4 KB checked in by niltonneto, 12 years ago (diff)

Ticket #2309 - Corrigido problema de warnings excessivos gerados pela função substr().

  • 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','base',
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                $limit = strlen($body).strlen($body);
1409                ini_set( 'pcre.backtrack_limit', $limit );
1410               
1411
1412                /*
1413                // PHP 5.3
1414                $replace = function( $matches )
1415                {
1416                        if ( $matches[ 1 ] )
1417                                return $matches[ 0 ];
1418
1419                        $url = ( $matches[ 2 ] ) ? $matches[ 2 ] : 'http';
1420                        $url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";
1421                        return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";
1422                };
1423                $body = preg_replace_callback( $pattern, $replace, $body );
1424                 */
1425
1426                // PHP 5.2.x - Remover assim que possível
1427                $body = preg_replace_callback( $pattern,
1428                        create_function(
1429                                '$matches',
1430                                'if ( $matches[ 1 ] ) return $matches[ 0 ];'
1431                                . '$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : "http";'
1432                                . '$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";'
1433                                . 'return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";'
1434                        ), $body
1435                );
1436                ini_set( 'pcre.backtrack_limit', 100000 );
1437                // E-mail address in the text should create a new e-mail on ExpressoMail
1438                $pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im';
1439                $replacement = '$1<a href="mailto:$2">$2</a>$3';
1440                $body = preg_replace( $pattern, $replacement, $body );
1441
1442                return $body;
1443        }
1444
1445        function get_signature($msg, $msg_number, $msg_folder)
1446        {
1447            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1448            include_once("class.db_functions.inc.php");
1449            foreach ($msg->file_type[$msg_number] as $index => $file_type)
1450            {
1451                $sign = array();
1452                $temp = $this->get_info_head_msg($msg_number);
1453                if($temp['ContentType'] =='normal') return $sign;
1454                $file_type = strtolower($file_type);
1455                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
1456                {
1457                    if ($temp['ContentType'] == 'signature')
1458                    {
1459                        if(!$this->mbox || !is_resource($this->mbox))
1460                        $this->mbox = $this->open_mbox($msg_folder);
1461
1462                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
1463
1464                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1465                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
1466
1467                        $certificado = new certificadoB();
1468                        $validade = $certificado->verificar($imap_msg);
1469                                        $sign[] = $certificado->msg_sem_assinatura;
1470                        if ($certificado->apresentado)
1471                        {
1472                            $from = $header->from;
1473                            foreach ($from as $id => $object)
1474                            {
1475                                $fromname = $object->personal;
1476                                $fromaddress = $object->mailbox . "@" . $object->host;
1477                            }
1478                            foreach ($certificado->erros_ssl as $item)
1479                            {
1480                                $sign[] = $item . "#@#";
1481                            }
1482
1483                            if (count($certificado->erros_ssl) < 1)
1484                            {
1485                                $check_msg = 'Message untouched';
1486                                if(strtoupper($fromaddress) == strtoupper($certificado->dados['EMAIL']))
1487                                {
1488                                    $check_msg .= ' and authentic###';
1489                                }
1490                                else
1491                                {
1492                                    $check_msg .= ' with signer different from sender#@#';
1493                                }
1494                                $sign[] = $check_msg;
1495                            }
1496                                               
1497                            $sign[] = 'Message signed by: ###' . $certificado->dados['NOME'];
1498                            $sign[] = 'Certificate email: ###' . $certificado->dados['EMAIL'];
1499                            $sign[] = 'Mail from: ###' . $fromaddress;
1500                            $sign[] = 'Certificate Authority: ###' . $certificado->dados['EMISSOR'];
1501                            $sign[] = 'Validity of certificate: ###' . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
1502                            $sign[] = 'Message date: ###' . $header->Date;
1503
1504                            $cert = openssl_x509_parse($certificado->cert_assinante);
1505
1506                            $sign_alert = array();
1507                            $sign_alert[] = 'Certificate Owner###:\n';
1508                            $sign_alert[] = 'Common Name (CN)###  ' . $cert[subject]['CN'] .  '\n';
1509                            $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1510                            $sign_alert[]= 'Organization (O)###  ' . $cert[subject]['O'] .  '\n';
1511                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[subject]['OU'][0] .  '\n';
1512                            //$sign_alert[] = 'Serial Number### ' . $cert['serialNumber'] . '\n';
1513                            $sign_alert[] = 'Personal Data###:' . '\n';
1514                            $sign_alert[] = 'Birthday### ' . $X .  '\n';
1515                            $sign_alert[]= 'Fiscal Id### ' . $certificado->dados['CPF'] .  '\n';
1516                            $sign_alert[]= 'Identification### ' . $certificado->dados['RG'] .  '\n\n';
1517                            $sign_alert[]= 'Certificate Issuer###:\n';
1518                            $sign_alert[]= 'Common Name (CN)###  ' . $cert[issuer]['CN'] . '\n';
1519                            $sign_alert[]= 'Organization (O)###  ' . $cert[issuer]['O'] .  '\n';
1520                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[issuer]['OU'][0] .  '\n\n';
1521                            $sign_alert[]= 'Validity###:\n';
1522                            $H = data_hora($cert[validFrom]);
1523                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1524                            $sign_alert[]= 'Valid From### ' . $X .  '\n';
1525                            $H = data_hora($cert[validTo]);
1526                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1527                            $sign_alert[]= 'Valid Until### ' . $X;
1528                            $sign[] = $sign_alert;
1529
1530                            $this->db = new db_functions();
1531                           
1532                            // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
1533                            if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
1534                                $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
1535                        }
1536                        else
1537                        {
1538                            $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
1539                            foreach($certificado->erros_ssl as $item)
1540                                $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
1541                        }
1542                    }
1543                }
1544            }
1545            return $sign;
1546        }
1547
1548        function get_thumbs($msg, $msg_number, $msg_folder)
1549        {
1550                $thumbs_array = array();
1551                $i = 0;
1552        foreach ($msg->file_type[$msg_number] as $index => $file_type)
1553        {
1554                $file_type = strtolower($file_type);
1555                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
1556                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
1557                                $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].">";
1558                                $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>";
1559                                        $thumbs_array[] = $href;
1560                        }
1561                        $i++;
1562                }
1563        }
1564        return $thumbs_array;
1565        }
1566
1567        /*function delete_msg($params)
1568        {
1569                $folder = $params['folder'];
1570                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
1571
1572                $mbox_stream = $this->open_mbox($folder);
1573
1574                foreach ($msgs_to_delete as $msg_number){
1575                        imap_delete($mbox_stream, $msg_number, FT_UID);
1576                }
1577                imap_close($mbox_stream, CL_EXPUNGE);
1578                return $params['msgs_to_delete'];
1579        }*/
1580
1581        // Novo
1582        function delete_msgs($params)
1583        {
1584
1585                $folder = $params['folder'];
1586                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
1587                $msgs_number = explode(",",$params['msgs_number']);
1588                $border_ID = $params['border_ID'];
1589
1590                $return = array();
1591
1592                if ($params['get_previous_msg']){
1593                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1594                        // Fix problem in unserialize function JS.
1595                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1596                }
1597
1598                //$mbox_stream = $this->open_mbox($folder);
1599                $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()))));
1600
1601                foreach ($msgs_number as $msg_number)
1602                {
1603                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1604                                $return['msgs_number'][] = $msg_number;
1605                }
1606
1607                $return['folder'] = $folder;
1608                $return['border_ID'] = $border_ID;
1609
1610                if($mbox_stream)
1611                        imap_close($mbox_stream, CL_EXPUNGE);
1612                return $return;
1613        }
1614
1615
1616        function refresh($params)
1617        {
1618
1619                $folder = $params['folder'];
1620                $msg_range_begin = $params['msg_range_begin'];
1621                $msg_range_end = $params['msg_range_end'];
1622                $msgs_existent = $params['msgs_existent'];
1623                $sort_box_type = $params['sort_box_type'];
1624                $sort_box_reverse = $params['sort_box_reverse'];
1625                $msgs_in_the_server = array();
1626                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1627                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1628                $msgs_in_the_server = array_keys($msgs_in_the_server);
1629                if(!count($msgs_in_the_server))
1630                        return array();
1631
1632                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
1633                $msgs_in_the_client = explode(",", $msgs_existent);
1634
1635                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
1636                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
1637
1638                $msgs_to_exec = array();
1639                foreach($msg_to_insert as $msg_number)
1640                        $msgs_to_exec[] = $msg_number;
1641                sort($msgs_to_exec);
1642
1643                $return = array();
1644                $return['new_msgs'] = imap_num_recent($this->mbox);
1645                $i = 0;
1646                foreach($msgs_to_exec as $msg_number)
1647                {
1648                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
1649                        * atributos do cabeçalho. Como eu preciso do atributo Importance
1650                        * para saber se o email é importante ou não, uso abaixo a função
1651                        * imap_fetchheader e busco o atributo importance nela para passar
1652                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1653                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1654                        * não preciso reimplementar o método utilizando o fetchheader.
1655                        */
1656   
1657                        $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1658                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
1659                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
1660
1661                        $msg_sample = $this->get_msg_sample($msg_number);
1662                        $return[$i]['msg_sample'] = $msg_sample;
1663
1664                        $header = $this->get_header($msg_number);
1665                        if (!is_object($header))
1666                                continue;
1667
1668                        $return[$i]['msg_number']       = $msg_number;
1669                       
1670                        //get the next msg number to append this msg in the view in a correct place
1671                        $msg_key_position = array_search($msg_number, $msgs_in_the_server);
1672                       
1673                        if($msg_key_position !== false && array_key_exists($msg_key_position + 1) !== false)
1674                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position + 1];
1675
1676                        $return[$i]['msg_folder']       = $folder;
1677                        // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1678                        $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
1679                        $return[$i]['Recent']           = $header->Recent;
1680                        $return[$i]['Unseen']           = $header->Unseen;
1681                        $return[$i]['Answered']         = $header->Answered;
1682                        $return[$i]['Deleted']          = $header->Deleted;
1683                        $return[$i]['Draft']            = $header->Draft;
1684                        $return[$i]['Flagged']          = $header->Flagged;
1685
1686                        $return[$i]['udate'] = $header->udate;
1687               
1688                        $from = $header->from;
1689                        $return[$i]['from'] = array();
1690                        $tmp = imap_mime_header_decode($from[0]->personal);
1691                        $return[$i]['from']['name'] = $tmp[0]->text;
1692                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
1693                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
1694                        if(!$return[$i]['from']['name'])
1695                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
1696
1697                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1698                        $return[$i]['toaddress'] = '';
1699                        foreach ($toaddress as $tmp)
1700                                $return[$i]['toaddress'] .= $tmp->text;*/
1701                        $to = $header->to;
1702                        $return[$i]['to'] = array();
1703                        $tmp = imap_mime_header_decode($to[0]->personal);
1704                        $return[$i]['to']['name'] = $tmp[0]->text;
1705                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1706                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
1707                        $cc = $header->cc;
1708                        if ( ($cc) && (!$return[$i]['to']['name']) ){
1709                                $return[$i]['to']['name'] =  $cc[0]->personal;
1710                                $return[$i]['to']['email'] = $cc[0]->mailbox . "@" . $cc[0]->host;
1711                        }
1712                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1713
1714                        $return[$i]['Size'] = $header->Size;
1715                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
1716
1717                        $return[$i]['attachment'] = array();
1718                        if (!isset($imap_attachment))
1719                        {
1720                                include_once("class.imap_attachment.inc.php");
1721                                $imap_attachment = new imap_attachment();
1722                        }
1723                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
1724                        $i++;
1725                }
1726                $return['quota'] = $this->get_quota(array('folder_id' => $folder));
1727                $return['sort_box_type'] = $params['sort_box_type'];
1728                if(!$this->mbox || !is_resource($this->mbox))
1729                {
1730                    $this->open_mbox($folder);
1731                }
1732
1733                $return['msgs_to_delete'] = $msg_to_delete;
1734                $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
1735                if($this->mbox && is_resource($this->mbox))
1736                        imap_close($this->mbox);
1737
1738                return $return;
1739        }
1740
1741     /**
1742     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1743     * assinado ou cifrado.
1744     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1745     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1746     * @param $msg_number O número da mesagem
1747     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1748     */
1749    function getMessageType($msg_number, $headers = false){
1750            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1751            $contentType = "normal";
1752            if (!$headers){
1753                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1754            }
1755           
1756            if (preg_match("/pkcs7-signature/i", $headers) == 1){
1757                $contentType = "signature";
1758            } else if (preg_match("/pkcs7-mime/i", $headers) == 1){
1759                $contentType = testa_p7m( imap_body($this->mbox, imap_msgno($this->mbox, $msg_number)) );
1760            }
1761
1762            return $contentType;
1763    }
1764
1765         /**
1766     * Metodo que retorna todas as pastas do usuario logado.
1767     * @param $params array opcional para repassar os argumentos ao metodo.
1768     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
1769     * excluindo as compartilhadas para ele.
1770     * Se usar $params['folderType'] = "default" irá retornar somente as pastas defaults
1771     * Se usar $params['folderType'] = "personal" irá retornar somente as pastas pessoais
1772     * Se usar $params['folderType'] = null irá retornar todas as pastas
1773     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
1774     * folder_id, folder_name, folder_parent e folder_hasChildren.
1775     */
1776        function get_folders_list($params = null)
1777        {
1778                $mbox_stream = $this->open_mbox();
1779                if($params && $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
1780                        $this->delete_mailbox(array("del_past" => "INBOX/decifradas"));
1781                }
1782
1783                $inbox  = 'INBOX';
1784                $trash  = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
1785                $drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
1786                $spam   = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
1787                $sent   = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
1788                $uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'];
1789                // Free others requests
1790                session_write_close();
1791
1792                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
1793               
1794                if ( $params && $params['noSharedFolders'] )
1795                        $folders_list = array_merge(imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ), imap_getmailboxes($mbox_stream, $serverString, 'INBOX/*' ) );
1796                else
1797                        $folders_list = imap_getmailboxes($mbox_stream, $serverString, '*' );
1798
1799                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1800
1801                $tmp = array();
1802                $resultMine = array();
1803                $resultDefault = array();
1804
1805                if ( is_array($folders_list) )
1806                {
1807                        reset($folders_list);
1808                        $this->ldap = new ldap_functions();
1809
1810                        $i = 0;
1811
1812                        while (list($key, $val) = each($folders_list))
1813                        {
1814                            $status = imap_status( $mbox_stream, $val->name, SA_UNSEEN );
1815                           
1816                            $tmp_folder_id = explode("}", $val->name );
1817
1818                            $folderUser = trim( strpos( $tmp_folder_id[1], $this->imap_delimiter , 5 ) );
1819
1820                                                        if($folderUser > 0)
1821                                $folderUser = trim( substr( $tmp_folder_id[1], 0, $folderUser ) );
1822
1823                            $Permission = true;
1824                           
1825                            if( $folderUser != "INBOX" && $folderUser != "" )
1826                            {   
1827                               $Permission = imap_getacl( $mbox_stream, $folderUser );
1828                            }
1829                           
1830                            if( $Permission )     
1831                            {   
1832                                $tmp_folder_id[1] = mb_convert_encoding( $tmp_folder_id[1], "ISO-8859-1", "UTF7-IMAP" );
1833
1834                                if( $tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas')
1835                                {
1836                                    //error_log('passou', 3,'/tmp/imap_get_list.log');
1837                                    //imap_deletemailbox($mbox_stream,imap_utf7_encode("{".$this->imap_server."}".'INBOX/decifradas'));
1838                                    continue;
1839                                }
1840                               
1841                                $result[$i]['folder_unseen'] = $status->unseen;
1842                                $folder_id = $tmp_folder_id[1];
1843                                $result[$i]['folder_id'] = $folder_id;
1844
1845                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1846                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1847                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1848
1849                                if ($uid2cn && substr($folder_id,0,4) == 'user')
1850                                {
1851                                    //$this->ldap = new ldap_functions();
1852                                    if ($cn = $this->ldap->uid2cn($result[$i]['folder_name']))
1853                                    {
1854                                        $result[$i]['folder_name'] = $cn;
1855                                    }
1856                                }
1857
1858                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1859                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
1860
1861                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1862                                    $result[$i]['folder_hasChildren'] = 1;
1863                                else
1864                                    $result[$i]['folder_hasChildren'] = 0;
1865
1866                                switch ($tmp_folder_id[1])
1867                                {
1868                                    case $inbox:
1869                                    case $sent:
1870                                    case $drafts:
1871                                    case $spam:
1872                                    case $trash:
1873                                        $resultDefault[]=$result[$i];
1874                                        break;
1875                                    default:
1876                                        $resultMine[]=$result[$i];
1877                                }
1878                            }   
1879                           
1880                            $i++;
1881                        }
1882                }
1883
1884                if ( $params && !$params['noQuotaInfo'] ) {
1885                        //Get quota info of current folder
1886                        $current_folder = "INBOX";
1887                        if($params && $params['folder'])
1888                                $current_folder = $params['folder'];
1889
1890                        $arr_quota_info = $this->get_quota(array('folder_id' => $current_folder));
1891                } else {
1892                        $arr_quota_info = array();
1893                }
1894
1895                // Sorting resultMine
1896                foreach ($resultMine as $folder_info)
1897                {
1898                        $array_tmp[] = $folder_info['folder_id'];
1899                }
1900
1901                natcasesort($array_tmp);
1902               
1903                $result2 = array();
1904
1905                foreach ($array_tmp as $key => $folder_id)
1906                {
1907                        $result2[] = $resultMine[$key];
1908                }
1909               
1910                // Sorting resultDefault
1911                foreach ($resultDefault as $key => $folder_id)
1912                {
1913                        switch ($resultDefault[$key]['folder_id']) {
1914                                case $inbox:
1915                                        $resultDefault2[0] = $resultDefault[$key];
1916                                        break;
1917                                case $sent:
1918                                        $resultDefault2[1] = $resultDefault[$key];
1919                                        break;
1920                                case $drafts:
1921                                        $resultDefault2[2] = $resultDefault[$key];
1922                                        break;
1923                                case $spam:
1924                                        $resultDefault2[3] = $resultDefault[$key];
1925                                        break;
1926                                case $trash:
1927                                        $resultDefault2[4] = $resultDefault[$key];
1928                                        break;
1929                        }
1930                }
1931               
1932                if ( $params && $params['folderType'] && $params['folderType'] == 'default' )
1933                        return array_merge($resultDefault2, $arr_quota_info);
1934
1935                if ( $params && $params['folderType'] && $params['folderType'] == 'personal' )
1936                        return array_merge($result2, $arr_quota_info);
1937
1938                // Merge default folders and personal
1939                $result2 = array_merge($resultDefault2, $result2);
1940               
1941                return array_merge($result2, $arr_quota_info);
1942        }
1943
1944        function create_mailbox($arr)
1945        {
1946                $namebox        = $arr['newp'];
1947                $mbox_stream = $this->open_mbox();
1948                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1949                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
1950
1951                $result = "Ok";
1952                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
1953                {
1954                        $result = implode("<br />\n", imap_errors());
1955                }
1956
1957                if($mbox_stream)
1958                        imap_close($mbox_stream);
1959
1960                return $result;
1961
1962        }
1963
1964        function create_extra_mailbox($arr)
1965        {
1966                $nameboxs = explode(";",$arr['nw_folders']);
1967                $result = "";
1968                $mbox_stream = $this->open_mbox();
1969                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1970                foreach($nameboxs as $key=>$tmp){
1971                        if($tmp != ""){
1972                                $to_create_array = explode($this->imap_delimiter, $tmp);
1973                                array_pop(&$to_create_array);
1974                                $folder = array();
1975                                foreach($to_create_array as $k=>$to_create){
1976                                        $folder[] = $to_create;
1977                                        if($to_create != 'INBOX') {
1978                                                $tmp = implode($this->imap_delimiter, $folder);
1979                                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1980                                                        $result = implode("<br />\n", imap_errors());
1981                                                        if("Mailbox already exists" != $result) {
1982                                                                imap_close($mbox_stream);
1983                                                                return $result;
1984                                                        }
1985                                                }
1986                                        }
1987                                }
1988                        }
1989                }
1990                if($mbox_stream)
1991                        imap_close($mbox_stream);
1992                return true;
1993        }
1994
1995        function delete_mailbox($arr)
1996        {
1997                $namebox = $arr['del_past'];
1998                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1999                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
2000                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
2001
2002                $result = "Ok";
2003                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
2004                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
2005                {
2006                        $result = implode("<br />\n", imap_errors());
2007                }
2008                /*
2009                if($mbox_stream)
2010                        imap_close($mbox_stream);
2011                */
2012                return $result;
2013        }
2014
2015        function ren_mailbox($arr)
2016        {
2017                $namebox = $arr['current'];
2018                $new_box = $arr['rename'];
2019                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2020                $mbox_stream = $this->open_mbox();
2021                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
2022
2023                $result = "Ok";
2024                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
2025                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
2026
2027                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
2028                {
2029                        $result = imap_errors();
2030                }
2031                if($mbox_stream)
2032                        imap_close($mbox_stream);
2033                return $result;
2034
2035        }
2036
2037        function get_num_msgs($params)
2038        {
2039                $folder = $params['folder'];
2040                if(!$this->mbox || !is_resource($this->mbox)) {
2041                        $this->mbox = $this->open_mbox($folder);
2042                        if(!$this->mbox || !is_resource($this->mbox))
2043                        return imap_last_error();
2044                }
2045                $num_msgs = imap_num_msg($this->mbox);
2046                if($this->mbox && is_resource($this->mbox))
2047                        imap_close($this->mbox);
2048
2049                return $num_msgs;
2050        }
2051
2052        function folder_exists($folder){
2053                $mbox =  $this->open_mbox();
2054                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";           
2055                $list = imap_getmailboxes($mbox,$serverString, $folder);
2056                $return = is_array($list);             
2057                imap_close($mbox);
2058                return $return;
2059        }
2060       
2061        function send_mail($params)
2062        {
2063                include_once("class.phpmailer.php");
2064                $mail = new PHPMailer();
2065                include_once("class.db_functions.inc.php");
2066                $db = new db_functions();
2067                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
2068                ##
2069                # @AUTHOR Rodrigo Souza dos Santos
2070                # @DATE 2008/09/17$fileName
2071                # @BRIEF Checks if the user has permission to send an email with the email address used.
2072                ##
2073                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
2074                {
2075                        $deny = true;
2076                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
2077                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
2078                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
2079
2080                        if ( $deny )
2081                                return "The server denied your request to send a mail, you cannot use this mail address.";
2082                }
2083
2084                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
2085                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
2086                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
2087                $replytoaddress = $params['input_replyto'];
2088                $subject = $params['input_subject'];
2089                $msg_uid = $params['msg_id'];
2090                $return_receipt = $params['input_return_receipt'];
2091                $is_important = $params['input_important_message'];
2092        $encrypt = $params['input_return_cripto'];
2093                $signed = $params['input_return_digital'];
2094
2095                if($params['smime'])
2096        {
2097            $body = $params['smime'];
2098            $mail->SMIME = true;
2099            // A MSG assinada deve ser testada neste ponto.
2100            // Testar o certificado e a integridade da msg....
2101            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2102            $erros_acumulados = '';
2103            $certificado = new certificadoB();
2104            $validade = $certificado->verificar($body);
2105            if(!$validade)
2106            {
2107                foreach($certificado->erros_ssl as $linha_erro)
2108                {
2109                    $erros_acumulados .= $linha_erro;
2110                }
2111            }
2112            else
2113            {
2114                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
2115                if ($certificado->apresentado)
2116                {
2117                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
2118                    if($certificado->dados['CPF'] != $this->username) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
2119                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
2120                }
2121                else
2122                {
2123                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
2124                }
2125            }
2126            if(!$erros_acumulados =='')
2127            {
2128                return $erros_acumulados;
2129            }
2130        }
2131        else
2132        {
2133            $body = $params['body'];
2134            //Compatibilização com Outlook, ao encaminhar a mensagem
2135            $body = mb_ereg_replace('<!--\[','<!-- [',$body);
2136        }
2137                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
2138                $attachments = $_FILES;
2139                $forwarding_attachments = $params['forwarding_attachments'];
2140                $local_attachments = $params['local_attachments'];
2141
2142                //Test if must be saved in shared folder and change if necessary
2143                if( $fromaddress[2] == 'y' ){
2144                        //build shared folder path
2145                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
2146                        if( $this->folder_exists($newfolder) ) $folder = $newfolder;
2147                        else $folder =  $params['folder'];                     
2148                } else  {
2149                        $folder = $params['folder'];                   
2150                }
2151               
2152                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
2153                $folder_name = $params['folder_name'];
2154                // Fix problem with cyrus delimiter changes.
2155                // Dots in names: enabled/disabled.
2156                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2157                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2158                // End Fix.
2159                if ($folder != 'null'){
2160                        $mail->SaveMessageInFolder = $folder;
2161                }
2162////////////////////////////////////////////////////////////////////////////////////////////////////
2163                $mail->SMTPDebug = false;
2164
2165                if($signed && !$params['smime'])
2166                {
2167            $mail->Mailer = "smime";
2168                        $mail->SignedBody = true;
2169                }
2170                else
2171            $mail->IsSMTP();
2172
2173                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2174                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2175                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2176                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2177                if($fromaddress){
2178                        $mail->Sender = $mail->From;
2179                        $mail->SenderName = $mail->FromName;
2180                        $mail->FromName = $fromaddress[0];
2181                        $mail->From = $fromaddress[1];
2182                }
2183
2184                $this->add_recipients("to", $toaddress, &$mail);
2185                $this->add_recipients("cc", $ccaddress, &$mail);
2186                $this->add_recipients("cco", $ccoaddress, &$mail);
2187                if ($replytoaddress !="")
2188                {
2189                $mail->AddReplyTo($replytoaddress);
2190                }
2191                $mail->Subject = $subject;
2192                $mail->IsHTML( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
2193                $mail->Body = $body;
2194
2195        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
2196                {
2197                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2198            $email = explode(",",$email);
2199            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2200            // Deve ser verificado um numero limite de destinatarios.
2201            // Deve ser verificado se os certificados sao validos.
2202            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2203            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2204            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2205            $erros_acumulados = "";
2206            $aux_mails = array();
2207            $mail_list = array();
2208            if(count($email) > $numero_maximo)
2209            {
2210                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2211                return $erros_acumulados;
2212            }
2213            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2214            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2215            foreach($email as $item)
2216            {
2217                $certificate = $db->get_certificate(strtolower($item));
2218                if(!$certificate)
2219                {
2220                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2221                    return $erros_acumulados;
2222                }
2223
2224                if (array_key_exists("dberr1", $certificate))
2225                {
2226
2227                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2228                    return $erros_acumulados;
2229                                }
2230                if (array_key_exists("dberr2", $certificate))
2231                {
2232                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2233                    //continue;
2234                }
2235                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2236                if (!array_key_exists("certs", $certificate))
2237                {
2238                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2239                    continue;
2240                }
2241            */
2242                include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2243
2244                foreach ($certificate['certs'] as $registro)
2245                {
2246                    $c1 = new certificadoB();
2247                    $c1->certificado($registro['chave_publica']);
2248                    if ($c1->apresentado)
2249                    {
2250                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2251                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2252                        {
2253                            $aux_mails[] = $registro['chave_publica'];
2254                            $mail_list[] = strtolower($item);
2255                        }
2256                        else
2257                        {
2258                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2259                            {
2260                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2261                                    $c1->dados['EXPIRADO'],$c2->revogado);
2262                            }
2263
2264                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2265                            foreach($c2->erros_ssl as $linha)
2266                            {
2267                                $erros_acumulados .=  $linha . chr(0x0A);
2268                            }
2269                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2270                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2271                        }
2272                    }
2273                    else
2274                    {
2275                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2276                    }
2277                }
2278                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2279                                {
2280                                        return $erros_acumulados;
2281                        }
2282            }
2283
2284            $mail->Certs_crypt = $aux_mails;
2285        }
2286                // Build CID images
2287                $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2288
2289                //      Build Uploading Attachments!!!
2290                if (count($attachments)>0) //Caso seja forward normal...
2291                {
2292                        $total_uploaded_size = 0;
2293                        $upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
2294                        foreach ($attachments as $attach)
2295                        {
2296                                if($attach['error'] == UPLOAD_ERR_INI_SIZE)
2297                                    return $this->parse_error("message file too big");
2298                                if($attach['name']=='Unknown')
2299                                        continue;
2300                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2301                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2302                        }
2303                        if( $total_uploaded_size > $upload_max_filesize){
2304                                return $this->parse_error("message file too big");
2305                        }
2306                }
2307                if(count($local_attachments)>0) { //Caso seja forward de mensagens locais
2308
2309                        $total_uploaded_size = 0;
2310                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
2311                        foreach($local_attachments as $local_attachment) {
2312                                $file_description = unserialize(rawurldecode($local_attachment));
2313                                $tmp = array_values($file_description);
2314                                foreach($file_description as $i => $descriptor){
2315                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2316                                }
2317                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2318                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2319                        }
2320                        if( $total_uploaded_size > $upload_max_filesize)
2321                                return 'false';
2322                }
2323////////////////////////////////////////////////////////////////////////////////////////////////////
2324                //      Build Forwarding Attachments!!!
2325                if (count($forwarding_attachments) > 0)
2326                {
2327                        // Bug fixed for array_search function
2328                        $name_cid_files = array();
2329                        if(count($name_cid_files) > 0) {
2330                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2331                                $name_cid_files[0] = null;
2332                        }
2333
2334                        foreach($forwarding_attachments as $forwarding_attachment)
2335                        {
2336                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2337                                        $tmp = array_values($file_description);
2338                                        foreach($file_description as $i => $descriptor){
2339                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2340                                        }
2341                                        $file_description = $tmp;
2342                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2343                                        $fileName = $file_description[2];
2344                                        if(!array_search(trim($fileName),$name_cid_files)) {
2345                                                $mail->AddStringAttachment($fileContent,html_entity_decode(rawurldecode($fileName)), $file_description[4], $this->get_file_type($file_description[2]));
2346                                }
2347                        }
2348                }
2349
2350////////////////////////////////////////////////////////////////////////////////////////////////////
2351                // Important message
2352                if($is_important)
2353                        $mail->isImportant();
2354
2355////////////////////////////////////////////////////////////////////////////////////////////////////
2356                // Disposition-Notification-To
2357                if ($return_receipt)
2358                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2359////////////////////////////////////////////////////////////////////////////////////////////////////
2360
2361                $sent = $mail->Send();
2362
2363                if(!$sent)
2364                {
2365                        return $this->parse_error($mail->ErrorInfo);
2366                }
2367                else
2368                {
2369            if ($signed && !$params['smime'])
2370                        {
2371                                return $sent;
2372                        }
2373                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
2374                        {
2375                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2376                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
2377                                $now = date("d/m/y H:i:s");
2378                                $addrs = $toaddress.$ccaddress.$ccoaddress;
2379                                $sent = trim($sent);
2380                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2381                        }
2382                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
2383                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
2384                                $contacts = new dynamic_contacts();
2385                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2386                                return array("success" => true, "new_contacts" => $new_contacts);
2387                        }
2388                        return array("success" => true);
2389                }
2390        }
2391        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments)
2392        {
2393                //      Build CID for embedded Images!!!
2394                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2395                $cid_imgs = '';
2396                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2397                $cid_array = array();
2398                foreach($cid_imgs[6] as $j => $val){
2399                        if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2400                        {
2401                                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2402                        }
2403                        $cid = $cid_array[$cid_imgs[4][$j].$val]; 
2404                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2405
2406                        if ($msg_uid != $cid_imgs[4][$j]) // The image is not in the same mail?
2407                        {
2408                                $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2409                                //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
2410                                $fileName = "image_".($j).".jpg";
2411                                $fileCode = "base64";
2412                                $fileType = "image/jpg";
2413                                $file_attached[0] = $cid_imgs[2][$j];
2414                                $file_attached[1] = $cid_imgs[4][$j];
2415                                $file_attached[2] = $fileName;
2416                                $file_attached[3] = $cid_imgs[6][$j];
2417                                $file_attached[4] = 'base64';
2418                                $file_attached[5] = strlen($fileContent); //Size of file
2419                                $return_forward[] = $file_attached;
2420
2421                                $attachment_ = unserialize(rawurldecode($forwarding_attachments[$cid_imgs[6][$j]-2]));
2422                                if ($file_attached[3] == $attachment_[3])
2423                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);     
2424                        }
2425                        else
2426                        {
2427                                $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2428                                $file_description = unserialize(rawurldecode($attach_img));
2429                                if (is_array($file_description))
2430                                        foreach($file_description as $i => $descriptor){                                 
2431                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2432                                        }
2433                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2434                                $fileName = $file_description[2];
2435                                $fileCode = $file_description[4];
2436                                $fileType = $this->get_file_type($file_description[2]);
2437                                unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2438                                if (!empty($file_description))
2439                                {
2440                                        $file_description[5] = strlen($fileContent); //Size of file
2441                                        $return_forward[] = $file_description;
2442                                }
2443                        }
2444                        $tempDir = ini_get("session.save_path");
2445                        $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                       
2446                        $f = fopen($tempDir.'/'.$file,"w");
2447                        fputs($f,$fileContent);
2448                        fclose($f);
2449                        if ($fileContent)
2450                                $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2451                        //else
2452                        //      return "Error loading image attachment content";                                                 
2453
2454                }
2455                return $return_forward;
2456        }
2457        function add_recipients_cert($full_address)
2458        {
2459                $result = "";
2460                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2461                foreach ($parse_address as $val)
2462                {
2463                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2464                        if ($val->mailbox == "INVALID_ADDRESS")
2465                                continue;
2466                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2467                                continue;
2468                        if (empty($val->personal))
2469                                $result .= $val->mailbox."@".$val->host . ",";
2470                        else
2471                                $result .= $val->mailbox."@".$val->host . ",";
2472                }
2473
2474                return substr($result,0,-1);
2475        }
2476
2477        function add_recipients($recipient_type, $full_address, $mail)
2478        {
2479                //remove a comma if is given two unexpected commas
2480                $full_address = preg_replace("/, ?,/",",",$full_address);
2481                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2482                foreach ($parse_address as $val)
2483                {
2484                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2485                        if ($val->mailbox == "INVALID_ADDRESS")
2486                                continue;
2487
2488                        if (empty($val->personal))
2489                        {
2490                                switch($recipient_type)
2491                                {
2492                                        case "to":
2493                                                $mail->AddAddress($val->mailbox."@".$val->host);
2494                                                break;
2495                                        case "cc":
2496                                                $mail->AddCC($val->mailbox."@".$val->host);
2497                                                break;
2498                                        case "cco":
2499                                                $mail->AddBCC($val->mailbox."@".$val->host);
2500                                                break;
2501                                }
2502                        }
2503                        else
2504                        {
2505                                switch($recipient_type)
2506                                {
2507                                        case "to":
2508                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2509                                                break;
2510                                        case "cc":
2511                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2512                                                break;
2513                                        case "cco":
2514                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2515                                                break;
2516                                }
2517                        }
2518                }
2519                return true;
2520        }
2521
2522        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2523        {
2524                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
2525                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
2526                if($encoding == 'base64')
2527                        # The function imap_base64 adds a new line
2528                        # at ASCII text, with CRLF line terminators.
2529                        # So is being exchanged for base64_decode.
2530                        #
2531                        #$fileContent = imap_base64($fileContent);
2532                        $fileContent = base64_decode($fileContent);
2533                else if($encoding == 'quoted-printable')
2534                        $fileContent = quoted_printable_decode($fileContent);
2535                return $fileContent;
2536        }
2537
2538        function del_last_caracter($string)
2539        {
2540                $string = substr($string,0,(strlen($string) - 1));
2541                return $string;
2542        }
2543
2544        function del_last_two_caracters($string)
2545        {
2546                $string = substr($string,0,(strlen($string) - 2));
2547                return $string;
2548        }
2549
2550        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
2551        {
2552                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
2553                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2554                        foreach($imapsort as $iuid)
2555                                $sort[$iuid] = "";
2556                       
2557                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2558                                $slice_array = false;
2559                        else
2560                                $slice_array = true;
2561                }
2562                else
2563                {
2564                        $sort = array();
2565                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2566                        $num_msgs = imap_num_msg($this->mbox);
2567                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
2568                        $slice_array = true;
2569
2570                        for ($i=$num_msgs; $i>0; $i--)
2571                        {
2572                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2573                                        break;
2574                                $iuid = @imap_uid($this->mbox,$i);
2575                                $header = $this->get_header($iuid);
2576                                // List UNSEEN messages.
2577                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2578                                        continue;
2579                                }
2580                                // List SEEN messages.
2581                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2582                                        continue;
2583                                }
2584                                // List ANSWERED messages.
2585                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2586                                        continue;
2587                                }
2588                                // List FLAGGED messages.
2589                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2590                                        continue;
2591                                }
2592
2593                                if($sort_box_type=='SORTFROM') {
2594                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
2595                                                $from = $header->to;
2596                                        else
2597                                                $from = $header->from;
2598
2599                                        $tmp = imap_mime_header_decode($from[0]->personal);
2600
2601                                        if ($tmp[0]->text != "")
2602                                                $sort[$iuid] = $tmp[0]->text;
2603                                        else
2604                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2605                                }
2606                                else if($sort_box_type=='SORTSUBJECT') {
2607                                        $sort[$iuid] = $header->subject;
2608                                }
2609                                else if($sort_box_type=='SORTSIZE') {
2610                                        $sort[$iuid] = $header->Size;
2611                                }
2612                                else {
2613                                        $sort[$iuid] = $header->udate;
2614                                }
2615
2616                        }
2617                        natcasesort($sort);
2618
2619                        if ($sort_box_reverse)
2620                                $sort = array_reverse($sort,true);
2621                }
2622
2623                if(!is_array($sort))
2624                        $sort = array();
2625
2626
2627                if ($slice_array)
2628                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
2629
2630
2631                return $sort;
2632
2633        }
2634
2635
2636        function move_search_messages($params){
2637                $params['selected_messages'] = urldecode($params['selected_messages']);
2638                $params['new_folder'] = urldecode($params['new_folder']);
2639                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2640                $sel_msgs = explode(",", $params['selected_messages']);
2641                @reset($sel_msgs);
2642                $sorted_msgs = array();
2643                foreach($sel_msgs as $idx => $sel_msg) {
2644                        $sel_msg = explode(";", $sel_msg);
2645                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2646                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
2647                         }
2648                         else {
2649                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2650                         }
2651                }
2652                @ksort($sorted_msgs);
2653                $last_return = false;
2654                foreach($sorted_msgs as $folder => $msgs_number) {
2655                        $params['msgs_number'] = $msgs_number;
2656                        $params['folder'] = $folder;
2657                        if($params['new_folder'] && $folder != $params['new_folder']){
2658                                $last_return = $this -> move_messages($params);
2659                        }
2660                        elseif(!$params['new_folder'] || $params['delete'] ){
2661                                $last_return = $this -> delete_msgs($params);
2662                                $last_return['deleted'] = true;
2663                        }
2664                }
2665                return $last_return;
2666        }
2667
2668        function move_messages($params)
2669        {
2670                $folder = $params['folder'];
2671                $mbox_stream = $this->open_mbox($folder);
2672                $newmailbox = ($params['new_folder']);
2673                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO-8859-1");
2674                $new_folder_name = $params['new_folder_name'];
2675                $msgs_number = $params['msgs_number'];
2676                $return = array('msgs_number' => $msgs_number,
2677                                                'folder' => $folder,
2678                                                'new_folder_name' => $new_folder_name,
2679                                                'border_ID' => $params['border_ID'],
2680                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
2681
2682                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2683        if (substr($folder,0,4) == 'user'){
2684                $acl = $this->getacltouser($folder);
2685                /*
2686                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2687                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2688                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2689                 *   w - write (STORE flags other than SEEN and DELETED)
2690                 *   i - insert (perform APPEND, COPY into mailbox)
2691                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2692                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2693                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2694                 *   a - administer (perform SETACL)
2695                        */
2696                        if (strpos($acl, "d") === false){
2697                                $return['status'] = false;
2698                                return $return;
2699                        }
2700        }
2701        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
2702        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
2703            if (substr($new_folder_name,0,4) == 'user'){
2704                $this->ldap = new ldap_functions();
2705                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
2706                $return['new_folder_name'] = array_pop($tmp_folder_name);
2707                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2708                {
2709                    $return['new_folder_name'] = $cn;
2710                }
2711            }
2712        }
2713
2714                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
2715                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
2716                {
2717                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2718                        // Fix problem in unserialize function JS.
2719                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2720                }
2721
2722                $mbox_stream = $this->open_mbox($folder);
2723                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2724                        imap_expunge($mbox_stream);
2725                        if($mbox_stream)
2726                                imap_close($mbox_stream);
2727                        return $return;
2728                }else {
2729                        if(strstr(imap_last_error(),'Over quota')) {
2730                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
2731                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
2732                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2733                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2734                                $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()))));
2735                                if(!$mbox)
2736                                        return imap_last_error();
2737                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
2738                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
2739                                        if($mbox_stream)
2740                                                imap_close($mbox_stream);
2741                                        if($mbox)
2742                                                imap_close($mbox);
2743                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
2744                                }
2745                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2746                                        imap_expunge($mbox_stream);
2747                                        if($mbox_stream)
2748                                                imap_close($mbox_stream);
2749                                        // return to original quota limit.
2750                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2751                                                if($mbox)
2752                                                        imap_close($mbox);
2753                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2754                                        }
2755                                        return $return;
2756                                }
2757                                else {
2758                                        if($mbox_stream)
2759                                                imap_close($mbox_stream);
2760                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2761                                                if($mbox)
2762                                                        imap_close($mbox);
2763                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2764                                        }
2765                                        return imap_last_error();
2766                                }
2767
2768                        }
2769                        else {
2770                                if($mbox_stream)
2771                                        imap_close($mbox_stream);
2772                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
2773                        }
2774                }
2775        }
2776
2777        function save_msg($params)
2778        {
2779
2780                include_once("class.phpmailer.php");
2781                $mail = new PHPMailer();
2782                include_once("class.db_functions.inc.php");
2783                $toaddress = $params['input_to'];
2784                $ccaddress = $params['input_cc'];
2785                $ccoaddress = $params['input_cco'];
2786                $return_receipt = $params['input_return_receipt'];
2787                $is_important = $params['input_important_message'];
2788                $subject = $params['input_subject'];
2789                $msg_uid = $params['msg_id'];
2790                $body = $params['body'];
2791                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
2792                $body = preg_replace("/\n/"," ",$body);
2793                $body = preg_replace("/\r/","",$body);
2794                $forwarding_attachments = $params['forwarding_attachments'];
2795                $attachments = $params['FILES'];
2796                $return_files = $params['FILES'];
2797
2798                $folder = $params['folder'];
2799                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
2800                // Fix problem with cyrus delimiter changes.
2801                // Dots in names: enabled/disabled.
2802                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2803                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2804                // End Fix.
2805                if(strtoupper($folder) == 'INBOX/DRAFTS') $mail->SaveMessageAsDraft = $folder;
2806
2807                $mail->SaveMessageInFolder = $folder;
2808                $mail->SMTPDebug = false;
2809
2810                $mail->IsSMTP();
2811                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2812                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2813                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2814                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2815
2816                $mail->Sender = $mail->From;
2817                $mail->SenderName = $mail->FromName;
2818                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2819                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
2820
2821                $this->add_recipients("to", $toaddress, &$mail);
2822                $this->add_recipients("cc", $ccaddress, &$mail);
2823    $this->add_recipients("cco", $ccoaddress, &$mail);
2824                $mail->AddReplyTo($replytoaddress);
2825                $mail->Subject = $subject;
2826                $mail->IsHTML(true);
2827                $mail->Body = $body;
2828               
2829                // Important message
2830                if($is_important)
2831                        $mail->isImportant();
2832
2833                // Disposition-Notification-To
2834                if ($return_receipt)
2835                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2836
2837                $return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2838
2839        //      Build Forwarding Attachments!!!
2840                if (count($forwarding_attachments) > 0)
2841                {
2842                        foreach($forwarding_attachments as $forwarding_attachment)
2843                        {
2844                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2845                                $tmp = array_values($file_description);
2846                                foreach($file_description as $i => $descriptor){
2847                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2848                                }
2849                                $file_description = $tmp;
2850
2851                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2852                                $fileName = $file_description[2];
2853
2854                                $file_description[5] = strlen($fileContent); //Size of file
2855                                $return_forward[] = $file_description;
2856
2857                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2858                        }
2859                }
2860
2861                if ((count($return_forward) > 0) && (count($return_files) > 0))
2862                        $return_files = array_merge_recursive($return_forward,$return_files);
2863                else
2864                        if (count($return_files) < 1)
2865                                $return_files = $return_forward;
2866
2867                //      Build Uploading Attachments!!!
2868                $sizeof_attachments = count($attachments);
2869                if ($sizeof_attachments)
2870                        foreach ($attachments as $numb => $attach){
2871                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2872                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2873                                        switch ($image_type)
2874                                        {
2875                                        // Do not corrupt animated gif
2876                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
2877                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2878                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2879                                        case 6:
2880                                                require_once("gd_functions.php");
2881                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2882                                        default:
2883                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2884                                                break;
2885                                        }
2886                                        header('Content-type: image/jpeg');
2887                                        $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
2888                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2889                                        if ($width < $max_resolution && $height < $max_resolution){
2890                                                $new_width = $width;
2891                                                $new_height = $height;
2892                                        }
2893                                        else if ($width > $max_resolution){
2894                                                $new_width = $max_resolution;
2895                                                $new_height = $height*($new_width/$width);
2896                                        }
2897                                        else {
2898                                                $new_height = $max_resolution;
2899                                                $new_width = $width*($new_height/$height);
2900                                        }
2901                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2902                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2903                                        $tmpDir = ini_get("session.save_path");
2904                                        $_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
2905                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2906                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2907                                }
2908                                else
2909                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2910                                // optional name
2911                                }
2912
2913
2914
2915
2916                if(!empty($mail->AltBody))
2917            $mail->ContentType = "multipart/alternative";
2918
2919                $mail->error_count = 0; // reset errors
2920                $mail->SetMessageType();
2921                $header = $mail->CreateHeader();
2922                $body = $mail->CreateBody();
2923
2924                $mbox_stream = $this->open_mbox($folder);
2925                $new_header = str_replace("\n", "\r\n", $header);
2926                $new_body = str_replace("\n", "\r\n", $body);
2927                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2928                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2929                $return['msg_no'] = $status->uidnext - 1;
2930                $return['folder_id'] = $folder;
2931
2932                if($mbox_stream)
2933                        imap_close($mbox_stream);
2934                if (is_array($return_files))
2935                        foreach ($return_files as $index => $_attachment) {
2936                                if (array_key_exists("name",$_attachment)){
2937                                unset($return_files[$index]);
2938                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2939                        }
2940                        else
2941                        {
2942                                unset($return_files[$index]);
2943                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2944                        }
2945                }
2946
2947                $return['files'] = serialize($return_files);
2948                $return["subject"] = $subject;
2949
2950                if (!$return['append']) {
2951                        $return['append'] = imap_last_error();
2952                        $return['has_error'] = true;
2953                }
2954
2955                return $return;
2956        }
2957
2958        function set_messages_flag($params)
2959        {
2960                $folder = $params['folder'];
2961                $msgs_to_set = $params['msgs_to_set'];
2962                $flag = $params['flag'];
2963                $return = array();
2964                $return["msgs_to_set"] = $msgs_to_set;
2965                $return["flag"] = $flag;
2966
2967                if(!$this->mbox && !is_resource($this->mbox))
2968                        $this->mbox = $this->open_mbox($folder);
2969
2970                if ($flag == "unseen")
2971                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2972                elseif ($flag == "seen")
2973                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2974                elseif ($flag == "answered"){
2975                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2976                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2977                }
2978                elseif ($flag == "forwarded")
2979                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2980                elseif ($flag == "flagged")
2981                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2982                elseif ($flag == "unflagged") {
2983                        $flag_importance = false;
2984                        $msgs_number = explode(",",$msgs_to_set);
2985                        $unflagged_msgs = "";
2986                        foreach($msgs_number as $msg_number) {
2987                                preg_match('/importance *: *(.*)\r/i',
2988                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2989                                        ,$importance);
2990                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2991                                        $flag_importance=true;
2992                                }
2993                                else {
2994                                        $unflagged_msgs.=$msg_number.",";
2995                                }
2996                        }
2997
2998                        if($unflagged_msgs!="") {
2999                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
3000                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
3001                        }
3002                        else {
3003                                $return["msgs_unflageds"] = false;
3004                        }
3005
3006                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3007                                $return["status"] = false;
3008                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
3009                        }
3010                        else {
3011                                $return["status"] = true;
3012                        }
3013                }
3014
3015                if($this->mbox && is_resource($this->mbox))
3016                        imap_close($this->mbox);
3017                return $return;
3018        }
3019
3020        function get_file_type($file_name)
3021        {
3022                $file_name = strtolower($file_name);
3023                $strFileType = strrev(substr(strrev($file_name),0,4));
3024                if ($strFileType == ".asf")
3025                        return "video/x-ms-asf";
3026                if ($strFileType == ".avi")
3027                        return "video/avi";
3028                if ($strFileType == ".doc")
3029                        return "application/msword";
3030                if ($strFileType == ".zip")
3031                        return "application/zip";
3032                if ($strFileType == ".xls")
3033                        return "application/vnd.ms-excel";
3034                if ($strFileType == ".gif")
3035                        return "image/gif";
3036                if ($strFileType == ".jpg" || $strFileType == "jpeg")
3037                        return "image/jpeg";
3038                if ($strFileType == ".png")
3039                        return "image/png";
3040                if ($strFileType == ".wav")
3041                        return "audio/wav";
3042                if ($strFileType == ".mp3")
3043                        return "audio/mpeg3";
3044                if ($strFileType == ".mpg" || $strFileType == "mpeg")
3045                        return "video/mpeg";
3046                if ($strFileType == ".rtf")
3047                        return "application/rtf";
3048                if ($strFileType == ".htm" || $strFileType == "html")
3049                        return "text/html";
3050                if ($strFileType == ".xml")
3051                        return "text/xml";
3052                if ($strFileType == ".xsl")
3053                        return "text/xsl";
3054                if ($strFileType == ".css")
3055                        return "text/css";
3056                if ($strFileType == ".php")
3057                        return "text/php";
3058                if ($strFileType == ".asp")
3059                        return "text/asp";
3060                if ($strFileType == ".pdf")
3061                        return "application/pdf";
3062                if ($strFileType == ".txt")
3063                        return "text/plain";
3064                if ($strFileType == ".wmv")
3065                        return "video/x-ms-wmv";
3066                if ($strFileType == ".sxc")
3067                        return "application/vnd.sun.xml.calc";
3068                if ($strFileType == ".stc")
3069                        return "application/vnd.sun.xml.calc.template";
3070                if ($strFileType == ".sxd")
3071                        return "application/vnd.sun.xml.draw";
3072                if ($strFileType == ".std")
3073                        return "application/vnd.sun.xml.draw.template";
3074                if ($strFileType == ".sxi")
3075                        return "application/vnd.sun.xml.impress";
3076                if ($strFileType == ".sti")
3077                        return "application/vnd.sun.xml.impress.template";
3078                if ($strFileType == ".sxm")
3079                        return "application/vnd.sun.xml.math";
3080                if ($strFileType == ".sxw")
3081                        return "application/vnd.sun.xml.writer";
3082                if ($strFileType == ".sxq")
3083                        return "application/vnd.sun.xml.writer.global";
3084                if ($strFileType == ".stw")
3085                        return "application/vnd.sun.xml.writer.template";
3086
3087
3088                return "application/octet-stream";
3089        }
3090
3091        function htmlspecialchars_encode($str)
3092        {
3093                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
3094        }
3095        function htmlspecialchars_decode($str)
3096        {
3097                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
3098        }
3099
3100        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
3101        {
3102                if(!$this->mbox || !is_resource($this->mbox))
3103                        $this->mbox = $this->open_mbox($folder);
3104
3105                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
3106        }
3107
3108        function get_info_next_msg($params)
3109        {
3110                $msg_number = $params['msg_number'];
3111                $folder = $params['msg_folder'];
3112                $sort_box_type = $params['sort_box_type'];
3113                $sort_box_reverse = $params['sort_box_reverse'];
3114                $reuse_border = $params['reuse_border'];
3115                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
3116                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
3117
3118                $success = false;
3119                if (is_array($sort_array_msg))
3120                {
3121                        foreach ($sort_array_msg as $i => $value){
3122                                if ($value == $msg_number)
3123                                {
3124                                        $success = true;
3125                                        break;
3126                                }
3127                        }
3128                }
3129
3130                if (! $success || $i >= sizeof($sort_array_msg)-1)
3131                {
3132                        $params['status'] = 'false';
3133                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3134                        return $params;
3135                }
3136
3137                $params = array();
3138                $params['msg_number'] = $sort_array_msg[($i+1)];
3139                $params['msg_folder'] = $folder;
3140
3141                $return = $this->get_info_msg($params);
3142                $return["reuse_border"] = $reuse_border;
3143                return $return;
3144        }
3145
3146        function get_info_previous_msg($params)
3147        {
3148                $msg_number = $params['msgs_number'];
3149                $folder = $params['folder'];
3150                $sort_box_type = $params['sort_box_type'];
3151                $sort_box_reverse = $params['sort_box_reverse'];
3152                $reuse_border = $params['reuse_border'];
3153                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
3154                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
3155
3156                $success = false;
3157                if (is_array($sort_array_msg))
3158                {
3159                        foreach ($sort_array_msg as $i => $value){
3160                                if ($value == $msg_number)
3161                                {
3162                                        $success = true;
3163                                        break;
3164                                }
3165                        }
3166                }
3167                if (! $success || $i == 0)
3168                {
3169                        $params['status'] = 'false';
3170                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3171                        return $params;
3172                }
3173
3174                $params = array();
3175                $params['msg_number'] = $sort_array_msg[($i-1)];
3176                $params['msg_folder'] = $folder;
3177
3178                $return = $this->get_info_msg($params);
3179                $return["reuse_border"] = $reuse_border;
3180                return $return;
3181        }
3182
3183        // This function updates the values: quota, paging and new messages menu.
3184        function get_menu_values($params){
3185                $return_array = array();
3186                $return_array = $this->get_quota($params);
3187
3188                $mbox_stream = $this->open_mbox($params['folder']);
3189                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
3190                if($mbox_stream)
3191                        imap_close($mbox_stream);
3192
3193                return $return_array;
3194        }
3195
3196        function get_quota($params){
3197                // folder_id = user/{uid} for shared folders
3198                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
3199                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
3200                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
3201                }
3202                // folder_id = INBOX for inbox folders
3203                else
3204                        $folder_id = "INBOX";
3205
3206                if(!$this->mbox || !is_resource($this->mbox))
3207                        $this->mbox = $this->open_mbox();
3208
3209                $quota = imap_get_quotaroot($this->mbox, $folder_id);
3210                if($this->mbox && is_resource($this->mbox))
3211                        imap_close($this->mbox);
3212
3213                if (!$quota){
3214                        return array(
3215                                'quota_percent' => 0,
3216                                'quota_used' => 0,
3217                                'quota_limit' =>  0
3218                        );
3219                }
3220
3221                if(count($quota) && $quota['limit']) {
3222                        $quota_limit = $quota['limit'];
3223                        $quota_used  = $quota['usage'];
3224                        if($quota_used >= $quota_limit)
3225                        {
3226                                $quotaPercent = 100;
3227                        }
3228                        else
3229                        {
3230                        $quotaPercent = ($quota_used / $quota_limit)*100;
3231                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
3232                        }
3233                        return array(
3234                                'quota_percent' => floor($quotaPercent),
3235                                'quota_used' => $quota_used,
3236                                'quota_limit' =>  $quota_limit
3237                        );
3238                }
3239                else
3240                        return array();
3241        }
3242
3243        function send_notification($params){
3244                include("../header.inc.php");
3245                require_once("class.phpmailer.php");
3246                $mail = new PHPMailer();
3247
3248                $toaddress = $params['notificationto'];
3249
3250                $subject = lang("Read receipt: %1",$params['subject']);
3251                $body = lang("Your message: %1",$params['subject']) . '<br>';
3252                $body .= lang("Received in: %1",date("d/m/Y H:i",$params['date'])) . '<br>';
3253                $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"));
3254                $mail->SMTPDebug = false;
3255                $mail->IsSMTP();
3256                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
3257                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
3258                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3259                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
3260                $mail->AddAddress($toaddress);
3261                $mail->Subject = $this->htmlspecialchars_decode($subject);
3262
3263                $mail->IsHTML(true);
3264                $mail->Body = $body;
3265
3266                if(!$mail->Send()){
3267                        return $mail->ErrorInfo;
3268                }
3269                else
3270                        return true;
3271        }
3272
3273        function empty_folder($params)
3274        {
3275                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
3276                $mbox_stream = $this->open_mbox($folder);
3277                $return = imap_delete($mbox_stream,'1:*');
3278                if($mbox_stream)
3279                        imap_close($mbox_stream, CL_EXPUNGE);
3280                return $return;
3281        }
3282
3283        function search($params)
3284        {
3285                include("class.imap_attachment.inc.php");
3286                $imap_attachment = new imap_attachment();
3287                $criteria = $params['criteria'];
3288                $return = array();
3289                $folders = $this->get_folders_list();
3290
3291                $j = 0;
3292                foreach($folders as $folder)
3293                {
3294                        $mbox_stream = $this->open_mbox($folder);
3295                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
3296
3297                        if ($messages == '')
3298                                continue;
3299
3300                        $i = 0;
3301                        $return[$j] = array();
3302                        $return[$j]['folder_name'] = $folder['name'];
3303
3304                        foreach($messages as $msg_number)
3305                        {
3306                                $header = $this->get_header($msg_number);
3307                                if (!is_object($header))
3308                                        return false;
3309
3310                                $return[$j][$i]['msg_folder']   = $folder['name'];
3311                                $return[$j][$i]['msg_number']   = $msg_number;
3312                                $return[$j][$i]['Recent']               = $header->Recent;
3313                                $return[$j][$i]['Unseen']               = $header->Unseen;
3314                                $return[$j][$i]['Answered']     = $header->Answered;
3315                                $return[$j][$i]['Deleted']              = $header->Deleted;
3316                                $return[$j][$i]['Draft']                = $header->Draft;
3317                                $return[$j][$i]['Flagged']              = $header->Flagged;
3318
3319                                $date_msg = gmdate("d/m/Y",$header->udate);
3320                                if (gmdate("d/m/Y") == $date_msg)
3321                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
3322                                else
3323                                        $return[$j][$i]['udate'] = $date_msg;
3324
3325                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3326                                $return[$j][$i]['fromaddress'] = '';
3327                                foreach ($fromaddress as $tmp)
3328                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
3329
3330                                $from = $header->from;
3331                                $return[$j][$i]['from'] = array();
3332                                $tmp = imap_mime_header_decode($from[0]->personal);
3333                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3334                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
3335                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
3336
3337                                $to = $header->to;
3338                                $return[$j][$i]['to'] = array();
3339                                $tmp = imap_mime_header_decode($to[0]->personal);
3340                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3341                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
3342                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
3343
3344                                $subject = imap_mime_header_decode($header->fetchsubject);
3345                                $return[$j][$i]['subject'] = '';
3346                                foreach ($subject as $tmp)
3347                                        $return[$j][$i]['subject'] .= $tmp->text;
3348
3349                                $return[$j][$i]['Size'] = $header->Size;
3350                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
3351
3352                                $return[$j][$i]['attachment'] = array();
3353                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
3354
3355                                $i++;
3356                        }
3357                        $j++;
3358                        if($mbox_stream)
3359                                imap_close($mbox_stream);
3360                }
3361
3362                return $return;
3363        }
3364
3365
3366        function mobile_search($params)
3367        {
3368                include("class.imap_attachment.inc.php");
3369                $imap_attachment = new imap_attachment();
3370                $criterias = array ("TO","SUBJECT","FROM","CC");
3371                $return = array();
3372                if(!isset($params['folder'])) {
3373                        $folder_params = array("noSharedFolders"=>1);
3374                        if(isset($params['folderType']))
3375                                $folder_params['folderType'] = $params['folderType'];
3376                        $folders = $this->get_folders_list($folder_params);
3377                }
3378                else
3379                        $folders = array(0=>array('folder_id'=>$params['folder']));
3380                $num_msgs = 0;
3381                $max_msgs = $params['max_msgs'] + 1; //get one more because mobile paginate
3382                $return["msgs"] = array();
3383               
3384                //get max_msgs of each folder order by date and later order all messages together and retur only max_msgs msgs
3385                foreach($folders as $id =>$folder)
3386                {
3387                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3388                                foreach($criterias as $criteria_fixed)
3389                                {
3390                                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3391
3392                                        $mbox_stream = $this->open_mbox($folder['folder_id']);
3393
3394                                        $messages = imap_sort($mbox_stream,SORTARRIVAL,1,SE_UID,$_filter);
3395                                       
3396                                        if ($messages == ''){
3397                                                if($mbox_stream)
3398                                                        imap_close($mbox_stream);
3399                                                continue;       
3400                                        }
3401                                       
3402                                        foreach($messages as $msg_number)
3403                                        {
3404                                                $temp = $this->get_info_head_msg($msg_number);
3405                                                if(!$temp)
3406                                                        return false;
3407                                                $temp['msg_folder'] = $folder['folder_id'];
3408                                                $return["msgs"][$num_msgs] = $temp;
3409                                                $num_msgs++;
3410                                        }
3411
3412                                        if($mbox_stream)
3413                                                imap_close($mbox_stream);
3414                                }
3415                        }
3416                }
3417
3418                if(!function_exists("cmp_date")) {
3419                        function cmp_date($obj1, $obj2){
3420                    if($obj1['timestamp'] == $obj2['timestamp']) return 0;
3421                    return ($obj1['timestamp'] < $obj2['timestamp']) ? 1 : -1;
3422                        }
3423                }
3424                usort($return["msgs"], "cmp_date");
3425                $return["has_more_msg"] = (sizeof($return["msgs"]) > $max_msgs);
3426                $return["msgs"] = array_slice($return["msgs"], 0, $max_msgs);
3427                $return["msgs"]['num_msgs'] = $num_msgs;
3428               
3429                return $return;
3430        }
3431
3432        function delete_and_show_previous_message($params)
3433        {
3434                $return = $this->get_info_previous_msg($params);
3435
3436                $params_tmp1 = array();
3437                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3438                $params_tmp1['folder'] = $params['msg_folder'];
3439                $return_tmp1 = $this->delete_msg($params_tmp1);
3440
3441                $return['msg_number_deleted'] = $return_tmp1;
3442
3443                return $return;
3444        }
3445
3446
3447        function automatic_trash_cleanness($params)
3448        {
3449                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3450                $criteria =  'BEFORE "'.$before_date.'"';
3451                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
3452                // Free others requests
3453                session_write_close();
3454                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3455                if (is_array($messages)){
3456                        foreach ($messages as $msg_number){
3457                                imap_delete($mbox_stream, $msg_number, FT_UID);
3458                        }
3459                }
3460                if($mbox_stream)
3461                        imap_close($mbox_stream, CL_EXPUNGE);
3462                return $messages;
3463        }
3464//      Fix the search problem with special characters!!!!
3465        function remove_accents($string) {
3466                return strtr($string,
3467                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
3468                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3469        }
3470
3471        function make_search_date($date){
3472
3473            //TODO: Adaptar a data de acordo com o locale do sistema.
3474            list($day,$month,$year) = explode("/", $date);
3475            $before?$day=(int)$day+1:$day=(int)$day;
3476            $timestamp = mktime(0,0,0,(int)$month,$day,(int)$year);
3477            $search_date = date('d-M-Y',$timestamp);
3478            return $search_date;
3479
3480        }
3481
3482        function search_msg( $params = false )
3483        {
3484                $mbox_stream = "";
3485               
3486                if(strpos($params['condition'],"#")===false)
3487                { //local messages
3488                        $search=false;
3489                }
3490                else
3491                {
3492                        $search = explode(",",$params['condition']);
3493                }
3494               
3495                $params['page'] = $params['page'] * 1;
3496
3497            if( is_array($search) )
3498            {
3499                        $search = array_unique($search); // Remove duplicated folders
3500                        $search_criteria = '';
3501                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
3502                        foreach($search as $tmp)
3503                        {
3504                                $tmp1 = explode("##",$tmp);
3505                                $sum = 0;
3506                                $name_box = $tmp1[0];
3507                                unset($filter);
3508                                foreach($tmp1 as $index => $criteria)
3509                                {
3510                                        if ($index != 0 && strlen($criteria) != 0)
3511                                        {
3512                                                $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
3513                                                $filter .= " ".$filter_array[0];
3514                                                if (strlen($filter_array[1]) != 0)
3515                                                {
3516                                                        if ( trim($filter_array[0]) != 'BEFORE' &&
3517                                                                 trim($filter_array[0]) != 'SINCE' &&
3518                                                                 trim($filter_array[0]) != 'ON')
3519                                                        {
3520                                                            $filter .= '"'.$filter_array[1].'"';
3521                                                        }else if(trim($filter_array[0]) == 'BEFORE' ){
3522                                                            $filter .= '"'.$this->make_search_date($filter_array[1],true).'"';
3523                                                        }else{
3524                                                                $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3525                                                        }
3526                                                }
3527                                        }
3528                                }
3529                               
3530                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
3531                                $filter = $this->remove_accents($filter);
3532
3533                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
3534                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
3535                                {
3536                                        $folder_name = explode($this->imap_delimiter,$name_box);
3537                                        $this->ldap = new ldap_functions();
3538                                       
3539                                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3540                                        {
3541                                                $folder_name[1] = $cn;
3542                                        }
3543                                        $folder_name = implode($this->imap_delimiter,$folder_name);
3544                                }
3545                                else
3546                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
3547                               
3548                                if(!is_resource($mbox_stream))
3549                                        $mbox_stream = $this->open_mbox($name_box);
3550                                else
3551                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
3552                               
3553                                if (preg_match("/^.?\bALL\b/", $filter))
3554                                {
3555                                        // Quick Search, note: this ALL isn't the same ALL from imap_search
3556                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3557                                           
3558                                        foreach($all_criterias as $criteria_fixed)
3559                                        {
3560                                                $_filter = $criteria_fixed . substr($filter,4);
3561                                               
3562                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
3563                                               
3564                                                if(is_array($search_criteria))
3565                                                {
3566                                                        foreach($search_criteria as $new_search)
3567                                                        {
3568                                                                $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3569                                                                $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );
3570                                                                $elem['uid'] = $new_search;
3571                                                                /* compare dates in ordering */
3572                                                                $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
3573                                                                $retorno[] = $elem;
3574                                                        }
3575                                                }
3576                                        }
3577                                }                               
3578                                else {
3579                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3580                                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
3581                                        {
3582                        if((!strpos($filter,"FLAGGED") === false) || (!strpos($filter,"UNFLAGGED") === false))
3583                                                {
3584                                $num_msgs = imap_num_msg($mbox_stream);
3585                                                        $flagged_msgs = array();
3586                                                        for ($i=$num_msgs; $i>0; $i--)
3587                                                        {
3588                                                                $iuid = @imap_uid($this->mbox,$i);
3589                                                                $header = $this->get_header($iuid);                                                             
3590                                                                if(trim($header->Flagged))
3591                                                                {
3592                                                                        $flagged_msgs[$i] = $iuid;
3593                                                                }
3594                                                        }
3595                                                        if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
3596                                                        {
3597                                                                $arry_diff = is_array($search_criteria) ? array_diff($flagged_msgs,$search_criteria):$flagged_msgs;
3598                                                                foreach($arry_diff as $msg)
3599                                                                {
3600                                                                        $search_criteria[] = $msg;
3601                                                                }
3602                                                        }
3603                                                        else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
3604                                                        {
3605                                                                $search_criteria = array_diff($search_criteria,$flagged_msgs);
3606                                                        }
3607                        }
3608                                        }
3609                    if( is_array( $search_criteria) )
3610                                        {
3611                                                foreach($search_criteria as $new_search)
3612                                                {
3613                                                        $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3614                                                        $elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" );
3615                                                        $elem['uid'] = $new_search;
3616                                                        /* compare dates in ordering */
3617                                                        $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
3618                                                        $retorno[] = $elem;
3619                                                }
3620                                        }
3621                }
3622                        }
3623                }
3624               
3625                if($mbox_stream)
3626                {
3627                        imap_close($mbox_stream);
3628            }
3629           
3630            $num_msgs = count($retorno);
3631
3632            /* Comparison functions, descendent is ascendent with parms inverted */
3633            function SORTDATE($a, $b){ return ($a['udatecomp'] < $b['udatecomp']); }
3634            function SORTDATE_REVERSE($b, $a) { return SORTDATE($a,$b); }
3635
3636            function SORTWHO($a, $b) { return (strtoupper($a['from']) > strtoupper($b['from'])); }
3637            function SORTWHO_REVERSE($b, $a) { return SORTWHO($a,$b); }
3638
3639            function SORTSUBJECT($a, $b) { return (strtoupper($a['subject']) > strtoupper($b['subject'])); }
3640            function SORTSUBJECT_REVERSE($b, $a) { return SORTSUBJECT($a,$b); }
3641
3642            function SORTBOX($a, $b) { return ($a['boxname'] > $b['boxname']); }
3643            function SORTBOX_REVERSE($b, $a) { return SORTBOX($a,$b); }
3644
3645            function SORTSIZE($a, $b) { return ($a['size'] > $b['size']); }
3646            function SORTSIZE_REVERSE($b, $a) { return SORTSIZE($a,$b); }
3647
3648            usort( $retorno, $params['sort_type']);
3649            $pageret = array_slice( $retorno, $params['page'] * $this->prefs['max_email_per_page'], $this->prefs['max_email_per_page']);
3650           
3651            $arrayRetorno['num_msgs']   =  $num_msgs;
3652            $arrayRetorno['data']               =  $pageret;
3653            $arrayRetorno['currentTab'] =  $params['current_tab'];
3654
3655                if ($pageret)
3656                {
3657                        return $arrayRetorno;
3658                }
3659                else
3660                {
3661                        return 'none';
3662                }
3663        }
3664
3665        function get_msg_detail($uid_msg,$name_box, $mbox_stream )
3666        {
3667                $header = $this->get_header($uid_msg);
3668                require_once("class.imap_attachment.inc.php");
3669                $imap_attachment = new imap_attachment();
3670                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3671                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3672                $flag = $header->Unseen
3673                        .$header->Recent
3674                        .$header->Flagged
3675                        .$header->Draft
3676                        .$header->Answered
3677                        .$header->Deleted
3678                        .$attachments;
3679
3680
3681                $subject = $this->decode_string($header->fetchsubject);
3682                $from = $header->from[0]->mailbox;
3683                if($header->from[0]->personal != "")
3684                        $from = $header->from[0]->personal;
3685                $ret_msg['from']        = $this->decode_string($from);
3686                $ret_msg['subject']     = $subject;
3687                $ret_msg['udate']       = gmdate("d/m/Y",$header->udate + $this->functions->CalculateDateOffset());
3688                $ret_msg['size']        = $header->Size;
3689                $ret_msg['flag']        = $flag;
3690                return $ret_msg;
3691        }
3692
3693
3694        function size_msg($size){
3695                $var = floor($size/1024);
3696                if($var >= 1){
3697                        return $var." kb";
3698                }else{
3699                        return $size ." b";
3700                }
3701        }
3702       
3703        function ob_array($the_object)
3704        {
3705           $the_array=array();
3706           if(!is_scalar($the_object))
3707           {
3708               foreach($the_object as $id => $object)
3709               {
3710                   if(is_scalar($object))
3711                   {
3712                       $the_array[$id]=$object;
3713                   }
3714                   else
3715                   {
3716                       $the_array[$id]=$this->ob_array($object);
3717                   }
3718               }
3719               return $the_array;
3720           }
3721           else
3722           {
3723               return $the_object;
3724           }
3725        }
3726
3727        function getacl()
3728        {
3729                $this->ldap = new ldap_functions();
3730
3731                $return = array();
3732                $mbox_stream = $this->open_mbox();
3733                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3734
3735                $i = 0;
3736                foreach ($mbox_acl as $user => $acl)
3737                {
3738                        if ($user != $this->username)
3739                        {
3740                                $return[$i]['uid'] = $user;
3741                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3742                        }
3743                        $i++;
3744                }
3745                return $return;
3746        }
3747
3748        function setacl($params)
3749        {
3750                $old_users = $this->getacl();
3751                if (!count($old_users))
3752                        $old_users = array();
3753
3754                $tmp_array = array();
3755                foreach ($old_users as $index => $user_info)
3756                {
3757                        $tmp_array[$index] = $user_info['uid'];
3758                }
3759                $old_users = $tmp_array;
3760
3761                $users = unserialize($params['users']);
3762                if (!count($users))
3763                        $users = array();
3764
3765                //$add_share = array_diff($users, $old_users);
3766                $remove_share = array_diff($old_users, $users);
3767
3768                $mbox_stream = $this->open_mbox();
3769
3770                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3771                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3772
3773                /*if (count($add_share))
3774                {
3775                        foreach ($add_share as $index=>$uid)
3776                        {
3777                        if (is_array($mailboxes_list))
3778                        {
3779                        foreach ($mailboxes_list as $key => $val)
3780                        {
3781                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3782                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3783                        }
3784                        }
3785                        }
3786                }*/
3787
3788                if (count($remove_share))
3789                {
3790                    foreach ($remove_share as $index=>$uid)
3791                    {
3792                        if (is_array($mailboxes_list))
3793                        {
3794                            foreach ($mailboxes_list as $key => $val)
3795                            {
3796                                $folder = str_replace($serverString, "", $val->name);
3797                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3798                            }
3799                        }
3800                    }
3801                }
3802
3803                return true;
3804        }
3805
3806        function getaclfromuser($params)
3807        {
3808                $useracl = $params['user'];
3809
3810                $return = array();
3811                $return[$useracl] = 'false';
3812                $mbox_stream = $this->open_mbox();
3813                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3814
3815                foreach ($mbox_acl as $user => $acl)
3816                {
3817                        if (($user != $this->username) && ($user == $useracl))
3818                        {
3819                                $return[$user] = $acl;
3820                        }
3821                }
3822                return $return;
3823        }
3824
3825        function getacltouser($user)
3826        {
3827                $return = array();
3828                $mbox_stream = $this->open_mbox();
3829                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3830                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3831                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3832                if(substr($user,0,4) != 'user')
3833                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3834                else
3835                  $mbox_acl = imap_getacl($mbox_stream, $user);
3836                return $mbox_acl[$this->username];
3837        }
3838
3839
3840        function setaclfromuser($params)
3841        {
3842                $user = $params['user'];
3843                $acl = $params['acl'];
3844
3845                $mbox_stream = $this->open_mbox();
3846
3847                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3848                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3849
3850                if (is_array($mailboxes_list))
3851                {
3852                        foreach ($mailboxes_list as $key => $val)
3853                        {
3854                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3855                                $folder = str_replace("&-", "&", $folder);
3856                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3857                                {
3858                                        $return = imap_last_error();
3859                                }
3860                        }
3861                }
3862                if (isset($return))
3863                        return $return;
3864                else
3865                        return true;
3866        }
3867
3868        function download_attachment($msg,$msgno)
3869        {
3870                $array_parts_attachments = array();
3871                //$array_parts_attachments['names'] = '';
3872                include_once("class.imap_attachment.inc.php");
3873                $imap_attachment = new imap_attachment();
3874
3875                if (count($msg->fname[$msgno]) > 0)
3876                {
3877                        $i = 0;
3878                        foreach ($msg->fname[$msgno] as $index=>$fname)
3879                        {
3880                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3881                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
3882                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3883                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3884                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3885                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3886                                $i++;
3887                        }
3888                }
3889                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3890                return $array_parts_attachments;
3891        }
3892
3893        function spam($params)
3894        {
3895                $is_spam = $params['spam'];
3896                $folder = $params['folder'];
3897                $mbox_stream = $this->open_mbox($folder);
3898                $msgs_number = explode(',',$params['msgs_number']);
3899
3900                foreach($msgs_number as $msg_number) {
3901                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3902                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3903                        $body = imap_body($mbox_stream, $imap_msg_number);
3904                        $msg = $header . $body;
3905                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3906                        $username = $this->username;
3907                        strtok($email, '@');
3908                        $domain = strtok('@');
3909
3910                        //Encontrar a assinatura do dspam no cabecalho
3911                        $v = explode("\r\n", $header);
3912                        foreach ($v as $linha){
3913                                if (eregi("^Message-ID", $linha)) {
3914                                        $args = explode(" ", $linha);
3915                                        $msg_id = "'$args[1]'";
3916                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
3917                                        $args = explode(" ",$linha);
3918                                        $signature = $args[1];
3919                                }
3920                        }
3921
3922                        // Seleciona qual comando a ser executado
3923                        switch($is_spam){
3924                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
3925                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
3926                        }
3927
3928                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3929                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
3930                        system($cmd);
3931                }
3932                imap_close($mbox_stream);
3933                return false;
3934        }
3935        function get_header($msg_number){
3936                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3937                if (!is_object($header))
3938                        return false;
3939
3940                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3941                        $flag = preg_match('/importance *: *(.*)\r/i',
3942                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3943                                                ,$importance);
3944                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3945                }
3946
3947                return $header;
3948        }
3949
3950//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
3951///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.
3952
3953    function insert_email($source,$folder,$timestamp,$flags){
3954        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3955        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
3956        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3957        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
3958        $imap_options = '/notls/novalidate-cert';
3959        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3960        if(imap_last_error())
3961        {
3962            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3963        }
3964        if($timestamp){
3965            $tempDir = ini_get("session.save_path");
3966            $file = $tempDir."imap_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
3967                $f = fopen($file,"w");
3968                fputs($f,base64_encode($source));
3969            fclose($f);
3970            $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);
3971            $return['command']=exec(escapeshellcmd($command));
3972        }else{
3973            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3974        }
3975        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3976                       
3977        $return['msg_no'] = $status->uidnext - 1;
3978        $return['error'] = imap_last_error();
3979        if(!$return['error'] && $flags != '' ){
3980
3981                  $flags_array=explode(':',$flags);
3982                  //"Answered","Draft","Flagged","Unseen"
3983                  $flags_fixed = "";
3984                  if($flags_array[0] == 'A')
3985                        $flags_fixed.="\\Answered ";
3986                  if($flags_array[1] == 'X')
3987                        $flags_fixed.="\\Draft ";
3988                  if($flags_array[2] == 'F')
3989                        $flags_fixed.="\\Flagged ";
3990                  if($flags_array[3] != 'U')
3991                        $flags_fixed.="\\Seen ";
3992
3993                  imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
3994                }
3995        if($mbox_stream)
3996            imap_close($mbox_stream);
3997        return $return;
3998    }
3999
4000    function show_decript($params){
4001        $source = $params['source'];
4002        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
4003        $source = str_replace(" ", "+", $source,$i);
4004
4005        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
4006            if(!$source = base64_decode($source,true))
4007                return "error ".$source."Espaços ".$i;
4008
4009        }
4010        else {
4011            if(!$source = base64_decode($source))
4012                return "error ".$source."Espaços ".$i;
4013        }
4014
4015        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
4016
4017                $get['msg_number'] = $insert['msg_no'];
4018                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
4019                $return = $this->get_info_msg($get);
4020                $get['msg_number'] = $params['ID'];
4021                $get['msg_folder'] = $params['folder'];
4022                $tmp = $this->get_info_msg($get);
4023                if(!$tmp['status_get_msg_info'])
4024                {
4025                        $return['msg_day']=$tmp['msg_day'];
4026                        $return['msg_hour']=$tmp['msg_hour'];
4027                        $return['fulldate']=$tmp['fulldate'];
4028                        $return['smalldate']=$tmp['smalldate'];
4029                }
4030                else
4031                {
4032                        $return['msg_day']='';
4033                        $return['msg_hour']='';
4034                        $return['fulldate']='';
4035                        $return['smalldate']='';
4036                }
4037        $return['msg_no'] =$insert['msg_no'];
4038        $return['error'] = $insert['error'];
4039        $return['folder'] = $params['folder'];
4040        //$return['acls'] = $insert['acls'];
4041        $return['original_ID'] =  $params['ID'];
4042
4043        return $return;
4044
4045    }
4046
4047//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
4048//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
4049
4050    function treat_base64_from_post($source){
4051            $offset = 0;
4052            do
4053            {
4054                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
4055                    {
4056                            $inicio = strpos($source, "\n\r", $inicio);
4057                            $fim = strpos($source, '--', $inicio);
4058                            if(!$fim)
4059                                    $fim = strpos($source,"\n\r", $inicio);
4060                            $length = $fim-$inicio;
4061                            $parte = substr( $source,$inicio,$length-1);
4062                            $parte = str_replace(" ", "+", $parte);
4063                            $source = substr_replace($source, $parte, $inicio, $length-1);
4064                    }
4065                    if($offset > $inicio)
4066                    $offset=FALSE;
4067                    else
4068                    $offset = $inicio;
4069            }
4070            while($offset);
4071            return $source;
4072    }
4073
4074//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.
4075
4076    function unarchive_mail($params)
4077    {
4078        $dest_folder = $params['folder'];
4079        $sources = explode("#@#@#@",$params['source']);
4080        $timestamps = explode("#@#@#@",$params['timestamp']);
4081        $flags = explode("#@#@#@",$params['flags']);
4082
4083        foreach($sources as $index=>$src)
4084        {
4085            if($src!="")
4086            {
4087                $source = $this->treat_base64_from_post($src);
4088                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]);
4089            }
4090        }
4091       
4092        return $insert;
4093    }
4094
4095    function download_all_local_attachments($params)
4096    {
4097        $source = $params['source'];
4098        $source = $this->treat_base64_from_post($source);
4099        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
4100        $exporteml = new ExportEml();
4101        $params['num_msg']=$insert['msg_no'];
4102        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
4103        return $exporteml->download_all_attachments($params);
4104    }
4105    function get_quota_folders(){
4106
4107            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
4108            include_once("class.imapfp.inc.php");           
4109            $imapfp = new imapfp();
4110
4111            if(!$imapfp->open($this->imap_server,$this->imap_port))
4112                    return $imapfp->get_error();             
4113            if (!$imapfp->login( $this->username,$this->password ))
4114                    return $imapfp->get_error();
4115
4116            $response_array = $imapfp->get_mailboxes_size();
4117            if ($imapfp->error)
4118                    return $imapfp->get_error();
4119
4120            $data = array();
4121            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
4122            $data["quota_root"] = $quota_root;
4123
4124            foreach ($response_array as $idx=>$line) {
4125                    $line2 = str_replace('"', "", $line);
4126                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
4127                    list($folder,$size) = explode(";",$line2);
4128                    $quota_used = str_replace(")","",$size);
4129                    $quotaPercent = (($quota_used / 1024) / $data["quota_root"]["quota_limit"])*100;
4130                    $folder = mb_convert_encoding($folder, "ISO-8859-1", "UTF7-IMAP");
4131                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
4132                            $folder = $this->functions->getLang("Inbox");
4133                    }
4134                    else
4135                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
4136
4137                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
4138            }
4139            $imapfp->close();
4140            return $data;
4141    } 
4142}
4143?>
Note: See TracBrowser for help on using the repository browser.