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

Revision 4416, 152.1 KB checked in by airton, 13 years ago (diff)

Ticket #1887 - Redefinicao do parser de email - Todas as adequacoes feitas no parser.

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