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

Revision 5134, 195.4 KB checked in by wmerlotto, 12 years ago (diff)

Ticket #2305 - Enviando alteracoes, desenvolvidas internamente na Prognus, do modulo ExpressoMail?.

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