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

Revision 3493, 142.5 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1322 - Data incorreta nas mensagens na caixa de entrada.

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