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

Revision 3385, 137.4 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #1256 - Correcao do erro narrado no ticket em questão

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