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

Revision 5085, 153.8 KB checked in by fernando-alberto, 13 years ago (diff)

Ticket #1269 - Desenvolvimento da nova solucao de arquivamento local MailArchiver?, tags para arquivamento

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