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

Revision 5264, 199.8 KB checked in by acoutinho, 12 years ago (diff)

Ticket #2385 - Sem acao ao marcar flags em mensagens resultantes de pesquisa rapida

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