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

Revision 4764, 155.5 KB checked in by roberto.santosjunior, 13 years ago (diff)

Ticket #1820 - Ordenação incorreta de mensagens. r4611

  • 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>'. htmlentities($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>'. htmlentities($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>'.  htmlentities($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") + $offset;                   
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'] = "";
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                $body = preg_replace("/text-indent:.*;/i","", $body);
1473               
1474                //Correção para compatibilização com Outlook, ao visualizar a mensagem
1475                $body = mb_ereg_replace('<!--\[','<!-- [',$body);
1476                $body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
1477                       
1478                return  "<div class=\"$wrapper_class\"><span>".$body.'</span></div>';
1479        }       
1480
1481       
1482       
1483        /**
1484        * @license   http://www.gnu.org/copyleft/gpl.html GPL
1485        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
1486        * @param     $body corpo da mensagem
1487        */
1488        function replace_links(&$body)
1489        {
1490                // Domains and IPs addresses found in the text and which is not a link yet should be replaced by one.
1491                // See more informations in www.iana.org
1492                $octets = array(
1493                        'first' => '(2[0-3][0-9]|1[0-9]{2}|[1-9][0-9]?)',
1494                        'middle' => '(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})',
1495                        'last' => '(25[0-4]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)'
1496                );
1497
1498                $ip = "\b{$octets[ 'first' ]}\.({$octets[ 'middle' ]}\.){2}{$octets[ 'last' ]}\b";
1499
1500                $top_level_domains = '(\.(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|as|asia|at|au|aw|ax|az|'
1501                        . 'ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bl|bm|bn|bo|br|bs|bt|bv|bw|by|bz|'
1502                        . 'ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|'
1503                        . 'de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|'
1504                        . 'ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|'
1505                        . 'hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|'
1506                        . 'ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|'
1507                        . 'ma|mc|md|me|mf|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|'
1508                        . 'mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|'
1509                        . 'pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|'
1510                        . 'sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|'
1511                        . 'tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|'
1512                        . 'ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))+\b';
1513               
1514                $path = '(?>\/[\w\d\/\.\'\(\)\-\+~?!&#@$%|:;,*=_]+)?';
1515                $port = '(?>:\d{2,5})?';
1516                $domain = '(?>[\w\d_\-]+)';
1517                $subdomain = "(?>{$domain}\.)*";
1518                $protocol = '(?>(http|ftp)(s)?:\/\/)?';
1519                $url = "(?>{$protocol}((?>{$subdomain}{$domain}{$top_level_domains}|{$ip}){$port}{$path}))";
1520
1521                $pattern = "/(<\w[^>]+|[\/\"'@=])?{$url}/";
1522               
1523                ini_set( 'pcre.backtrack_limit', 300000 );
1524                /*
1525                // PHP 5.3
1526                $replace = function( $matches )
1527                {
1528                        if ( $matches[ 1 ] )
1529                                return $matches[ 0 ];
1530
1531                        $url = ( $matches[ 2 ] ) ? $matches[ 2 ] : 'http';
1532                        $url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";
1533                        return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";
1534                };
1535                $body = preg_replace_callback( $pattern, $replace, $body );
1536                */
1537
1538                // PHP 5.2.x - Remover assim que possível
1539                $body = preg_replace_callback( $pattern,
1540                        create_function(
1541                                '$matches',
1542                                'if ( $matches[ 1 ] ) return $matches[ 0 ];'
1543                                        . '$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : "http";'
1544                                        . '$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";'
1545                                        . 'return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";'
1546                        ), $body
1547                );
1548                ini_set( 'pcre.backtrack_limit', 100000 );
1549
1550                // E-mail address in the text should create a new e-mail on ExpressoMail
1551                $pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im';
1552                $replacement = '$1<a href="mailto:$2">$2</a>$3';
1553                $body = preg_replace( $pattern, $replacement, $body );
1554
1555                return $body;
1556        }
1557
1558        function get_signature($msg, $msg_number, $msg_folder)
1559        {
1560            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1561            include_once("class.db_functions.inc.php");
1562            foreach ($msg->file_type[$msg_number] as $index => $file_type)
1563            {
1564                $sign = array();
1565                $temp = $this->get_info_head_msg($msg_number);
1566                if($temp['ContentType'] =='normal') return $sign;
1567                $file_type = strtolower($file_type);
1568                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
1569                {
1570                    if ($temp['ContentType'] == 'signature')
1571                    {
1572                        if(!$this->mbox || !is_resource($this->mbox))
1573                        $this->mbox = $this->open_mbox($msg_folder);
1574
1575                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
1576
1577                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1578                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
1579
1580                        $certificado = new certificadoB();
1581                        $validade = $certificado->verificar($imap_msg);
1582                                        $sign[] = $certificado->msg_sem_assinatura;
1583                        if ($certificado->apresentado)
1584                        {
1585                            $from = $header->from;
1586                            foreach ($from as $id => $object)
1587                            {
1588                                $fromname = $object->personal;
1589                                $fromaddress = $object->mailbox . "@" . $object->host;
1590                            }
1591                            foreach ($certificado->erros_ssl as $item)
1592                            {
1593                                $sign[] = $item . "#@#";
1594                            }
1595
1596                            if (count($certificado->erros_ssl) < 1)
1597                            {
1598                                $check_msg = 'Message untouched';
1599                                if(strtoupper($fromaddress) == strtoupper($certificado->dados['EMAIL']))
1600                                {
1601                                    $check_msg .= ' and authentic###';
1602                                }
1603                                else
1604                                {
1605                                    $check_msg .= ' with signer different from sender#@#';
1606                                }
1607                                $sign[] = $check_msg;
1608                            }
1609                                               
1610                            $sign[] = 'Message signed by: ###' . $certificado->dados['NOME'];
1611                            $sign[] = 'Certificate email: ###' . $certificado->dados['EMAIL'];
1612                            $sign[] = 'Mail from: ###' . $fromaddress;
1613                            $sign[] = 'Certificate Authority: ###' . $certificado->dados['EMISSOR'];
1614                            $sign[] = 'Validity of certificate: ###' . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
1615                            $sign[] = 'Message date: ###' . $header->Date;
1616
1617                            $cert = openssl_x509_parse($certificado->cert_assinante);
1618
1619                            $sign_alert = array();
1620                            $sign_alert[] = 'Certificate Owner###:\n';
1621                            $sign_alert[] = 'Common Name (CN)###  ' . $cert[subject]['CN'] .  '\n';
1622                            $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1623                            $sign_alert[]= 'Organization (O)###  ' . $cert[subject]['O'] .  '\n';
1624                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[subject]['OU'][0] .  '\n';
1625                            //$sign_alert[] = 'Serial Number### ' . $cert['serialNumber'] . '\n';
1626                            $sign_alert[] = 'Personal Data###:' . '\n';
1627                            $sign_alert[] = 'Birthday### ' . $X .  '\n';
1628                            $sign_alert[]= 'Fiscal Id### ' . $certificado->dados['CPF'] .  '\n';
1629                            $sign_alert[]= 'Identification### ' . $certificado->dados['RG'] .  '\n\n';
1630                            $sign_alert[]= 'Certificate Issuer###:\n';
1631                            $sign_alert[]= 'Common Name (CN)###  ' . $cert[issuer]['CN'] . '\n';
1632                            $sign_alert[]= 'Organization (O)###  ' . $cert[issuer]['O'] .  '\n';
1633                            $sign_alert[]= 'Organizational Unit (OU)### ' . $cert[issuer]['OU'][0] .  '\n\n';
1634                            $sign_alert[]= 'Validity###:\n';
1635                            $H = data_hora($cert[validFrom]);
1636                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1637                            $sign_alert[]= 'Valid From### ' . $X .  '\n';
1638                            $H = data_hora($cert[validTo]);
1639                            $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1640                            $sign_alert[]= 'Valid Until### ' . $X;
1641                            $sign[] = $sign_alert;
1642
1643                            $this->db = new db_functions();
1644                           
1645                            // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
1646                            if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
1647                                $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
1648                        }
1649                        else
1650                        {
1651                            $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
1652                            foreach($certificado->erros_ssl as $item)
1653                                $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
1654                        }
1655                    }
1656                }
1657            }
1658            return $sign;
1659        }
1660
1661       
1662        /**
1663        * @license   http://www.gnu.org/copyleft/gpl.html GPL
1664        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
1665        * @param     $images
1666        * @param     $msg_number
1667        * @param     $msg_folder
1668        */
1669        function get_thumbs($images, $msg_number, $msg_folder)
1670        {
1671
1672            $thumbs_array = array();
1673            $i = 0;
1674
1675            foreach ($images as $x => $image)
1676            {
1677                 if($x && $x == 'names')
1678                    continue;
1679                 
1680                 $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']." />";
1681                 $href = "./inc/show_img.php?msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$image['pid'];
1682                                 $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>";
1683                 $thumbs_array[] = $anchor;
1684                 $i++;
1685               
1686            }
1687            return $thumbs_array;
1688        }
1689
1690        /*function delete_msg($params)
1691        {
1692                $folder = $params['folder'];
1693                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
1694
1695                $mbox_stream = $this->open_mbox($folder);
1696
1697                foreach ($msgs_to_delete as $msg_number){
1698                        imap_delete($mbox_stream, $msg_number, FT_UID);
1699                }
1700                imap_close($mbox_stream, CL_EXPUNGE);
1701                return $params['msgs_to_delete'];
1702        }*/
1703
1704        // Novo
1705        function delete_msgs($params)
1706        {
1707               
1708                $folder = $params['folder'];
1709                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
1710                $msgs_number = explode(",",$params['msgs_number']);
1711                $border_ID = $params['border_ID'];
1712               
1713                $return = array();
1714               
1715                if ($params['get_previous_msg']){
1716                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1717                        // Fix problem in unserialize function JS.
1718                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1719                }
1720
1721                //$mbox_stream = $this->open_mbox($folder);             
1722                $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()))));
1723               
1724                foreach ($msgs_number as $msg_number)
1725                {
1726                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1727                                $return['msgs_number'][] = $msg_number;
1728                }
1729               
1730                $return['folder'] = $folder;
1731                $return['border_ID'] = $border_ID;
1732               
1733                if($mbox_stream)
1734                        imap_close($mbox_stream, CL_EXPUNGE);
1735                return $return;
1736        }
1737
1738
1739        function refresh($params)
1740        {
1741
1742                $folder = $params['folder'];
1743                $msg_range_begin = $params['msg_range_begin'];
1744                $msg_range_end = $params['msg_range_end'];
1745                $msgs_existent = $params['msgs_existent'];
1746                $sort_box_type = $params['sort_box_type'];
1747                $sort_box_reverse = $params['sort_box_reverse'];
1748                $msgs_in_the_server = array();
1749                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1750                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1751                $msgs_in_the_server = array_keys($msgs_in_the_server);
1752                if(!count($msgs_in_the_server))
1753                        return array();
1754
1755                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
1756                $msgs_in_the_client = explode(",", $msgs_existent);
1757
1758                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
1759                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
1760
1761                $msgs_to_exec = array();
1762                foreach($msg_to_insert as $msg_number)
1763                        $msgs_to_exec[] = $msg_number;
1764                //sort($msgs_to_exec);
1765
1766                $return = array();
1767                $i = 0;
1768                foreach($msgs_to_exec as $msg_number)
1769                {
1770                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
1771                        * atributos do cabeçalho. Como eu preciso do atributo Importance
1772                        * para saber se o email é importante ou não, uso abaixo a função
1773                        * imap_fetchheader e busco o atributo importance nela para passar
1774                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1775                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1776                        * não preciso reimplementar o método utilizando o fetchheader.
1777                        */
1778   
1779                        $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1780                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
1781                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
1782
1783                        $msg_sample = $this->get_msg_sample($msg_number);
1784                        $return[$i]['msg_sample'] = $msg_sample;
1785
1786                        $header = $this->get_header($msg_number);
1787                        if (!is_object($header))
1788                                continue;
1789
1790                        $return[$i]['msg_number']       = $msg_number;
1791                       
1792                        //get the next msg number to append this msg in the view in a correct place
1793                        $msg_key_position = array_search($msg_number, $msgs_in_the_server);
1794                       
1795                        $return[$i]['msg_key_position'] = $msg_key_position;
1796                        if($msg_key_position !== false && array_key_exists($msg_key_position + 1,$msgs_in_the_server) !== false)
1797                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position + 1];
1798                        else
1799                                $return[$i]['next_msg_number'] = $msgs_in_the_server[$msg_key_position];
1800
1801                        $return[$i]['msg_folder']       = $folder;
1802                        // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1803                        $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
1804                        $return[$i]['Recent']           = $header->Recent;
1805                        $return[$i]['Unseen']           = $header->Unseen;
1806                        $return[$i]['Answered']         = $header->Answered;
1807                        $return[$i]['Deleted']          = $header->Deleted;
1808                        $return[$i]['Draft']            = $header->Draft;
1809                        $return[$i]['Flagged']          = $header->Flagged;
1810
1811                        $return[$i]['udate'] = $header->udate;
1812               
1813                        $from = $header->from;
1814                        $return[$i]['from'] = array();
1815                        $tmp = imap_mime_header_decode($from[0]->personal);
1816                        $return[$i]['from']['name'] = $tmp[0]->text;
1817                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
1818                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
1819                        if(!$return[$i]['from']['name'])
1820                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
1821
1822                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1823                        $return[$i]['toaddress'] = '';
1824                        foreach ($toaddress as $tmp)
1825                                $return[$i]['toaddress'] .= $tmp->text;*/
1826                        $to = $header->to;
1827                        $return[$i]['to'] = array();
1828                        $tmp = imap_mime_header_decode($to[0]->personal);
1829                        $return[$i]['to']['name'] = $tmp[0]->text;
1830                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1831                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
1832                        $cc = $header->cc;
1833                        if ( ($cc) && (!$return[$i]['to']['name']) ){
1834                                $return[$i]['to']['name'] =  $cc[0]->personal;
1835                                $return[$i]['to']['email'] = $cc[0]->mailbox . "@" . $cc[0]->host;
1836                        }
1837                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1838
1839                        $return[$i]['Size'] = $header->Size;
1840                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
1841
1842                        $return[$i]['attachment'] = array();
1843                        if (!isset($imap_attachment))
1844                        {
1845                                include_once("class.imap_attachment.inc.php");
1846                                $imap_attachment = new imap_attachment();
1847                        }
1848                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
1849                        $i++;
1850                }
1851                $return['quota'] = $this->get_quota(array('folder_id' => $folder));
1852                $return['sort_box_type'] = $params['sort_box_type'];
1853                if(!$this->mbox || !is_resource($this->mbox))
1854                {
1855                    $this->open_mbox($folder);
1856                }
1857                $return['new_msgs'] = imap_num_recent($this->mbox);
1858                $return['msgs_to_delete'] = $msg_to_delete;
1859                $return['offsetToGMT'] = $this->functions->CalculateDateOffset();
1860                if($this->mbox && is_resource($this->mbox))
1861                        imap_close($this->mbox);
1862
1863                return $return;
1864        }
1865
1866     /**
1867     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1868     * assinado ou cifrado.
1869     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1870     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1871     * @param $msg_number O número da mesagem
1872     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1873     */
1874    function getMessageType($msg_number, $headers = false){
1875            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
1876            $contentType = "normal";
1877            if (!$headers){
1878                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1879            }
1880           
1881            if (preg_match("/pkcs7-signature/i", $headers) == 1){
1882                $contentType = "signature";
1883            } else if (preg_match("/pkcs7-mime/i", $headers) == 1){
1884                $contentType = testa_p7m( imap_body($this->mbox, imap_msgno($this->mbox, $msg_number)) );
1885            }
1886
1887            return $contentType;
1888    }
1889
1890         /**
1891     * Metodo que retorna todas as pastas do usuario logado.
1892     * @param $params array opcional para repassar os argumentos ao metodo.
1893     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
1894     * excluindo as compartilhadas para ele.
1895     * Se usar $params['folderType'] = "default" irá retornar somente as pastas defaults
1896     * Se usar $params['folderType'] = "personal" irá retornar somente as pastas pessoais
1897     * Se usar $params['folderType'] = null irá retornar todas as pastas
1898     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
1899     * folder_id, folder_name, folder_parent e folder_hasChildren.
1900     */
1901        function get_folders_list($params = null)
1902        {
1903                $mbox_stream = $this->open_mbox();
1904                if($params && $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
1905                        $this->delete_mailbox(array("del_past" => "INBOX".$this->imap_delimiter."decifradas"));
1906                }
1907
1908                $inbox = 'INBOX';
1909                $trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
1910                $drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
1911                $spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
1912                $sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
1913                $uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'];
1914                // Free others requests
1915                session_write_close();
1916
1917                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
1918               
1919                if ( $params && $params['noSharedFolders'] )
1920                        $folders_list = array_merge(imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ), imap_getmailboxes($mbox_stream, $serverString, 'INBOX/*' ) );
1921                else
1922                        $folders_list = imap_getmailboxes($mbox_stream, $serverString, '*' );
1923
1924                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1925
1926                $tmp = array();
1927                $resultMine = array();
1928                $resultDefault = array();
1929
1930                if (is_array($folders_list)) {
1931                        reset($folders_list);
1932                        $this->ldap = new ldap_functions();
1933
1934                        $i = 0;
1935                        while (list($key, $val) = each($folders_list)) {
1936                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
1937
1938                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1939                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
1940
1941                                if($tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas') {
1942                                        //error_log('passou', 3,'/tmp/imap_get_list.log');
1943                                        //imap_deletemailbox($mbox_stream,imap_utf7_encode("{".$this->imap_server."}".'INBOX/decifradas'));
1944                                        continue;
1945                                }
1946                                $result[$i]['folder_unseen'] = $status->unseen;
1947                                $folder_id = $tmp_folder_id[1];
1948                                $result[$i]['folder_id'] = $folder_id;
1949
1950                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1951                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1952                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1953                       
1954                                if ($uid2cn && substr($folder_id,0,4) == 'user') {
1955                                        //$this->ldap = new ldap_functions();
1956                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
1957                                                $result[$i]['folder_name'] = $cn;
1958                                        }
1959                                }
1960
1961                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1962                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
1963
1964                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1965                                        $result[$i]['folder_hasChildren'] = 1;
1966                                else
1967                                        $result[$i]['folder_hasChildren'] = 0;
1968
1969                                switch ($tmp_folder_id[1]) {
1970                                        case $inbox:
1971                                        case $sent:
1972                                        case $drafts:
1973                                        case $spam:
1974                                        case $trash:
1975                                                $resultDefault[]=$result[$i];
1976                                                break;
1977                                        default:
1978                                                $resultMine[]=$result[$i];
1979                                }
1980
1981                                $i++;
1982                        }
1983                }
1984
1985                if ( $params && !$params['noQuotaInfo'] ) {
1986                        //Get quota info of current folder
1987                        $current_folder = "INBOX";
1988                        if($params && $params['folder'])
1989                                $current_folder = $params['folder'];
1990
1991                        $arr_quota_info = $this->get_quota(array('folder_id' => $current_folder));
1992                } else {
1993                        $arr_quota_info = array();
1994                }
1995
1996                // Sorting resultMine
1997                foreach ($resultMine as $folder_info)
1998                {
1999                        $array_tmp[] = $folder_info['folder_id'];
2000                }
2001
2002                natcasesort($array_tmp);
2003               
2004                $result2 = array();
2005
2006                foreach ($array_tmp as $key => $folder_id)
2007                {
2008                        $result2[] = $resultMine[$key];
2009                }
2010               
2011                // Sorting resultDefault
2012                foreach ($resultDefault as $key => $folder_id)
2013                {
2014                        switch ($resultDefault[$key]['folder_id']) {
2015                                case $inbox:
2016                                        $resultDefault2[0] = $resultDefault[$key];
2017                                        break;
2018                                case $sent:
2019                                        $resultDefault2[1] = $resultDefault[$key];
2020                                        break;
2021                                case $drafts:
2022                                        $resultDefault2[2] = $resultDefault[$key];
2023                                        break;
2024                                case $spam:
2025                                        $resultDefault2[3] = $resultDefault[$key];
2026                                        break;
2027                                case $trash:
2028                                        $resultDefault2[4] = $resultDefault[$key];
2029                                        break;
2030                        }
2031                }
2032               
2033                if ( $params && $params['folderType'] && $params['folderType'] == 'default' )
2034                        return array_merge($resultDefault2, $arr_quota_info);
2035
2036                if ( $params && $params['folderType'] && $params['folderType'] == 'personal' )
2037                        return array_merge($result2, $arr_quota_info);
2038
2039                // Merge default folders and personal
2040                $result2 = array_merge($resultDefault2, $result2);
2041               
2042                return array_merge($result2, $arr_quota_info);
2043        }
2044
2045        function create_mailbox($arr)
2046        {
2047                $namebox        = $arr['newp'];
2048                $mbox_stream = $this->open_mbox();
2049                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2050                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
2051
2052                $result = "Ok";
2053                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
2054                {
2055                        $result = implode("<br />\n", imap_errors());
2056                }
2057
2058                if($mbox_stream)
2059                        imap_close($mbox_stream);
2060
2061                return $result;
2062
2063        }
2064
2065        function create_extra_mailbox($arr)
2066        {
2067                $nameboxs = explode(";",$arr['nw_folders']);
2068                $result = "";
2069                $mbox_stream = $this->open_mbox();
2070                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2071                foreach($nameboxs as $key=>$tmp){
2072                        if($tmp != ""){
2073                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
2074                                        $result = implode("<br />\n", imap_errors());
2075                                        if($mbox_stream)
2076                                                imap_close($mbox_stream);
2077                                        return $result;
2078                                }
2079                        }
2080                }
2081                if($mbox_stream)
2082                        imap_close($mbox_stream);
2083                return true;
2084        }
2085
2086        function delete_mailbox($arr)
2087        {
2088                $namebox = $arr['del_past'];
2089                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2090                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
2091                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
2092
2093                $result = "Ok";
2094                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
2095                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
2096                {
2097                        $result = implode("<br />\n", imap_errors());
2098                }
2099                /*
2100                if($mbox_stream)
2101                        imap_close($mbox_stream);
2102                */
2103                return $result;
2104        }
2105
2106        function ren_mailbox($arr)
2107        {
2108                $namebox = $arr['current'];
2109                $new_box = $arr['rename'];
2110                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2111                $mbox_stream = $this->open_mbox();
2112                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
2113
2114                $result = "Ok";
2115                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
2116                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
2117
2118                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
2119                {
2120                        $result = imap_errors();
2121                }
2122                if($mbox_stream)
2123                        imap_close($mbox_stream);
2124                return $result;
2125
2126        }
2127
2128        function get_num_msgs($params)
2129        {
2130                $folder = $params['folder'];
2131                if(!$this->mbox || !is_resource($this->mbox)) {
2132                        $this->mbox = $this->open_mbox($folder);
2133                        if(!$this->mbox || !is_resource($this->mbox))
2134                        return imap_last_error();
2135                }
2136                $num_msgs = imap_num_msg($this->mbox);
2137                if($this->mbox && is_resource($this->mbox))
2138                        imap_close($this->mbox);
2139
2140                return $num_msgs;
2141        }
2142
2143        function folder_exists($folder){
2144                $mbox =  $this->open_mbox();
2145                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";           
2146                $list = imap_getmailboxes($mbox,$serverString, $folder);
2147                $return = is_array($list);             
2148                imap_close($mbox);
2149                return $return;
2150        }
2151       
2152        function send_mail($params)
2153        {
2154                include_once("class.phpmailer.php");
2155                $mail = new PHPMailer();
2156                include_once("class.db_functions.inc.php");
2157                $db = new db_functions();
2158                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
2159                ##
2160                # @AUTHOR Rodrigo Souza dos Santos
2161                # @DATE 2008/09/17$fileName
2162                # @BRIEF Checks if the user has permission to send an email with the email address used.
2163                ##
2164                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
2165                {
2166                        $deny = true;
2167                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
2168                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
2169                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
2170
2171                        if ( $deny )
2172                                return "The server denied your request to send a mail, you cannot use this mail address.";
2173                }
2174
2175                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
2176                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
2177                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
2178                $replytoaddress = $params['input_replyto'];
2179                $subject = $params['input_subject'];
2180                $msg_uid = $params['msg_id'];
2181                $return_receipt = $params['input_return_receipt'];
2182                $is_important = $params['input_important_message'];
2183        $encrypt = $params['input_return_cripto'];
2184                $signed = $params['input_return_digital'];
2185
2186                if($params['smime'])
2187        {
2188            $body = $params['smime'];
2189            $mail->SMIME = true;
2190            // A MSG assinada deve ser testada neste ponto.
2191            // Testar o certificado e a integridade da msg....
2192            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2193            $erros_acumulados = '';
2194            $certificado = new certificadoB();
2195            $validade = $certificado->verificar($body);
2196            if(!$validade)
2197            {
2198                foreach($certificado->erros_ssl as $linha_erro)
2199                {
2200                    $erros_acumulados .= $linha_erro;
2201                }
2202            }
2203            else
2204            {
2205                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
2206                if ($certificado->apresentado)
2207                {
2208                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
2209                    $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;
2210                    if($certificado->dados['CPF'] != $this->cpf) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
2211                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
2212                }
2213                else
2214                {
2215                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
2216                }
2217            }
2218            if(!$erros_acumulados =='')
2219            {
2220                return $erros_acumulados;
2221            }
2222        }
2223        else
2224        {
2225            $body = $params['body'];
2226            //Compatibilização com Outlook, ao encaminhar a mensagem
2227            $body = mb_ereg_replace('<!--\[','<!-- [',$body);
2228        }
2229                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
2230                $attachments = $_FILES;
2231                $forwarding_attachments = $params['forwarding_attachments'];
2232                $local_attachments = $params['local_attachments'];
2233
2234                //Test if must be saved in shared folder and change if necessary
2235                if( $fromaddress[2] == 'y' ){
2236                        //build shared folder path
2237                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
2238                        if( $this->folder_exists($newfolder) ) $folder = $newfolder;
2239                        else $folder =  $params['folder'];                     
2240                } else  {
2241                        $folder = $params['folder'];                   
2242                }
2243               
2244                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2245                $folder_name = $params['folder_name'];
2246                // Fix problem with cyrus delimiter changes.
2247                // Dots in names: enabled/disabled.
2248                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2249                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2250                // End Fix.
2251                if ($folder != 'null'){
2252                        $mail->SaveMessageInFolder = $folder;
2253                }
2254////////////////////////////////////////////////////////////////////////////////////////////////////
2255                $mail->SMTPDebug = false;
2256
2257                if($signed && !$params['smime'])
2258                {
2259            $mail->Mailer = "smime";
2260                        $mail->SignedBody = true;
2261                }
2262                else
2263            $mail->IsSMTP();
2264
2265                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2266                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2267                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2268                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2269                if($fromaddress){
2270                        $mail->Sender = $mail->From;
2271                        $mail->SenderName = $mail->FromName;
2272                        $mail->FromName = $fromaddress[0];
2273                        $mail->From = $fromaddress[1];
2274                }
2275
2276                $this->add_recipients("to", $toaddress, &$mail);
2277                $this->add_recipients("cc", $ccaddress, &$mail);
2278                $this->add_recipients("cco", $ccoaddress, &$mail);
2279                $mail->AddReplyTo($replytoaddress);
2280                $mail->Subject = $subject;
2281                $mail->IsHTML( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
2282                $mail->Body = $body;
2283
2284        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
2285                {
2286                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
2287            $email = explode(",",$email);
2288            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
2289            // Deve ser verificado um numero limite de destinatarios.
2290            // Deve ser verificado se os certificados sao validos.
2291            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
2292            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
2293            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
2294            $erros_acumulados = "";
2295            $aux_mails = array();
2296            $mail_list = array();
2297            if(count($email) > $numero_maximo)
2298            {
2299                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2300                return $erros_acumulados;
2301            }
2302            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2303            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2304            foreach($email as $item)
2305            {
2306                $certificate = $db->get_certificate(strtolower($item));
2307                if(!$certificate)
2308                {
2309                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2310                    return $erros_acumulados;
2311                }
2312
2313                if (array_key_exists("dberr1", $certificate))
2314                {
2315
2316                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2317                    return $erros_acumulados;
2318                                }
2319                if (array_key_exists("dberr2", $certificate))
2320                {
2321                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2322                    //continue;
2323                }
2324                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2325                if (!array_key_exists("certs", $certificate))
2326                {
2327                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2328                    continue;
2329                }
2330            */
2331                include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
2332
2333                foreach ($certificate['certs'] as $registro)
2334                {
2335                    $c1 = new certificadoB();
2336                    $c1->certificado($registro['chave_publica']);
2337                    if ($c1->apresentado)
2338                    {
2339                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2340                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2341                        {
2342                            $aux_mails[] = $registro['chave_publica'];
2343                            $mail_list[] = strtolower($item);
2344                        }
2345                        else
2346                        {
2347                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2348                            {
2349                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2350                                    $c1->dados['EXPIRADO'],$c2->revogado);
2351                            }
2352
2353                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2354                            foreach($c2->erros_ssl as $linha)
2355                            {
2356                                $erros_acumulados .=  $linha . chr(0x0A);
2357                            }
2358                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2359                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2360                        }
2361                    }
2362                    else
2363                    {
2364                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2365                    }
2366                }
2367                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2368                                {
2369                                        return $erros_acumulados;
2370                        }
2371            }
2372
2373            $mail->Certs_crypt = $aux_mails;
2374        }
2375                // Build CID images
2376                $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2377
2378                //      Build Uploading Attachments!!!
2379                if (count($attachments)>0) //Caso seja forward normal...
2380                {
2381                        $total_uploaded_size = 0;
2382                        $upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
2383                        foreach ($attachments as $attach)
2384                        {
2385                                if($attach['error'] == UPLOAD_ERR_INI_SIZE)
2386                                    return $this->parse_error("message file too big");
2387                                if($attach['name']=='Unknown')
2388                                        continue;
2389                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2390                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2391                        }
2392                        if( $total_uploaded_size > $upload_max_filesize){
2393                                return $this->parse_error("message file too big");
2394                        }
2395                }
2396                if(count($local_attachments)>0) { //Caso seja forward de mensagens locais
2397
2398                        $total_uploaded_size = 0;
2399                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
2400                        foreach($local_attachments as $local_attachment) {
2401                                $file_description = unserialize(rawurldecode($local_attachment));
2402                                $tmp = array_values($file_description);
2403                                foreach($file_description as $i => $descriptor){
2404                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2405                                }
2406                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2407                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2408                        }
2409                        if( $total_uploaded_size > $upload_max_filesize)
2410                                return 'false';
2411                }
2412////////////////////////////////////////////////////////////////////////////////////////////////////
2413                //      Build Forwarding Attachments!!!
2414                if (count($forwarding_attachments) > 0)
2415                {
2416                        // Bug fixed for array_search function
2417                        $name_cid_files = array();
2418                        if(count($name_cid_files) > 0) {
2419                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2420                                $name_cid_files[0] = null;
2421                        }
2422
2423                        foreach($forwarding_attachments as $forwarding_attachment)
2424                        {
2425                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2426                                        $tmp = array_values($file_description);
2427                                        foreach($file_description as $i => $descriptor){
2428                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2429                                        }
2430                                        $file_description = $tmp;
2431                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2432                                        $fileName = $file_description[2];
2433                                        if(!array_search(trim($fileName),$name_cid_files)) {
2434                                                $mail->AddStringAttachment($fileContent,html_entity_decode(rawurldecode($fileName)), $file_description[4], $this->get_file_type($file_description[2]));
2435                                }
2436                        }
2437                }
2438
2439////////////////////////////////////////////////////////////////////////////////////////////////////
2440                // Important message
2441                if($is_important)
2442                        $mail->isImportant();
2443
2444////////////////////////////////////////////////////////////////////////////////////////////////////
2445                // Disposition-Notification-To
2446                if ($return_receipt)
2447                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2448////////////////////////////////////////////////////////////////////////////////////////////////////
2449
2450                $sent = $mail->Send();
2451
2452                if(!$sent)
2453                {
2454                        return $this->parse_error($mail->ErrorInfo);
2455                }
2456                else
2457                {
2458            if ($signed && !$params['smime'])
2459                        {
2460                                return $sent;
2461                        }
2462                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
2463                        {
2464                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2465                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
2466                                $now = date("d/m/y H:i:s");
2467                                $addrs = $toaddress.$ccaddress.$ccoaddress;
2468                                $sent = trim($sent);
2469                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2470                        }
2471                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
2472                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
2473                                $contacts = new dynamic_contacts();
2474                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2475                                return array("success" => true, "new_contacts" => $new_contacts);
2476                        }
2477                        return array("success" => true);
2478                }
2479        }
2480       
2481       
2482        /**
2483        * @license   http://www.gnu.org/copyleft/gpl.html GPL
2484        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
2485        * @param     $mail email
2486        * @param     $msg_uid uid da mensagem
2487        * @param     $forwarding_attachments anexos
2488        */
2489        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments)
2490        {
2491                //Build CID for embedded Images!!!
2492                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2493                $cid_imgs = '';
2494                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2495                $cid_array = array();
2496
2497                foreach($cid_imgs[6] as $j => $val){
2498                        if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2499                        {
2500                                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2501                        }
2502                        $cid = $cid_array[$cid_imgs[4][$j].$val];
2503
2504                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2505
2506                        $count    = strlen($cid_imgs[6][$j]);
2507                        $position = substr($cid_imgs[6][$j], 2, $count);
2508                        $position--;
2509                                       
2510                        $attach_img = $forwarding_attachments[$position];
2511                        $file_description = unserialize(rawurldecode($attach_img));
2512                       
2513                        if (is_array($file_description))
2514                                foreach($file_description as $i => $descriptor)                         
2515                                        $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2516
2517                        // The image is not in the same mail?
2518                        if ($msg_uid != $cid_imgs[4][$j])
2519                        {
2520                                $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2521                                $fileName = ($msg_uid != 'undefined') ? "image_".($j).".jpg" : $file_description[2];
2522                                $fileCode = "base64";
2523                                $fileType = "image/jpg";
2524                                $file_attached[0] = $cid_imgs[2][$j];
2525                                $file_attached[1] = $cid_imgs[4][$j];
2526                                $file_attached[2] = $fileName;
2527                                $file_attached[3] = '0.'.($j+1);
2528                                $file_attached[4] = 'base64';
2529                                $file_attached[5] = strlen($fileContent); //Size of file
2530                                $file_attached[6] = $cid_imgs[6][$j];
2531                                $return_forward[] = $file_attached;
2532
2533                                if ($file_attached[3] == $file_description[3] || $msg_uid == 'undefined')
2534                                        unset($forwarding_attachments[$position]);
2535                               
2536                        }
2537                        else
2538                        {
2539                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2540                                $fileName = $file_description[2];
2541                                $fileCode = $file_description[4];
2542                                $file_description[3] = '0.'.($j+1);
2543                                $file_description[6] = $cid_imgs[6][$j];
2544                                $fileType = $this->get_file_type($file_description[2]);
2545                                unset($forwarding_attachments[$position]);
2546                                if (!empty($file_description))
2547                                {
2548                                        $file_description[5] = strlen($fileContent); //Size of file
2549                                        $return_forward[] = $file_description;
2550                                }
2551                        }
2552                        $tempDir = '/tmp';
2553                        $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                       
2554                        $f = fopen($tempDir.'/'.$file,"w");
2555                        fputs($f,$fileContent);
2556                        fclose($f);
2557
2558                        if ($fileContent)
2559                                $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);                                     
2560                }
2561                       
2562                return $return_forward;
2563        }
2564        function add_recipients_cert($full_address)
2565        {
2566                $result = "";
2567                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2568                foreach ($parse_address as $val)
2569                {
2570                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2571                        if ($val->mailbox == "INVALID_ADDRESS")
2572                                continue;
2573                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2574                                continue;
2575                        if (empty($val->personal))
2576                                $result .= $val->mailbox."@".$val->host . ",";
2577                        else
2578                                $result .= $val->mailbox."@".$val->host . ",";
2579                }
2580
2581                return substr($result,0,-1);
2582        }
2583
2584        function add_recipients($recipient_type, $full_address, $mail)
2585        {
2586                //remove a comma if is given two unexpected commas
2587                $full_address = preg_replace("/, ?,/",",",$full_address);
2588                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2589                foreach ($parse_address as $val)
2590                {
2591                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2592                        if ($val->mailbox == "INVALID_ADDRESS")
2593                                continue;
2594
2595                        if (empty($val->personal))
2596                        {
2597                                switch($recipient_type)
2598                                {
2599                                        case "to":
2600                                                $mail->AddAddress($val->mailbox."@".$val->host);
2601                                                break;
2602                                        case "cc":
2603                                                $mail->AddCC($val->mailbox."@".$val->host);
2604                                                break;
2605                                        case "cco":
2606                                                $mail->AddBCC($val->mailbox."@".$val->host);
2607                                                break;
2608                                }
2609                        }
2610                        else
2611                        {
2612                                switch($recipient_type)
2613                                {
2614                                        case "to":
2615                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2616                                                break;
2617                                        case "cc":
2618                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2619                                                break;
2620                                        case "cco":
2621                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2622                                                break;
2623                                }
2624                        }
2625                }
2626                return true;
2627        }
2628
2629        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2630        {
2631            include_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
2632            $attachment = new attachment();
2633            $attachment->setStructureFromMail($msg_folder, $msg_number);
2634            return $attachment->getAttachment($msg_part);
2635        }
2636
2637        function del_last_caracter($string)
2638        {
2639                $string = substr($string,0,(strlen($string) - 1));
2640                return $string;
2641        }
2642
2643        function del_last_two_caracters($string)
2644        {
2645                $string = substr($string,0,(strlen($string) - 2));
2646                return $string;
2647        }
2648
2649        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
2650        {
2651                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
2652                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2653                        foreach($imapsort as $iuid)
2654                                $sort[$iuid] = "";
2655                       
2656                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2657                                $slice_array = false;
2658                        else
2659                                $slice_array = true;
2660                }
2661                else
2662                {
2663                        $sort = array();
2664                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2665                        $num_msgs = imap_num_msg($this->mbox);
2666                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
2667                        $slice_array = true;
2668
2669                        for ($i=$num_msgs; $i>0; $i--)
2670                        {
2671                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2672                                        break;
2673                                $iuid = @imap_uid($this->mbox,$i);
2674                                $header = $this->get_header($iuid);
2675                                // List UNSEEN messages.
2676                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2677                                        continue;
2678                                }
2679                                // List SEEN messages.
2680                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2681                                        continue;
2682                                }
2683                                // List ANSWERED messages.
2684                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2685                                        continue;
2686                                }
2687                                // List FLAGGED messages.
2688                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2689                                        continue;
2690                                }
2691
2692                                if($sort_box_type=='SORTFROM') {
2693                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
2694                                                $from = $header->to;
2695                                        else
2696                                                $from = $header->from;
2697
2698                                        $tmp = imap_mime_header_decode($from[0]->personal);
2699
2700                                        if ($tmp[0]->text != "")
2701                                                $sort[$iuid] = $tmp[0]->text;
2702                                        else
2703                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2704                                }
2705                                else if($sort_box_type=='SORTSUBJECT') {
2706                                        $sort[$iuid] = $header->subject;
2707                                }
2708                                else if($sort_box_type=='SORTSIZE') {
2709                                        $sort[$iuid] = $header->Size;
2710                                }
2711                                else {
2712                                        $sort[$iuid] = $header->udate;
2713                                }
2714
2715                        }
2716                        natcasesort($sort);
2717
2718                        if ($sort_box_reverse)
2719                                $sort = array_reverse($sort,true);
2720                }
2721
2722                if(!is_array($sort))
2723                        $sort = array();
2724
2725
2726                if ($slice_array)
2727                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
2728
2729
2730                return $sort;
2731
2732        }
2733
2734
2735        function move_search_messages($params){
2736                $params['selected_messages'] = urldecode($params['selected_messages']);
2737                $params['new_folder'] = urldecode($params['new_folder']);
2738                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2739                $sel_msgs = explode(",", $params['selected_messages']);
2740                @reset($sel_msgs);
2741                $sorted_msgs = array();
2742                foreach($sel_msgs as $idx => $sel_msg) {
2743                        $sel_msg = explode(";", $sel_msg);
2744                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2745                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
2746                         }
2747                         else {
2748                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2749                         }
2750                }
2751                @ksort($sorted_msgs);
2752                $last_return = false;
2753                foreach($sorted_msgs as $folder => $msgs_number) {
2754                        $params['msgs_number'] = $msgs_number;
2755                        $params['folder'] = $folder;
2756                        if($params['new_folder'] && $folder != $params['new_folder']){
2757                                $last_return = $this -> move_messages($params);
2758                        }
2759                        elseif(!$params['new_folder'] || $params['delete'] ){
2760                                $last_return = $this -> delete_msgs($params);
2761                                $last_return['deleted'] = true;
2762                        }
2763                }
2764                return $last_return;
2765        }
2766
2767        function move_messages($params)
2768        {
2769                $folder = $params['folder'];
2770                $mbox_stream = $this->open_mbox($folder);
2771                $newmailbox = ($params['new_folder']);
2772                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
2773                $new_folder_name = $params['new_folder_name'];
2774                $msgs_number = $params['msgs_number'];
2775                $return = array('msgs_number' => $msgs_number,
2776                                                'folder' => $folder,
2777                                                'new_folder_name' => $new_folder_name,
2778                                                'border_ID' => $params['border_ID'],
2779                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
2780
2781                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2782        if (substr($folder,0,4) == 'user'){
2783                $acl = $this->getacltouser($folder);
2784                /*
2785                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2786                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2787                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2788                 *   w - write (STORE flags other than SEEN and DELETED)
2789                 *   i - insert (perform APPEND, COPY into mailbox)
2790                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2791                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2792                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2793                 *   a - administer (perform SETACL)
2794                        */
2795                        if (strpos($acl, "d") === false){
2796                                $return['status'] = false;
2797                                return $return;
2798                        }
2799        }
2800        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
2801        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
2802            if (substr($new_folder_name,0,4) == 'user'){
2803                $this->ldap = new ldap_functions();
2804                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
2805                $return['new_folder_name'] = array_pop($tmp_folder_name);
2806                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2807                {
2808                    $return['new_folder_name'] = $cn;
2809                }
2810            }
2811        }
2812
2813                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
2814                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
2815                {
2816                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2817                        // Fix problem in unserialize function JS.
2818                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2819                }
2820
2821                $mbox_stream = $this->open_mbox($folder);
2822                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2823                        imap_expunge($mbox_stream);
2824                        if($mbox_stream)
2825                                imap_close($mbox_stream);
2826                        return $return;
2827                }else {
2828                        if(strstr(imap_last_error(),'Over quota')) {
2829                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
2830                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
2831                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2832                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2833                                $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()))));
2834                                if(!$mbox)
2835                                        return imap_last_error();
2836                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
2837                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
2838                                        if($mbox_stream)
2839                                                imap_close($mbox_stream);
2840                                        if($mbox)
2841                                                imap_close($mbox);
2842                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
2843                                }
2844                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2845                                        imap_expunge($mbox_stream);
2846                                        if($mbox_stream)
2847                                                imap_close($mbox_stream);
2848                                        // return to original quota limit.
2849                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2850                                                if($mbox)
2851                                                        imap_close($mbox);
2852                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2853                                        }
2854                                        return $return;
2855                                }
2856                                else {
2857                                        if($mbox_stream)
2858                                                imap_close($mbox_stream);
2859                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2860                                                if($mbox)
2861                                                        imap_close($mbox);
2862                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2863                                        }
2864                                        return imap_last_error();
2865                                }
2866
2867                        }
2868                        else {
2869                                if($mbox_stream)
2870                                        imap_close($mbox_stream);
2871                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
2872                        }
2873                }
2874        }
2875
2876        function save_msg($params)
2877        {
2878
2879        include_once("class.phpmailer.php");
2880                $mail = new PHPMailer();
2881                include_once("class.db_functions.inc.php");
2882                $toaddress    = $params['input_to'];
2883                $ccaddress    = $params['input_cc'];
2884                $ccoaddress = $params['input_cco'];
2885        $return_receipt = $params['input_return_receipt'];
2886        $is_important = $params['input_important_message'];
2887                $subject      = $params['input_subject'];
2888                $msg_uid      = $params['msg_id'];
2889                $body         = $params['body'];
2890                $body = str_replace("%nbsp;","&nbsp;",$body);
2891                $body = preg_replace("/\n/"," ",$body);
2892                $body = preg_replace("/\r/","",$body);
2893                $forwarding_attachments = $params['forwarding_attachments'];
2894                $attachments  = $params['FILES'];
2895                $return_files = $params['FILES'];
2896
2897                 
2898                $folder = $params['folder'];
2899                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
2900                // Fix problem with cyrus delimiter changes.
2901                // Dots in names: enabled/disabled.                             
2902                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2903                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2904                // End Fix.
2905                                       
2906                $mail->SaveMessageInFolder = $folder;
2907                $mail->SMTPDebug = false;
2908                                               
2909                $mail->IsSMTP();
2910                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2911                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2912                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2913                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2914               
2915                $mail->Sender = $mail->From;
2916                $mail->SenderName = $mail->FromName;
2917                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2918                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
2919                               
2920                $this->add_recipients("to", $toaddress, &$mail);
2921                $this->add_recipients("cc", $ccaddress, &$mail);
2922                $mail->Subject = $subject;
2923                $mail->IsHTML(true);
2924                $mail->Body = $body;
2925
2926                $return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2927                $imagesParts = array();
2928               
2929                foreach ($return_forward as $value)
2930                        $imagesParts[$value[6]] = $value[3];   
2931
2932                //Build Forwarding Attachments!!!                   
2933                foreach($forwarding_attachments as $forwarding_attachment)
2934                {
2935                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2936                        $file_description = array_values($file_description);
2937                                       
2938                                foreach($file_description as $i => $descriptor){                                 
2939                                                        $file_description[$i] = eregi_replace('\'*\'','',$descriptor);
2940                                                }
2941                                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2942                                                $fileName = $file_description[2];
2943                                                 
2944                                                $file_description[5] = strlen($fileContent); //Size of file
2945                                                $return_forward[] = $file_description;
2946                                         
2947                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2948                }
2949               
2950                if ((count($return_forward) > 0) && (count($return_files) > 0))
2951                {
2952                        $return_files = array_merge_recursive($return_forward,$return_files);
2953                }
2954                else if (count($return_files) < 1)
2955                {
2956                        $return_files = $return_forward;
2957                }
2958
2959                //Build Uploading Attachments!!!
2960                $sizeof_attachments = count($attachments);
2961                if ($sizeof_attachments)
2962                {
2963                        foreach ($attachments as $numb => $attach)
2964                        {
2965                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true')
2966                                { // Auto-resize image
2967                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2968                                        switch ($image_type)
2969                                        {
2970                                                // Do not corrupt animated gif
2971                                                //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
2972                                                case 2:
2973                                                        $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2974                                                case 3:
2975                                                        $image_big = imagecreatefrompng($attach['tmp_name']); break;
2976                                                case 6:
2977                                                        require_once("gd_functions.php");
2978                                                        $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2979                                                default:
2980                                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2981                                                        break;
2982                                        }
2983                                        header('Content-type: image/jpeg');
2984                                        $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
2985                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2986                                        if ($width < $max_resolution && $height < $max_resolution)
2987                                        {
2988                                                $new_width = $width;
2989                                                $new_height = $height;
2990                                        }
2991                                        else if ($width > $max_resolution)
2992                                        {
2993                                                $new_width = $max_resolution;
2994                                                $new_height = $height*($new_width/$width);
2995                                        }
2996                                        else
2997                                        {
2998                                                $new_height = $max_resolution;
2999                                                $new_width = $width*($new_height/$height);
3000                                        }
3001                                        $image_new = imagecreatetruecolor($new_width, $new_height);
3002                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
3003                                        $tmpDir = '/tmp';
3004
3005                                       // $tmpDir = ini_get("session.save_path");
3006                                        $_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
3007                                        imagejpeg($image_new,$tmpDir.$_file, 85);
3008                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
3009                                }
3010                                else
3011                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
3012                               
3013                        }
3014                }
3015               
3016                if(!empty($mail->AltBody))
3017                    $mail->ContentType = "multipart/alternative";
3018
3019                $mail->error_count = 0; // reset errors
3020                $mail->SetMessageType();
3021                $header = $mail->CreateHeader();
3022                $body   = $mail->CreateBody();
3023
3024                $mbox_stream = $this->open_mbox($folder);       
3025                $new_header  = str_replace("\n", "\r\n", $header);
3026                $new_body    = str_replace("\n", "\r\n", $body);
3027                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
3028                $status      = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3029                $return['msg_no'] = $status->uidnext - 1;
3030                $return['folder_id'] = $folder;
3031                $return['imagesParts'] = $imagesParts;
3032
3033                if($mbox_stream)
3034                        imap_close($mbox_stream);
3035                       
3036                if (is_array($return_files))
3037                {
3038                        foreach ($return_files as $index => $_attachment)
3039                        {
3040                                if (array_key_exists("name", $_attachment))
3041                                {
3042                                        unset($return_files[$index]);
3043                                        $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
3044                                }
3045                                else
3046                                {
3047                                        unset($return_files[$index]);
3048                                        $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
3049                                }
3050                        }
3051                }
3052               
3053                $return['files'] = serialize($return_files);
3054                $return["subject"] = $subject;
3055                               
3056                if (!$return['append'])
3057                        $return['append'] = imap_last_error();
3058
3059                return $return;
3060        }
3061
3062        function set_messages_flag($params)
3063        {
3064                $folder = $params['folder'];
3065                $msgs_to_set = $params['msgs_to_set'];
3066                $flag = $params['flag'];
3067                $return = array();
3068                $return["msgs_to_set"] = $msgs_to_set;
3069                $return["flag"] = $flag;
3070
3071                if(!$this->mbox && !is_resource($this->mbox))
3072                        $this->mbox = $this->open_mbox($folder);
3073
3074                if ($flag == "unseen")
3075                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
3076                elseif ($flag == "seen")
3077                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
3078                elseif ($flag == "answered"){
3079                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
3080                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
3081                }
3082                elseif ($flag == "forwarded")
3083                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
3084                elseif ($flag == "flagged")
3085                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
3086                elseif ($flag == "unflagged") {
3087                        $flag_importance = false;
3088                        $msgs_number = explode(",",$msgs_to_set);
3089                        $unflagged_msgs = "";
3090                        foreach($msgs_number as $msg_number) {
3091                                preg_match('/importance *: *(.*)\r/i',
3092                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3093                                        ,$importance);
3094                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3095                                        $flag_importance=true;
3096                                }
3097                                else {
3098                                        $unflagged_msgs.=$msg_number.",";
3099                                }
3100                        }
3101
3102                        if($unflagged_msgs!="") {
3103                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
3104                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
3105                        }
3106                        else {
3107                                $return["msgs_unflageds"] = false;
3108                        }
3109
3110                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3111                                $return["status"] = false;
3112                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
3113                        }
3114                        else {
3115                                $return["status"] = true;
3116                        }
3117                }
3118
3119                if($this->mbox && is_resource($this->mbox))
3120                        imap_close($this->mbox);
3121                return $return;
3122        }
3123
3124        function get_file_type($file_name)
3125        {
3126                $file_name = strtolower($file_name);
3127                $strFileType = strrev(substr(strrev($file_name),0,4));
3128                if ($strFileType == ".asf")
3129                        return "video/x-ms-asf";
3130                if ($strFileType == ".avi")
3131                        return "video/avi";
3132                if ($strFileType == ".doc")
3133                        return "application/msword";
3134                if ($strFileType == ".zip")
3135                        return "application/zip";
3136                if ($strFileType == ".xls")
3137                        return "application/vnd.ms-excel";
3138                if ($strFileType == ".gif")
3139                        return "image/gif";
3140                if ($strFileType == ".jpg" || $strFileType == "jpeg")
3141                        return "image/jpeg";
3142                if ($strFileType == ".png")
3143                        return "image/png";
3144                if ($strFileType == ".wav")
3145                        return "audio/wav";
3146                if ($strFileType == ".mp3")
3147                        return "audio/mpeg3";
3148                if ($strFileType == ".mpg" || $strFileType == "mpeg")
3149                        return "video/mpeg";
3150                if ($strFileType == ".rtf")
3151                        return "application/rtf";
3152                if ($strFileType == ".htm" || $strFileType == "html")
3153                        return "text/html";
3154                if ($strFileType == ".xml")
3155                        return "text/xml";
3156                if ($strFileType == ".xsl")
3157                        return "text/xsl";
3158                if ($strFileType == ".css")
3159                        return "text/css";
3160                if ($strFileType == ".php")
3161                        return "text/php";
3162                if ($strFileType == ".asp")
3163                        return "text/asp";
3164                if ($strFileType == ".pdf")
3165                        return "application/pdf";
3166                if ($strFileType == ".txt")
3167                        return "text/plain";
3168                if ($strFileType == ".wmv")
3169                        return "video/x-ms-wmv";
3170                if ($strFileType == ".sxc")
3171                        return "application/vnd.sun.xml.calc";
3172                if ($strFileType == ".stc")
3173                        return "application/vnd.sun.xml.calc.template";
3174                if ($strFileType == ".sxd")
3175                        return "application/vnd.sun.xml.draw";
3176                if ($strFileType == ".std")
3177                        return "application/vnd.sun.xml.draw.template";
3178                if ($strFileType == ".sxi")
3179                        return "application/vnd.sun.xml.impress";
3180                if ($strFileType == ".sti")
3181                        return "application/vnd.sun.xml.impress.template";
3182                if ($strFileType == ".sxm")
3183                        return "application/vnd.sun.xml.math";
3184                if ($strFileType == ".sxw")
3185                        return "application/vnd.sun.xml.writer";
3186                if ($strFileType == ".sxq")
3187                        return "application/vnd.sun.xml.writer.global";
3188                if ($strFileType == ".stw")
3189                        return "application/vnd.sun.xml.writer.template";
3190
3191
3192                return "application/octet-stream";
3193        }
3194
3195        function htmlspecialchars_encode($str)
3196        {
3197                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
3198        }
3199        function htmlspecialchars_decode($str)
3200        {
3201                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
3202        }
3203
3204        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
3205        {
3206                if(!$this->mbox || !is_resource($this->mbox))
3207                        $this->mbox = $this->open_mbox($folder);
3208
3209                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
3210        }
3211
3212        function get_info_next_msg($params)
3213        {
3214                $msg_number = $params['msg_number'];
3215                $folder = $params['msg_folder'];
3216                $sort_box_type = $params['sort_box_type'];
3217                $sort_box_reverse = $params['sort_box_reverse'];
3218                $reuse_border = $params['reuse_border'];
3219                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
3220                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
3221
3222                $success = false;
3223                if (is_array($sort_array_msg))
3224                {
3225                        foreach ($sort_array_msg as $i => $value){
3226                                if ($value == $msg_number)
3227                                {
3228                                        $success = true;
3229                                        break;
3230                                }
3231                        }
3232                }
3233
3234                if (! $success || $i >= sizeof($sort_array_msg)-1)
3235                {
3236                        $params['status'] = 'false';
3237                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3238                        return $params;
3239                }
3240
3241                $params = array();
3242                $params['msg_number'] = $sort_array_msg[($i+1)];
3243                $params['msg_folder'] = $folder;
3244
3245                $return = $this->get_info_msg($params);
3246                $return["reuse_border"] = $reuse_border;
3247                return $return;
3248        }
3249
3250        function get_info_previous_msg($params)
3251        {
3252                $msg_number = $params['msgs_number'];
3253                $folder = $params['folder'];
3254                $sort_box_type = $params['sort_box_type'];
3255                $sort_box_reverse = $params['sort_box_reverse'];
3256                $reuse_border = $params['reuse_border'];
3257                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
3258                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
3259
3260                $success = false;
3261                if (is_array($sort_array_msg))
3262                {
3263                        foreach ($sort_array_msg as $i => $value){
3264                                if ($value == $msg_number)
3265                                {
3266                                        $success = true;
3267                                        break;
3268                                }
3269                        }
3270                }
3271                if (! $success || $i == 0)
3272                {
3273                        $params['status'] = 'false';
3274                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
3275                        return $params;
3276                }
3277
3278                $params = array();
3279                $params['msg_number'] = $sort_array_msg[($i-1)];
3280                $params['msg_folder'] = $folder;
3281
3282                $return = $this->get_info_msg($params);
3283                $return["reuse_border"] = $reuse_border;
3284                return $return;
3285        }
3286
3287        // This function updates the values: quota, paging and new messages menu.
3288        function get_menu_values($params){
3289                $return_array = array();
3290                $return_array = $this->get_quota($params);
3291
3292                $mbox_stream = $this->open_mbox($params['folder']);
3293                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
3294                if($mbox_stream)
3295                        imap_close($mbox_stream);
3296
3297                return $return_array;
3298        }
3299
3300        function get_quota($params){
3301                // folder_id = user/{uid} for shared folders
3302                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
3303                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
3304                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
3305                }
3306                // folder_id = INBOX for inbox folders
3307                else
3308                        $folder_id = "INBOX";
3309
3310                if(!$this->mbox || !is_resource($this->mbox))
3311                        $this->mbox = $this->open_mbox();
3312
3313                $quota = imap_get_quotaroot($this->mbox, $folder_id);
3314                if($this->mbox && is_resource($this->mbox))
3315                        imap_close($this->mbox);
3316
3317                if (!$quota){
3318                        return array(
3319                                'quota_percent' => 0,
3320                                'quota_used' => 0,
3321                                'quota_limit' =>  0
3322                        );
3323                }
3324
3325                if(count($quota) && $quota['limit']) {
3326                        $quota_limit = $quota['limit'];
3327                        $quota_used  = $quota['usage'];
3328                        if($quota_used >= $quota_limit)
3329                        {
3330                                $quotaPercent = 100;
3331                        }
3332                        else
3333                        {
3334                        $quotaPercent = ($quota_used / $quota_limit)*100;
3335                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
3336                        }
3337                        return array(
3338                                'quota_percent' => floor($quotaPercent),
3339                                'quota_used' => $quota_used,
3340                                'quota_limit' =>  $quota_limit
3341                        );
3342                }
3343                else
3344                        return array();
3345        }
3346
3347        function send_notification($params){
3348                include("../header.inc.php");
3349                require_once("class.phpmailer.php");
3350                $mail = new PHPMailer();
3351
3352                $toaddress = $params['notificationto'];
3353
3354                $subject = lang("Read receipt: %1",$params['subject']);
3355                $body = lang("Your message: %1",$params['subject']) . '<br>';
3356                $body .= lang("Received in: %1",date("d/m/Y H:i",$params['date'])) . '<br>';
3357                $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"));
3358                $mail->SMTPDebug = false;
3359                $mail->IsSMTP();
3360                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
3361                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
3362                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3363                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
3364                $mail->AddAddress($toaddress);
3365                $mail->Subject = $this->htmlspecialchars_decode($subject);
3366
3367                $mail->IsHTML(true);
3368                $mail->Body = $body;
3369
3370                if(!$mail->Send()){
3371                        return $mail->ErrorInfo;
3372                }
3373                else
3374                        return true;
3375        }
3376
3377        function empty_folder($params)
3378        {
3379                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
3380                $mbox_stream = $this->open_mbox($folder);
3381                $return = imap_delete($mbox_stream,'1:*');
3382                if($mbox_stream)
3383                        imap_close($mbox_stream, CL_EXPUNGE);
3384                return $return;
3385        }
3386
3387        function search($params)
3388        {
3389                include("class.imap_attachment.inc.php");
3390                $imap_attachment = new imap_attachment();
3391                $criteria = $params['criteria'];
3392                $return = array();
3393                $folders = $this->get_folders_list();
3394
3395                $j = 0;
3396                foreach($folders as $folder)
3397                {
3398                        $mbox_stream = $this->open_mbox($folder);
3399                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
3400
3401                        if ($messages == '')
3402                                continue;
3403
3404                        $i = 0;
3405                        $return[$j] = array();
3406                        $return[$j]['folder_name'] = $folder['name'];
3407
3408                        foreach($messages as $msg_number)
3409                        {
3410                                $header = $this->get_header($msg_number);
3411                                if (!is_object($header))
3412                                        return false;
3413
3414                                $return[$j][$i]['msg_folder']   = $folder['name'];
3415                                $return[$j][$i]['msg_number']   = $msg_number;
3416                                $return[$j][$i]['Recent']               = $header->Recent;
3417                                $return[$j][$i]['Unseen']               = $header->Unseen;
3418                                $return[$j][$i]['Answered']     = $header->Answered;
3419                                $return[$j][$i]['Deleted']              = $header->Deleted;
3420                                $return[$j][$i]['Draft']                = $header->Draft;
3421                                $return[$j][$i]['Flagged']              = $header->Flagged;
3422
3423                                $date_msg = gmdate("d/m/Y",$header->udate);
3424                                if (gmdate("d/m/Y") == $date_msg)
3425                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
3426                                else
3427                                        $return[$j][$i]['udate'] = $date_msg;
3428
3429                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3430                                $return[$j][$i]['fromaddress'] = '';
3431                                foreach ($fromaddress as $tmp)
3432                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
3433
3434                                $from = $header->from;
3435                                $return[$j][$i]['from'] = array();
3436                                $tmp = imap_mime_header_decode($from[0]->personal);
3437                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3438                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
3439                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
3440
3441                                $to = $header->to;
3442                                $return[$j][$i]['to'] = array();
3443                                $tmp = imap_mime_header_decode($to[0]->personal);
3444                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3445                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
3446                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
3447
3448                                $subject = imap_mime_header_decode($header->fetchsubject);
3449                                $return[$j][$i]['subject'] = '';
3450                                foreach ($subject as $tmp)
3451                                        $return[$j][$i]['subject'] .= $tmp->text;
3452
3453                                $return[$j][$i]['Size'] = $header->Size;
3454                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
3455
3456                                $return[$j][$i]['attachment'] = array();
3457                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
3458
3459                                $i++;
3460                        }
3461                        $j++;
3462                        if($mbox_stream)
3463                                imap_close($mbox_stream);
3464                }
3465
3466                return $return;
3467        }
3468
3469
3470        function mobile_search($params)
3471        {
3472                include("class.imap_attachment.inc.php");
3473                $imap_attachment = new imap_attachment();
3474                $criterias = array ("TO","SUBJECT","FROM","CC");
3475                $return = array();
3476                if(!isset($params['folder'])) {
3477                        $folder_params = array("noSharedFolders"=>1);
3478                        if(isset($params['folderType']))
3479                                $folder_params['folderType'] = $params['folderType'];
3480                        $folders = $this->get_folders_list($folder_params);
3481                }
3482                else
3483                        $folders = array(0=>array('folder_id'=>$params['folder']));
3484                $num_msgs = 0;
3485                $max_msgs = $params['max_msgs'] + 1; //get one more because mobile paginate
3486                $return["msgs"] = array();
3487               
3488                //get max_msgs of each folder order by date and later order all messages together and retur only max_msgs msgs
3489                foreach($folders as $id =>$folder)
3490                {
3491                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3492                                foreach($criterias as $criteria_fixed)
3493                                {
3494                                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3495
3496                                        $mbox_stream = $this->open_mbox($folder['folder_id']);
3497
3498                                        $messages = imap_sort($mbox_stream,SORTARRIVAL,1,SE_UID,$_filter);
3499                                       
3500                                        if ($messages == ''){
3501                                                if($mbox_stream)
3502                                                        imap_close($mbox_stream);
3503                                                continue;       
3504                                        }
3505                                       
3506                                        foreach($messages as $msg_number)
3507                                        {
3508                                                $temp = $this->get_info_head_msg($msg_number);
3509                                                if(!$temp)
3510                                                        return false;
3511                                                $temp['msg_folder'] = $folder['folder_id'];
3512                                                $return["msgs"][$num_msgs] = $temp;
3513                                                $num_msgs++;
3514                                        }
3515
3516                                        if($mbox_stream)
3517                                                imap_close($mbox_stream);
3518                                }
3519                        }
3520                }
3521
3522                if(!function_exists("cmp_date")) {
3523                        function cmp_date($obj1, $obj2){
3524                    if($obj1['timestamp'] == $obj2['timestamp']) return 0;
3525                    return ($obj1['timestamp'] < $obj2['timestamp']) ? 1 : -1;
3526                        }
3527                }
3528                usort($return["msgs"], "cmp_date");
3529                $return["has_more_msg"] = (sizeof($return["msgs"]) > $max_msgs);
3530                $return["msgs"] = array_slice($return["msgs"], 0, $max_msgs);
3531                $return["msgs"]['num_msgs'] = $num_msgs;
3532               
3533                return $return;
3534        }
3535
3536        function delete_and_show_previous_message($params)
3537        {
3538                $return = $this->get_info_previous_msg($params);
3539
3540                $params_tmp1 = array();
3541                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3542                $params_tmp1['folder'] = $params['msg_folder'];
3543                $return_tmp1 = $this->delete_msg($params_tmp1);
3544
3545                $return['msg_number_deleted'] = $return_tmp1;
3546
3547                return $return;
3548        }
3549
3550
3551        function automatic_trash_cleanness($params)
3552        {
3553                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3554                $criteria =  'BEFORE "'.$before_date.'"';
3555                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
3556                // Free others requests
3557                session_write_close();
3558                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3559                if (is_array($messages)){
3560                        foreach ($messages as $msg_number){
3561                                imap_delete($mbox_stream, $msg_number, FT_UID);
3562                        }
3563                }
3564                if($mbox_stream)
3565                        imap_close($mbox_stream, CL_EXPUNGE);
3566                return $messages;
3567        }
3568//      Fix the search problem with special characters!!!!
3569        function remove_accents($string) {
3570                return strtr($string,
3571                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
3572                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3573        }
3574       
3575        function make_search_date($date,$before = false){
3576
3577            //TODO: Adaptar a data de acordo com o locale do sistema.
3578            list($day,$month,$year) = explode("/", $date);
3579                        $before?$day=(int)$day+1:$day=(int)$day;
3580                $timestamp = mktime(0,0,0,(int)$month,$day,(int)$year);
3581                $search_date = date('d-M-Y',$timestamp);
3582            return $search_date;
3583
3584    }
3585
3586        function search_msg( $params = false )
3587        {
3588                $mbox_stream = "";
3589               
3590                if(strpos($params['condition'],"#")===false)
3591                { //local messages
3592                        $search=false;
3593                }
3594                else
3595                {
3596                        $search = explode(",",$params['condition']);
3597                }
3598               
3599                $params['page'] = $params['page'] * 1;
3600
3601            if( is_array($search) )
3602            {
3603                        $search = array_unique($search); // Remove duplicated folders
3604                        $search_criteria = '';
3605                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
3606                        foreach($search as $tmp)
3607                        {
3608                                $tmp1 = explode("##",$tmp);
3609                                $sum = 0;
3610                                $name_box = $tmp1[0];
3611                                unset($filter);
3612                                foreach($tmp1 as $index => $criteria)
3613                                {
3614                                        if ($index != 0 && strlen($criteria) != 0)
3615                                        {
3616                                                $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
3617                                                $filter .= " ".$filter_array[0];
3618                                                if (strlen($filter_array[1]) != 0)
3619                                                {
3620                                                        if ( trim($filter_array[0]) != 'BEFORE' &&
3621                                                                 trim($filter_array[0]) != 'SINCE' &&
3622                                                                 trim($filter_array[0]) != 'ON')
3623                                                        {
3624                                                            $filter .= '"'.$filter_array[1].'"';
3625                                                        }
3626                                                        if(trim($filter_array[0]) == 'BEFORE' )
3627                                                        {
3628                                                                $filter .= '"'.$this->make_search_date($filter_array[1],true).'"';
3629                                    }else{
3630                                                                $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3631                                }
3632                                                }
3633                                        }
3634                                }
3635                               
3636                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3637                                $filter = $this->remove_accents($filter);
3638
3639                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
3640                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
3641                                {
3642                                        $folder_name = explode($this->imap_delimiter,$name_box);
3643                                        $this->ldap = new ldap_functions();
3644                                       
3645                                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3646                                        {
3647                                                $folder_name[1] = $cn;
3648                                        }
3649                                        $folder_name = implode($this->imap_delimiter,$folder_name);
3650                                }
3651                                else
3652                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3653                               
3654                                if(!is_resource($mbox_stream))
3655                                        $mbox_stream = $this->open_mbox($name_box);
3656                                else
3657                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
3658                               
3659                                if (preg_match("/^.?\bALL\b/", $filter))
3660                                {
3661                                        // Quick Search, note: this ALL isn't the same ALL from imap_search
3662                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3663                                           
3664                                        foreach($all_criterias as $criteria_fixed)
3665                                        {
3666                                                $_filter = $criteria_fixed . substr($filter,4);
3667                                               
3668                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
3669                                               
3670                                                if(is_array($search_criteria))
3671                                                {
3672                                                        foreach($search_criteria as $new_search)
3673                                                        {
3674                                                                $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3675                                                                $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
3676                                                                $elem['uid'] = $new_search;
3677                                                                /* compare dates in ordering */
3678                                                                $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2); 
3679                                                                $retorno[] = $elem;
3680                                                        }
3681                                                }
3682                                        }
3683                                }
3684                                else{
3685                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3686                                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
3687                                        {
3688                                            if((!strpos($filter,"FLAGGED") === false) || (!strpos($filter,"UNFLAGGED") === false))
3689                                            {
3690                                                $num_msgs = imap_num_msg($mbox_stream);
3691                                                $flagged_msgs = array();
3692                                                for ($i=$num_msgs; $i>0; $i--)
3693                                                {
3694                                                        $iuid = @imap_uid($this->mbox,$i);
3695                                                        $header = $this->get_header($iuid);
3696                                                        if(trim($header->Flagged))
3697                                                        {
3698                                                                $flagged_msgs[$i] = $iuid;
3699                                                        }
3700                                                }
3701                                                if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
3702                                                {
3703                                                    $arry_diff = is_array($search_criteria) ? array_diff($flagged_msgs,$search_criteria):$flagged_msgs;
3704                                                    foreach($arry_diff as $msg)
3705                                                    {
3706                                                        $search_criteria[] = $msg;
3707                                                    }
3708                                                }
3709                                                else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
3710                                                {
3711                                                    $search_criteria = array_diff($search_criteria,$flagged_msgs);
3712                                                }
3713                                            }
3714                                        }
3715
3716                                        if( is_array( $search_criteria) )
3717                                        {
3718                                                foreach($search_criteria as $new_search)
3719                                                {
3720                                                        $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3721                                                        $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
3722                                                        $elem['uid'] = $new_search;
3723                                                        /* compare dates in ordering */
3724                                                        $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
3725                                                        $retorno[] = $elem;
3726                                                }
3727                                        }
3728                                }
3729                        }
3730                }
3731               
3732                if($mbox_stream)
3733                {
3734                        imap_close($mbox_stream);
3735            }
3736           
3737            $num_msgs = count($retorno);
3738
3739            /* Comparison functions, descendent is ascendent with parms inverted */
3740            function SORTDATE($a, $b){ return ($a['udatecomp'] < $b['udatecomp']); }
3741            function SORTDATE_REVERSE($b, $a) { return SORTDATE($a,$b); }
3742
3743            function SORTWHO($a, $b) { return (strtoupper($a['from']) > strtoupper($b['from'])); }
3744            function SORTWHO_REVERSE($b, $a) { return SORTWHO($a,$b); }
3745
3746            function SORTSUBJECT($a, $b) { return (strtoupper($a['subject']) > strtoupper($b['subject'])); }
3747            function SORTSUBJECT_REVERSE($b, $a) { return SORTSUBJECT($a,$b); }
3748
3749            function SORTBOX($a, $b) { return ($a['boxname'] > $b['boxname']); }
3750            function SORTBOX_REVERSE($b, $a) { return SORTBOX($a,$b); }
3751
3752            function SORTSIZE($a, $b) { return ($a['size'] > $b['size']); }
3753            function SORTSIZE_REVERSE($b, $a) { return SORTSIZE($a,$b); }
3754
3755            usort( $retorno, $params['sort_type']);
3756            $pageret = array_slice( $retorno, $params['page'] * $this->prefs['max_email_per_page'], $this->prefs['max_email_per_page']);
3757           
3758            $arrayRetorno['num_msgs']   =  $num_msgs;
3759            $arrayRetorno['data']               =  $pageret;
3760            $arrayRetorno['currentTab'] =  $params['current_tab'];
3761
3762                if ($pageret)
3763                {
3764                        return $arrayRetorno;
3765                }
3766                else
3767                {
3768                        return 'none';
3769                }
3770        }
3771
3772        function get_msg_detail($uid_msg,$name_box, $mbox_stream )
3773        {
3774                $header = $this->get_header($uid_msg);
3775                require_once("class.imap_attachment.inc.php");
3776                $imap_attachment = new imap_attachment();
3777                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3778                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3779                $flag = $header->Unseen
3780                        .$header->Recent
3781                        .$header->Flagged
3782                        .$header->Draft
3783                        .$header->Answered
3784                        .$header->Deleted
3785                        .$attachments;
3786
3787
3788                $subject = $this->decode_string($header->fetchsubject);
3789                $from = $header->from[0]->mailbox;
3790                if($header->from[0]->personal != "")
3791                        $from = $header->from[0]->personal;
3792                $ret_msg['from']        = $this->decode_string($from);
3793                $ret_msg['subject']     = $subject;
3794                $ret_msg['udate']       = gmdate("d/m/Y",$header->udate + $this->functions->CalculateDateOffset());
3795                $ret_msg['size']        = $header->Size;
3796                $ret_msg['flag']        = $flag;
3797                return $ret_msg;
3798        }
3799
3800
3801        function size_msg($size){
3802                $var = floor($size/1024);
3803                if($var >= 1){
3804                        return $var." kb";
3805                }else{
3806                        return $size ." b";
3807                }
3808        }
3809       
3810        function ob_array($the_object)
3811        {
3812           $the_array=array();
3813           if(!is_scalar($the_object))
3814           {
3815               foreach($the_object as $id => $object)
3816               {
3817                   if(is_scalar($object))
3818                   {
3819                       $the_array[$id]=$object;
3820                   }
3821                   else
3822                   {
3823                       $the_array[$id]=$this->ob_array($object);
3824                   }
3825               }
3826               return $the_array;
3827           }
3828           else
3829           {
3830               return $the_object;
3831           }
3832        }
3833
3834        function getacl()
3835        {
3836                $this->ldap = new ldap_functions();
3837
3838                $return = array();
3839                $mbox_stream = $this->open_mbox();
3840                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3841
3842                $i = 0;
3843                foreach ($mbox_acl as $user => $acl)
3844                {
3845                        if ($user != $this->username)
3846                        {
3847                                $return[$i]['uid'] = $user;
3848                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3849                        }
3850                        $i++;
3851                }
3852                return $return;
3853        }
3854
3855        function setacl($params)
3856        {
3857                $old_users = $this->getacl();
3858                if (!count($old_users))
3859                        $old_users = array();
3860
3861                $tmp_array = array();
3862                foreach ($old_users as $index => $user_info)
3863                {
3864                        $tmp_array[$index] = $user_info['uid'];
3865                }
3866                $old_users = $tmp_array;
3867
3868                $users = unserialize($params['users']);
3869                if (!count($users))
3870                        $users = array();
3871
3872                //$add_share = array_diff($users, $old_users);
3873                $remove_share = array_diff($old_users, $users);
3874
3875                $mbox_stream = $this->open_mbox();
3876
3877                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3878                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3879
3880                /*if (count($add_share))
3881                {
3882                        foreach ($add_share as $index=>$uid)
3883                        {
3884                        if (is_array($mailboxes_list))
3885                        {
3886                        foreach ($mailboxes_list as $key => $val)
3887                        {
3888                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3889                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3890                        }
3891                        }
3892                        }
3893                }*/
3894
3895                if (count($remove_share))
3896                {
3897                        foreach ($remove_share as $index=>$uid)
3898                        {
3899                            if (is_array($mailboxes_list))
3900                            {
3901                                foreach ($mailboxes_list as $key => $val)
3902                                {
3903                                    $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3904                                    $folder = str_replace("&-", "&", $folder);
3905                                    imap_setacl ($mbox_stream, $folder, "$uid", "");
3906                                }
3907                            }
3908                        }
3909                }
3910
3911                return true;
3912        }
3913
3914        function getaclfromuser($params)
3915        {
3916                $useracl = $params['user'];
3917
3918                $return = array();
3919                $return[$useracl] = 'false';
3920                $mbox_stream = $this->open_mbox();
3921                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3922
3923                foreach ($mbox_acl as $user => $acl)
3924                {
3925                        if (($user != $this->username) && ($user == $useracl))
3926                        {
3927                                $return[$user] = $acl;
3928                        }
3929                }
3930                return $return;
3931        }
3932
3933        function getacltouser($user)
3934        {
3935                $return = array();
3936                $mbox_stream = $this->open_mbox();
3937                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3938                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3939                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3940                if(substr($user,0,4) != 'user')
3941                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3942                else
3943                  $mbox_acl = imap_getacl($mbox_stream, $user);
3944                return $mbox_acl[$this->username];
3945        }
3946
3947
3948        function setaclfromuser($params)
3949        {
3950                $user = $params['user'];
3951                $acl = $params['acl'];
3952
3953                $mbox_stream = $this->open_mbox();
3954
3955                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3956                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3957
3958                if (is_array($mailboxes_list))
3959                {
3960                        foreach ($mailboxes_list as $key => $val)
3961                        {
3962                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3963                                $folder = str_replace("&-", "&", $folder);
3964                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3965                                {
3966                                        $return = imap_last_error();
3967                                }
3968                        }
3969                }
3970                if (isset($return))
3971                        return $return;
3972                else
3973                        return true;
3974        }
3975
3976        function download_attachment($msg,$msgno)
3977        {
3978                $array_parts_attachments = array();
3979                //$array_parts_attachments['names'] = '';
3980                include_once("class.imap_attachment.inc.php");
3981                $imap_attachment = new imap_attachment();
3982
3983                if (count($msg->fname[$msgno]) > 0)
3984                {
3985                        $i = 0;
3986                        foreach ($msg->fname[$msgno] as $index=>$fname)
3987                        {
3988                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3989                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
3990                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3991                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3992                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3993                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3994                                $i++;
3995                        }
3996                }
3997                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3998                return $array_parts_attachments;
3999        }
4000
4001       
4002        /**
4003        * @license   http://www.gnu.org/copyleft/gpl.html GPL
4004        * @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
4005        * @param     $params
4006        */
4007        function spam($params)
4008        {
4009               
4010                $mbox_stream = $this->open_mbox($params['folder']);
4011                $msgs_number = explode(',',$params['msgs_number']);
4012
4013                $user = Array();
4014
4015                if(substr($params['folder'], 0, 4) == 'user')
4016                {
4017                    $ldapObject = new ldap_functions();
4018
4019                    $folderArray = Array();
4020                    $folderArray = explode($this->imap_delimiter, $params['folder']);
4021
4022                    $user['name'] = $folderArray[1];
4023                    $user['email'] = $ldapObject->getMailByUid($user['name']);
4024               
4025                }
4026                else
4027                {
4028                    $user['name'] = $this->username;
4029                    $user['email'] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
4030                }
4031
4032                foreach($msgs_number as $msg_number)
4033                {
4034                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
4035                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
4036                        $body = imap_body($mbox_stream, $imap_msg_number);
4037                        $msg = $header . $body;
4038                        strtok($user['email'], '@');
4039                        $domain = strtok('@');
4040
4041           
4042
4043                        //Encontrar a assinatura do dspam no cabecalho
4044                        $v = explode("\r\n", $header);
4045                        foreach ($v as $linha){
4046                                if (eregi("^Message-ID", $linha)) {
4047                                        $args = explode(" ", $linha);
4048                                        $msg_id = "'$args[1]'";
4049                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
4050                                        $args = explode(" ",$linha);
4051                                        $signature = $args[1];
4052                                }
4053                        }
4054
4055                        // Seleciona qual comando a ser executado
4056                        switch($params['spam']){
4057                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
4058                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
4059                        }
4060
4061                     
4062                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
4063                        $cmd = str_replace($tags, array($user['email'], $user['name'], $domain, $signature, $msg_id), $cmd);
4064                       
4065                        system($cmd);
4066                }
4067
4068                imap_close($mbox_stream);
4069                return false;
4070        }
4071       
4072       
4073        function get_header($msg_number)
4074        {
4075        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
4076                if (!is_object($header))
4077                        return false;
4078
4079                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
4080                        $flag = preg_match('/importance *: *(.*)\r/i',
4081                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
4082                                                ,$importance);
4083                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
4084                }
4085
4086                return $header;
4087        }
4088
4089//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
4090///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.
4091
4092    function insert_email($source,$folder,$timestamp,$flags){
4093        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
4094        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
4095        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
4096        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
4097        $imap_options = '/notls/novalidate-cert';
4098        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
4099        if(imap_last_error())
4100        {
4101            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
4102        }
4103        if($timestamp){
4104                        $pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local)
4105                        $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.
4106                        /* TODO: o diretorio /tmp deve ser substituido pelo diretorio temporario configurado no setup */
4107                        $file = "/tmp/sess_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
4108               
4109                $f = fopen($file,"w");
4110                fputs($f,base64_encode($source));
4111            fclose($f);           
4112                   $command = "python ".$_SESSION['rootPatch']."/expressoMail1_2/imap.py ".escapeshellarg($imap_server)." ".escapeshellarg($imap_port)." ".escapeshellarg($username)." ".escapeshellarg($password)." ".escapeshellarg($timestamp)." ".escapeshellarg($folder)." ".escapeshellarg($file);
4113            $return['command']=exec(escapeshellcmd($command));
4114        }else{
4115            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
4116        }
4117        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
4118                       
4119        $return['msg_no'] = $status->uidnext - 1;
4120        $return['error'] = imap_last_error();
4121        if(!$return['error'] && $flags != '' ){
4122
4123                  $flags_array=explode(':',$flags);
4124                  //"Answered","Draft","Flagged","Unseen"
4125                  $flags_fixed = "";
4126                  if($flags_array[0] == 'A')
4127                        $flags_fixed.="\\Answered ";
4128                  if($flags_array[1] == 'X')
4129                        $flags_fixed.="\\Draft ";
4130                  if($flags_array[2] == 'F')
4131                        $flags_fixed.="\\Flagged ";
4132                  if($flags_array[3] != 'U')
4133                        $flags_fixed.="\\Seen ";
4134
4135                  imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
4136                }
4137        if($mbox_stream)
4138            imap_close($mbox_stream);
4139        return $return;
4140    }
4141
4142    function show_decript($params){
4143        $source = $params['source'];
4144        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
4145        $source = str_replace(" ", "+", $source,$i);
4146
4147        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
4148            if(!$source = base64_decode($source,true))
4149                return "error ".$source."Espaços ".$i;
4150
4151        }
4152        else {
4153            if(!$source = base64_decode($source))
4154                return "error ".$source."Espaços ".$i;
4155        }
4156
4157        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
4158
4159                $get['msg_number'] = $insert['msg_no'];
4160                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
4161                $return = $this->get_info_msg($get);
4162                $get['msg_number'] = $params['ID'];
4163                $get['msg_folder'] = $params['folder'];
4164                $tmp = $this->get_info_msg($get);
4165                if(!$tmp['status_get_msg_info'])
4166                {
4167                        $return['msg_day']=$tmp['msg_day'];
4168                        $return['msg_hour']=$tmp['msg_hour'];
4169                        $return['fulldate']=$tmp['fulldate'];
4170                        $return['smalldate']=$tmp['smalldate'];
4171                }
4172                else
4173                {
4174                        $return['msg_day']='';
4175                        $return['msg_hour']='';
4176                        $return['fulldate']='';
4177                        $return['smalldate']='';
4178                }
4179        $return['msg_no'] =$insert['msg_no'];
4180        $return['error'] = $insert['error'];
4181        $return['folder'] = $params['folder'];
4182        //$return['acls'] = $insert['acls'];
4183        $return['original_ID'] =  $params['ID'];
4184
4185        return $return;
4186
4187    }
4188
4189//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
4190//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
4191
4192    function treat_base64_from_post($source){
4193            $offset = 0;
4194            do
4195            {
4196                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
4197                    {
4198                            $inicio = strpos($source, "\n\r", $inicio);
4199                            $fim = strpos($source, '--', $inicio);
4200                            if(!$fim)
4201                                    $fim = strpos($source,"\n\r", $inicio);
4202                            $length = $fim-$inicio;
4203                            $parte = substr( $source,$inicio,$length-1);
4204                            $parte = str_replace(" ", "+", $parte);
4205                            $source = substr_replace($source, $parte, $inicio, $length-1);
4206                    }
4207                    if($offset > $inicio)
4208                    $offset=FALSE;
4209                    else
4210                    $offset = $inicio;
4211            }
4212            while($offset);
4213            return $source;
4214    }
4215
4216//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.
4217
4218    function unarchive_mail($params)
4219    {
4220        $dest_folder = $params['folder'];
4221        $sources = explode("#@#@#@",$params['source']);
4222        $timestamps = explode("#@#@#@",$params['timestamp']);
4223        $flags = explode("#@#@#@",$params['flags']);
4224
4225        foreach($sources as $index=>$src)
4226        {
4227            if($src!="")
4228            {
4229                $source = $this->treat_base64_from_post($src);
4230                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]);
4231            }
4232        }
4233       
4234        return $insert;
4235    }
4236
4237    function download_all_local_attachments($params)
4238    {
4239        $source = $params['source'];
4240        $source = $this->treat_base64_from_post($source);
4241        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
4242        $exporteml = new ExportEml();
4243        $params['num_msg']=$insert['msg_no'];
4244        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
4245        return $exporteml->download_all_attachments($params);
4246    }
4247    function get_quota_folders(){
4248
4249            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
4250            include_once("class.imapfp.inc.php");           
4251            $imapfp = new imapfp();
4252
4253            if(!$imapfp->open($this->imap_server,$this->imap_port))
4254                    return $imapfp->get_error();             
4255            if (!$imapfp->login( $this->username,$this->password ))
4256                    return $imapfp->get_error();
4257
4258            $response_array = $imapfp->get_mailboxes_size();
4259            if ($imapfp->error)
4260                    return $imapfp->get_error();
4261
4262            $data = array();
4263            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
4264            $data["quota_root"] = $quota_root;
4265
4266            foreach ($response_array as $idx=>$line) {
4267                    $line2 = str_replace('"', "", $line);
4268                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
4269                    list($folder,$size) = explode(";",$line2);
4270                    $quota_used = str_replace(")","",$size);
4271                    $quotaPercent = (($quota_used / 1024) / $data["quota_root"]["quota_limit"])*100;
4272                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
4273                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
4274                            $folder = $this->functions->getLang("Inbox");
4275                    }
4276                    else
4277                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
4278
4279                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
4280            }
4281            $imapfp->close();
4282            return $data;
4283    } 
4284}
4285?>
Note: See TracBrowser for help on using the repository browser.