source: sandbox/expressoMail1_2/MailArchiver/2.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 4955

Revision 4955, 152.0 KB checked in by cassiano.dalpizzol, 13 years ago (diff)

Ticket #1269 - Implementação do desarquivamento no mailarchiver

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