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

Revision 3394, 140.9 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #1265 - Tratamento de mensagens encapsuladas do Outlook.

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