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

Revision 4468, 154.7 KB checked in by airton, 13 years ago (diff)

Ticket #1820 - Aumenta a data passada para pesquisa em 1 dia - r4430

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