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

Revision 5243, 199.4 KB checked in by gustavo, 12 years ago (diff)

Ticket #2375 - Verificar problema ao alternar entre a interface web/mobile

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