source: branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 3922

Revision 3922, 145.6 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1695 - E-mail com corpo em multpart tem visualização repetida.

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