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

Revision 3872, 144.1 KB checked in by thiagoaos, 13 years ago (diff)

Ticket #1629 - Corrigido o desarquivamento de mensagens mantendo a flag de importante.

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