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

Revision 5266, 199.5 KB checked in by acoutinho, 12 years ago (diff)

Ticket #2392 - Inconsistencia ao anexar mensagens ao e-mail

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