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

Revision 3912, 144.7 KB checked in by brunocosta, 13 years ago (diff)

Ticket #1696 - retira os caracteres "\0" do corpo de mensagens text/plain.

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