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

Revision 4429, 152.1 KB checked in by wmerlotto, 13 years ago (diff)

Ticket #1887 - Aplicando pequenas correções de tabulação.

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