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

Revision 5079, 160.3 KB checked in by airton, 13 years ago (diff)

Ticket #2266 - Atualizar documentacao dos arquivos PHP

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