source: sandbox/2.2.0.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 4493

Revision 4493, 154.6 KB checked in by adriano, 13 years ago (diff)

Ticket #812 - Melhorias nas interfaces de leitura e composiacao de email do Expresso Mail

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