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

Revision 3414, 142.2 KB checked in by brunocosta, 14 years ago (diff)

Ticket #1276 - Limite de tamanho para exibição de partes text/plain ou text/html no Expresso mail

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