source: trunk/expressoMail1_2/inc/class.imap_functions.inc.php @ 2037

Revision 2037, 137.1 KB checked in by amuller, 14 years ago (diff)

Ticket #859 - Resolvendo problema de links...................

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