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

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

Ticket #1254 - 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)>0) //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                                if($attach['name']=='Unknown')
2036                                        continue;
2037                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2038                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2039                        }
2040                        if( $total_uploaded_size > $upload_max_filesize){
2041                                return $this->parse_error("message file too big");
2042                        }
2043                }
2044                if(count($local_attachments)>0) { //Caso seja forward de mensagens locais
2045
2046                        $total_uploaded_size = 0;
2047                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
2048                        foreach($local_attachments as $local_attachment) {
2049                                $file_description = unserialize(rawurldecode($local_attachment));
2050                                $tmp = array_values($file_description);
2051                                foreach($file_description as $i => $descriptor){
2052                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2053                                }
2054                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2055                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2056                        }
2057                        if( $total_uploaded_size > $upload_max_filesize)
2058                                return 'false';
2059                }
2060////////////////////////////////////////////////////////////////////////////////////////////////////
2061                //      Build Forwarding Attachments!!!
2062                if (count($forwarding_attachments) > 0)
2063                {
2064                        // Bug fixed for array_search function
2065                        $name_cid_files = array();
2066                        if(count($name_cid_files) > 0) {
2067                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2068                                $name_cid_files[0] = null;
2069                        }
2070
2071                        foreach($forwarding_attachments as $forwarding_attachment)
2072                        {
2073                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2074                                        $tmp = array_values($file_description);
2075                                        foreach($file_description as $i => $descriptor){
2076                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2077                                        }
2078                                        $file_description = $tmp;
2079                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2080                                        $fileName = $file_description[2];
2081                                        if(!array_search(trim($fileName),$name_cid_files)) {
2082                                                $mail->AddStringAttachment($fileContent,html_entity_decode(rawurldecode($fileName)), $file_description[4], $this->get_file_type($file_description[2]));
2083                                }
2084                        }
2085                }
2086
2087////////////////////////////////////////////////////////////////////////////////////////////////////
2088                // Important message
2089                if($is_important)
2090                        $mail->isImportant();
2091
2092////////////////////////////////////////////////////////////////////////////////////////////////////
2093                // Disposition-Notification-To
2094                if ($return_receipt)
2095                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2096////////////////////////////////////////////////////////////////////////////////////////////////////
2097
2098                $sent = $mail->Send();
2099
2100                if(!$sent)
2101                {
2102                        return $this->parse_error($mail->ErrorInfo);
2103                }
2104                else
2105                {
2106            if ($signed && !$params['smime'])
2107                        {
2108                                return $sent;
2109                        }
2110                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
2111                        {
2112                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2113                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
2114                                $now = date("d/m/y H:i:s");
2115                                $addrs = $toaddress.$ccaddress.$ccoaddress;
2116                                $sent = trim($sent);
2117                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2118                        }
2119                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
2120                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
2121                                $contacts = new dynamic_contacts();
2122                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2123                                return array("success" => true, "new_contacts" => $new_contacts);
2124                        }
2125                        return array("success" => true);
2126                }
2127        }
2128        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments)
2129        {
2130                //      Build CID for embedded Images!!!
2131                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2132                $cid_imgs = '';
2133                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2134                $cid_array = array();
2135                foreach($cid_imgs[6] as $j => $val){
2136                        if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2137                        {
2138                                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2139                        }
2140                        $cid = $cid_array[$cid_imgs[4][$j].$val]; 
2141                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2142
2143                        if ($msg_uid != $cid_imgs[4][$j]) // The image is not in the same mail?
2144                        {
2145                                $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2146                                //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
2147                                $fileName = "image_".($j).".jpg";
2148                                $fileCode = "base64";
2149                                $fileType = "image/jpg";
2150                                $file_attached[0] = $cid_imgs[2][$j];
2151                                $file_attached[1] = $cid_imgs[4][$j];
2152                                $file_attached[2] = $fileName;
2153                                $file_attached[3] = $cid_imgs[6][$j];
2154                                $file_attached[4] = 'base64';
2155                                $file_attached[5] = strlen($fileContent); //Size of file
2156                                $return_forward[] = $file_attached;
2157
2158                                $attachment_ = unserialize(rawurldecode($forwarding_attachments[$cid_imgs[6][$j]-2]));
2159                                if ($file_attached[3] == $attachment_[3])
2160                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);     
2161                        }
2162                        else
2163                        {
2164                                $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2165                                $file_description = unserialize(rawurldecode($attach_img));
2166                                if (is_array($file_description))
2167                                        foreach($file_description as $i => $descriptor){                                 
2168                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2169                                        }
2170                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2171                                $fileName = $file_description[2];
2172                                $fileCode = $file_description[4];
2173                                $fileType = $this->get_file_type($file_description[2]);
2174                                unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2175                                if (!empty($file_description))
2176                                {
2177                                        $file_description[5] = strlen($fileContent); //Size of file
2178                                        $return_forward[] = $file_description;
2179                                }
2180                        }
2181                        $tempDir = ini_get("session.save_path");
2182                        $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                       
2183                        $f = fopen($tempDir.'/'.$file,"w");
2184                        fputs($f,$fileContent);
2185                        fclose($f);
2186                        if ($fileContent)
2187                                $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2188                        //else
2189                        //      return "Error loading image attachment content";                                                 
2190
2191                }
2192                return $return_forward;
2193        }
2194        function add_recipients_cert($full_address)
2195        {
2196                $result = "";
2197                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2198                foreach ($parse_address as $val)
2199                {
2200                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2201                        if ($val->mailbox == "INVALID_ADDRESS")
2202                                continue;
2203                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2204                                continue;
2205                        if (empty($val->personal))
2206                                $result .= $val->mailbox."@".$val->host . ",";
2207                        else
2208                                $result .= $val->mailbox."@".$val->host . ",";
2209                }
2210
2211                return substr($result,0,-1);
2212        }
2213
2214        function add_recipients($recipient_type, $full_address, $mail)
2215        {
2216                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2217                foreach ($parse_address as $val)
2218                {
2219                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2220                        if ($val->mailbox == "INVALID_ADDRESS")
2221                                continue;
2222
2223                        if (empty($val->personal))
2224                        {
2225                                switch($recipient_type)
2226                                {
2227                                        case "to":
2228                                                $mail->AddAddress($val->mailbox."@".$val->host);
2229                                                break;
2230                                        case "cc":
2231                                                $mail->AddCC($val->mailbox."@".$val->host);
2232                                                break;
2233                                        case "cco":
2234                                                $mail->AddBCC($val->mailbox."@".$val->host);
2235                                                break;
2236                                }
2237                        }
2238                        else
2239                        {
2240                                switch($recipient_type)
2241                                {
2242                                        case "to":
2243                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2244                                                break;
2245                                        case "cc":
2246                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2247                                                break;
2248                                        case "cco":
2249                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2250                                                break;
2251                                }
2252                        }
2253                }
2254                return true;
2255        }
2256
2257        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2258        {
2259                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
2260                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
2261                if($encoding == 'base64')
2262                        # The function imap_base64 adds a new line
2263                        # at ASCII text, with CRLF line terminators.
2264                        # So is being exchanged for base64_decode.
2265                        #
2266                        #$fileContent = imap_base64($fileContent);
2267                        $fileContent = base64_decode($fileContent);
2268                else if($encoding == 'quoted-printable')
2269                        $fileContent = quoted_printable_decode($fileContent);
2270                return $fileContent;
2271        }
2272
2273        function del_last_caracter($string)
2274        {
2275                $string = substr($string,0,(strlen($string) - 1));
2276                return $string;
2277        }
2278
2279        function del_last_two_caracters($string)
2280        {
2281                $string = substr($string,0,(strlen($string) - 2));
2282                return $string;
2283        }
2284
2285        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
2286        {
2287                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
2288                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2289                        foreach($imapsort as $iuid)
2290                                $sort[$iuid] = "";
2291                       
2292                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2293                                $slice_array = false;
2294                        else
2295                                $slice_array = true;
2296                }
2297                else
2298                {
2299                        $sort = array();
2300                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2301                        $num_msgs = imap_num_msg($this->mbox);
2302                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
2303                        $slice_array = true;
2304
2305                        for ($i=$num_msgs; $i>0; $i--)
2306                        {
2307                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2308                                        break;
2309                                $iuid = @imap_uid($this->mbox,$i);
2310                                $header = $this->get_header($iuid);
2311                                // List UNSEEN messages.
2312                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2313                                        continue;
2314                                }
2315                                // List SEEN messages.
2316                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2317                                        continue;
2318                                }
2319                                // List ANSWERED messages.
2320                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2321                                        continue;
2322                                }
2323                                // List FLAGGED messages.
2324                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2325                                        continue;
2326                                }
2327
2328                                if($sort_box_type=='SORTFROM') {
2329                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
2330                                                $from = $header->to;
2331                                        else
2332                                                $from = $header->from;
2333
2334                                        $tmp = imap_mime_header_decode($from[0]->personal);
2335
2336                                        if ($tmp[0]->text != "")
2337                                                $sort[$iuid] = $tmp[0]->text;
2338                                        else
2339                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2340                                }
2341                                else if($sort_box_type=='SORTSUBJECT') {
2342                                        $sort[$iuid] = $header->subject;
2343                                }
2344                                else if($sort_box_type=='SORTSIZE') {
2345                                        $sort[$iuid] = $header->Size;
2346                                }
2347                                else {
2348                                        $sort[$iuid] = $header->udate;
2349                                }
2350
2351                        }
2352                        natcasesort($sort);
2353
2354                        if ($sort_box_reverse)
2355                                $sort = array_reverse($sort,true);
2356                }
2357
2358                if(!is_array($sort))
2359                        $sort = array();
2360
2361
2362                if ($slice_array)
2363                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
2364
2365
2366                return $sort;
2367
2368        }
2369
2370
2371        function move_search_messages($params){
2372                $params['selected_messages'] = urldecode($params['selected_messages']);
2373                $params['new_folder'] = urldecode($params['new_folder']);
2374                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2375                $sel_msgs = explode(",", $params['selected_messages']);
2376                @reset($sel_msgs);
2377                $sorted_msgs = array();
2378                foreach($sel_msgs as $idx => $sel_msg) {
2379                        $sel_msg = explode(";", $sel_msg);
2380                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2381                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
2382                         }
2383                         else {
2384                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2385                         }
2386                }
2387                @ksort($sorted_msgs);
2388                $last_return = false;
2389                foreach($sorted_msgs as $folder => $msgs_number) {
2390                        $params['msgs_number'] = $msgs_number;
2391                        $params['folder'] = $folder;
2392                        if($params['new_folder'] && $folder != $params['new_folder']){
2393                                $last_return = $this -> move_messages($params);
2394                        }
2395                        elseif(!$params['new_folder'] || $params['delete'] ){
2396                                $last_return = $this -> delete_msgs($params);
2397                                $last_return['deleted'] = true;
2398                        }
2399                }
2400                return $last_return;
2401        }
2402
2403        function move_messages($params)
2404        {
2405                $folder = $params['folder'];
2406                $mbox_stream = $this->open_mbox($folder);
2407                $newmailbox = ($params['new_folder']);
2408                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
2409                $new_folder_name = $params['new_folder_name'];
2410                $msgs_number = $params['msgs_number'];
2411                $return = array('msgs_number' => $msgs_number,
2412                                                'folder' => $folder,
2413                                                'new_folder_name' => $new_folder_name,
2414                                                'border_ID' => $params['border_ID'],
2415                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
2416
2417                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2418        if (substr($folder,0,4) == 'user'){
2419                $acl = $this->getacltouser($folder);
2420                /*
2421                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2422                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2423                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2424                 *   w - write (STORE flags other than SEEN and DELETED)
2425                 *   i - insert (perform APPEND, COPY into mailbox)
2426                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2427                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2428                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2429                 *   a - administer (perform SETACL)
2430                        */
2431                        if (strpos($acl, "d") === false){
2432                                $return['status'] = false;
2433                                return $return;
2434                        }
2435        }
2436        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
2437        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
2438            if (substr($new_folder_name,0,4) == 'user'){
2439                $this->ldap = new ldap_functions();
2440                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
2441                $return['new_folder_name'] = array_pop($tmp_folder_name);
2442                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2443                {
2444                    $return['new_folder_name'] = $cn;
2445                }
2446            }
2447        }
2448
2449                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
2450                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
2451                {
2452                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2453                        // Fix problem in unserialize function JS.
2454                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2455                }
2456
2457                $mbox_stream = $this->open_mbox($folder);
2458                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2459                        imap_expunge($mbox_stream);
2460                        if($mbox_stream)
2461                                imap_close($mbox_stream);
2462                        return $return;
2463                }else {
2464                        if(strstr(imap_last_error(),'Over quota')) {
2465                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
2466                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
2467                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2468                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2469                                $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()))));
2470                                if(!$mbox)
2471                                        return imap_last_error();
2472                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
2473                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
2474                                        if($mbox_stream)
2475                                                imap_close($mbox_stream);
2476                                        if($mbox)
2477                                                imap_close($mbox);
2478                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
2479                                }
2480                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2481                                        imap_expunge($mbox_stream);
2482                                        if($mbox_stream)
2483                                                imap_close($mbox_stream);
2484                                        // return to original quota limit.
2485                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2486                                                if($mbox)
2487                                                        imap_close($mbox);
2488                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2489                                        }
2490                                        return $return;
2491                                }
2492                                else {
2493                                        if($mbox_stream)
2494                                                imap_close($mbox_stream);
2495                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2496                                                if($mbox)
2497                                                        imap_close($mbox);
2498                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2499                                        }
2500                                        return imap_last_error();
2501                                }
2502
2503                        }
2504                        else {
2505                                if($mbox_stream)
2506                                        imap_close($mbox_stream);
2507                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
2508                        }
2509                }
2510        }
2511
2512        function save_msg($params)
2513        {
2514
2515                include_once("class.phpmailer.php");
2516                $mail = new PHPMailer();
2517                include_once("class.db_functions.inc.php");
2518                $toaddress = $params['input_to'];
2519                $ccaddress = $params['input_cc'];
2520                $ccoaddress = $params['input_cco'];
2521                $subject = $params['input_subject'];
2522                $msg_uid = $params['msg_id'];
2523                $body = $params['body'];
2524                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
2525                $body = preg_replace("/\n/"," ",$body);
2526                $body = preg_replace("/\r/","",$body);
2527                $forwarding_attachments = $params['forwarding_attachments'];
2528                $attachments = $params['FILES'];
2529                $return_files = $params['FILES'];
2530
2531                $folder = $params['folder'];
2532                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2533                // Fix problem with cyrus delimiter changes.
2534                // Dots in names: enabled/disabled.
2535                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2536                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2537                // End Fix.
2538                if(strtoupper($folder) == 'INBOX/DRAFTS')
2539                    {
2540                        $mail->SaveMessageAsDraft = $folder;
2541                    }
2542                $mail->SaveMessageInFolder = $folder;
2543                $mail->SMTPDebug = false;
2544
2545                $mail->IsSMTP();
2546                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2547                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2548                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2549                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2550
2551                $mail->Sender = $mail->From;
2552                $mail->SenderName = $mail->FromName;
2553                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2554                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
2555
2556                $this->add_recipients("to", $toaddress, &$mail);
2557                $this->add_recipients("cc", $ccaddress, &$mail);
2558                $this->add_recipients("cco", $ccoaddress, &$mail);
2559                $mail->Subject = $subject;
2560                $mail->IsHTML(true);
2561                $mail->Body = $body;
2562
2563                $return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2564
2565        //      Build Forwarding Attachments!!!
2566                if (count($forwarding_attachments) > 0)
2567                {
2568                        foreach($forwarding_attachments as $forwarding_attachment)
2569                        {
2570                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2571                                $tmp = array_values($file_description);
2572                                foreach($file_description as $i => $descriptor){
2573                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2574                                }
2575                                $file_description = $tmp;
2576
2577                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2578                                $fileName = $file_description[2];
2579
2580                                $file_description[5] = strlen($fileContent); //Size of file
2581                                $return_forward[] = $file_description;
2582
2583                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2584                        }
2585                }
2586
2587                if ((count($return_forward) > 0) && (count($return_files) > 0))
2588                        $return_files = array_merge_recursive($return_forward,$return_files);
2589                else
2590                        if (count($return_files) < 1)
2591                                $return_files = $return_forward;
2592
2593                //      Build Uploading Attachments!!!
2594                $sizeof_attachments = count($attachments);
2595                if ($sizeof_attachments)
2596                        foreach ($attachments as $numb => $attach){
2597                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2598                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2599                                        switch ($image_type)
2600                                        {
2601                                        // Do not corrupt animated gif
2602                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
2603                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2604                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2605                                        case 6:
2606                                                require_once("gd_functions.php");
2607                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2608                                        default:
2609                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2610                                                break;
2611                                        }
2612                                        header('Content-type: image/jpeg');
2613                                        $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
2614                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2615                                        if ($width < $max_resolution && $height < $max_resolution){
2616                                                $new_width = $width;
2617                                                $new_height = $height;
2618                                        }
2619                                        else if ($width > $max_resolution){
2620                                                $new_width = $max_resolution;
2621                                                $new_height = $height*($new_width/$width);
2622                                        }
2623                                        else {
2624                                                $new_height = $max_resolution;
2625                                                $new_width = $width*($new_height/$height);
2626                                        }
2627                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2628                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2629                                        $tmpDir = ini_get("session.save_path");
2630                                        $_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
2631                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2632                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2633                                }
2634                                else
2635                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2636                                // optional name
2637                                }
2638
2639
2640
2641
2642                if(!empty($mail->AltBody))
2643            $mail->ContentType = "multipart/alternative";
2644
2645                $mail->error_count = 0; // reset errors
2646                $mail->SetMessageType();
2647                $header = $mail->CreateHeader();
2648                $body = $mail->CreateBody();
2649
2650                $mbox_stream = $this->open_mbox($folder);
2651                $new_header = str_replace("\n", "\r\n", $header);
2652                $new_body = str_replace("\n", "\r\n", $body);
2653                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2654                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2655                $return['msg_no'] = $status->uidnext - 1;
2656                $return['folder_id'] = $folder;
2657
2658                if($mbox_stream)
2659                        imap_close($mbox_stream);
2660                if (is_array($return_files))
2661                        foreach ($return_files as $index => $_attachment) {
2662                                if (array_key_exists("name",$_attachment)){
2663                                unset($return_files[$index]);
2664                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2665                        }
2666                        else
2667                        {
2668                                unset($return_files[$index]);
2669                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2670                        }
2671                }
2672
2673                $return['files'] = serialize($return_files);
2674                $return["subject"] = $subject;
2675
2676                if (!$return['append'])
2677                        $return['append'] = imap_last_error();
2678
2679                return $return;
2680        }
2681
2682        function set_messages_flag($params)
2683        {
2684                $folder = $params['folder'];
2685                $msgs_to_set = $params['msgs_to_set'];
2686                $flag = $params['flag'];
2687                $return = array();
2688                $return["msgs_to_set"] = $msgs_to_set;
2689                $return["flag"] = $flag;
2690
2691                if(!$this->mbox && !is_resource($this->mbox))
2692                        $this->mbox = $this->open_mbox($folder);
2693
2694                if ($flag == "unseen")
2695                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2696                elseif ($flag == "seen")
2697                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2698                elseif ($flag == "answered"){
2699                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2700                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2701                }
2702                elseif ($flag == "forwarded")
2703                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2704                elseif ($flag == "flagged")
2705                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2706                elseif ($flag == "unflagged") {
2707                        $flag_importance = false;
2708                        $msgs_number = explode(",",$msgs_to_set);
2709                        $unflagged_msgs = "";
2710                        foreach($msgs_number as $msg_number) {
2711                                preg_match('/importance *: *(.*)\r/i',
2712                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2713                                        ,$importance);
2714                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2715                                        $flag_importance=true;
2716                                }
2717                                else {
2718                                        $unflagged_msgs.=$msg_number.",";
2719                                }
2720                        }
2721
2722                        if($unflagged_msgs!="") {
2723                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2724                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2725                        }
2726                        else {
2727                                $return["msgs_unflageds"] = false;
2728                        }
2729
2730                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2731                                $return["status"] = false;
2732                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2733                        }
2734                        else {
2735                                $return["status"] = true;
2736                        }
2737                }
2738
2739                if($this->mbox && is_resource($this->mbox))
2740                        imap_close($this->mbox);
2741                return $return;
2742        }
2743
2744        function get_file_type($file_name)
2745        {
2746                $file_name = strtolower($file_name);
2747                $strFileType = strrev(substr(strrev($file_name),0,4));
2748                if ($strFileType == ".asf")
2749                        return "video/x-ms-asf";
2750                if ($strFileType == ".avi")
2751                        return "video/avi";
2752                if ($strFileType == ".doc")
2753                        return "application/msword";
2754                if ($strFileType == ".zip")
2755                        return "application/zip";
2756                if ($strFileType == ".xls")
2757                        return "application/vnd.ms-excel";
2758                if ($strFileType == ".gif")
2759                        return "image/gif";
2760                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2761                        return "image/jpeg";
2762                if ($strFileType == ".png")
2763                        return "image/png";
2764                if ($strFileType == ".wav")
2765                        return "audio/wav";
2766                if ($strFileType == ".mp3")
2767                        return "audio/mpeg3";
2768                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2769                        return "video/mpeg";
2770                if ($strFileType == ".rtf")
2771                        return "application/rtf";
2772                if ($strFileType == ".htm" || $strFileType == "html")
2773                        return "text/html";
2774                if ($strFileType == ".xml")
2775                        return "text/xml";
2776                if ($strFileType == ".xsl")
2777                        return "text/xsl";
2778                if ($strFileType == ".css")
2779                        return "text/css";
2780                if ($strFileType == ".php")
2781                        return "text/php";
2782                if ($strFileType == ".asp")
2783                        return "text/asp";
2784                if ($strFileType == ".pdf")
2785                        return "application/pdf";
2786                if ($strFileType == ".txt")
2787                        return "text/plain";
2788                if ($strFileType == ".wmv")
2789                        return "video/x-ms-wmv";
2790                if ($strFileType == ".sxc")
2791                        return "application/vnd.sun.xml.calc";
2792                if ($strFileType == ".stc")
2793                        return "application/vnd.sun.xml.calc.template";
2794                if ($strFileType == ".sxd")
2795                        return "application/vnd.sun.xml.draw";
2796                if ($strFileType == ".std")
2797                        return "application/vnd.sun.xml.draw.template";
2798                if ($strFileType == ".sxi")
2799                        return "application/vnd.sun.xml.impress";
2800                if ($strFileType == ".sti")
2801                        return "application/vnd.sun.xml.impress.template";
2802                if ($strFileType == ".sxm")
2803                        return "application/vnd.sun.xml.math";
2804                if ($strFileType == ".sxw")
2805                        return "application/vnd.sun.xml.writer";
2806                if ($strFileType == ".sxq")
2807                        return "application/vnd.sun.xml.writer.global";
2808                if ($strFileType == ".stw")
2809                        return "application/vnd.sun.xml.writer.template";
2810
2811
2812                return "application/octet-stream";
2813        }
2814
2815        function htmlspecialchars_encode($str)
2816        {
2817                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
2818        }
2819        function htmlspecialchars_decode($str)
2820        {
2821                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
2822        }
2823
2824        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2825        {
2826                if(!$this->mbox || !is_resource($this->mbox))
2827                        $this->mbox = $this->open_mbox($folder);
2828
2829                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2830        }
2831
2832        function get_info_next_msg($params)
2833        {
2834                $msg_number = $params['msg_number'];
2835                $folder = $params['msg_folder'];
2836                $sort_box_type = $params['sort_box_type'];
2837                $sort_box_reverse = $params['sort_box_reverse'];
2838                $reuse_border = $params['reuse_border'];
2839                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2840                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2841
2842                $success = false;
2843                if (is_array($sort_array_msg))
2844                {
2845                        foreach ($sort_array_msg as $i => $value){
2846                                if ($value == $msg_number)
2847                                {
2848                                        $success = true;
2849                                        break;
2850                                }
2851                        }
2852                }
2853
2854                if (! $success || $i >= sizeof($sort_array_msg)-1)
2855                {
2856                        $params['status'] = 'false';
2857                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2858                        return $params;
2859                }
2860
2861                $params = array();
2862                $params['msg_number'] = $sort_array_msg[($i+1)];
2863                $params['msg_folder'] = $folder;
2864
2865                $return = $this->get_info_msg($params);
2866                $return["reuse_border"] = $reuse_border;
2867                return $return;
2868        }
2869
2870        function get_info_previous_msg($params)
2871        {
2872                $msg_number = $params['msgs_number'];
2873                $folder = $params['folder'];
2874                $sort_box_type = $params['sort_box_type'];
2875                $sort_box_reverse = $params['sort_box_reverse'];
2876                $reuse_border = $params['reuse_border'];
2877                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2878                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2879
2880                $success = false;
2881                if (is_array($sort_array_msg))
2882                {
2883                        foreach ($sort_array_msg as $i => $value){
2884                                if ($value == $msg_number)
2885                                {
2886                                        $success = true;
2887                                        break;
2888                                }
2889                        }
2890                }
2891                if (! $success || $i == 0)
2892                {
2893                        $params['status'] = 'false';
2894                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2895                        return $params;
2896                }
2897
2898                $params = array();
2899                $params['msg_number'] = $sort_array_msg[($i-1)];
2900                $params['msg_folder'] = $folder;
2901
2902                $return = $this->get_info_msg($params);
2903                $return["reuse_border"] = $reuse_border;
2904                return $return;
2905        }
2906
2907        // This function updates the values: quota, paging and new messages menu.
2908        function get_menu_values($params){
2909                $return_array = array();
2910                $return_array = $this->get_quota($params);
2911
2912                $mbox_stream = $this->open_mbox($params['folder']);
2913                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
2914                if($mbox_stream)
2915                        imap_close($mbox_stream);
2916
2917                return $return_array;
2918        }
2919
2920        function get_quota($params){
2921                // folder_id = user/{uid} for shared folders
2922                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
2923                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
2924                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
2925                }
2926                // folder_id = INBOX for inbox folders
2927                else
2928                        $folder_id = "INBOX";
2929
2930                if(!$this->mbox || !is_resource($this->mbox))
2931                        $this->mbox = $this->open_mbox();
2932
2933                $quota = imap_get_quotaroot($this->mbox, $folder_id);
2934                if($this->mbox && is_resource($this->mbox))
2935                        imap_close($this->mbox);
2936
2937                if (!$quota){
2938                        return array(
2939                                'quota_percent' => 0,
2940                                'quota_used' => 0,
2941                                'quota_limit' =>  0
2942                        );
2943                }
2944
2945                if(count($quota) && $quota['limit']) {
2946                        $quota_limit = $quota['limit'];
2947                        $quota_used  = $quota['usage'];
2948                        if($quota_used >= $quota_limit)
2949                        {
2950                                $quotaPercent = 100;
2951                        }
2952                        else
2953                        {
2954                        $quotaPercent = ($quota_used / $quota_limit)*100;
2955                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
2956                        }
2957                        return array(
2958                                'quota_percent' => floor($quotaPercent),
2959                                'quota_used' => $quota_used,
2960                                'quota_limit' =>  $quota_limit
2961                        );
2962                }
2963                else
2964                        return array();
2965        }
2966
2967        function send_notification($params){
2968                include("../header.inc.php");
2969                require_once("class.phpmailer.php");
2970                $mail = new PHPMailer();
2971
2972                $toaddress = $params['notificationto'];
2973
2974                $subject = lang("Read receipt: %1",$params['subject']);
2975                $body = lang("Your message: %1",$params['subject']) . '<br>';
2976                $body .= lang("Received in: %1",$params['date']) . '<br>';
2977                $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"));
2978                $mail->SMTPDebug = false;
2979                $mail->IsSMTP();
2980                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2981                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2982                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2983                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2984                $mail->AddAddress($toaddress);
2985                $mail->Subject = $this->htmlspecialchars_decode($subject);
2986
2987                $mail->IsHTML(true);
2988                $mail->Body = $body;
2989
2990                if(!$mail->Send()){
2991                        return $mail->ErrorInfo;
2992                }
2993                else
2994                        return true;
2995        }
2996
2997        function empty_folder($params)
2998        {
2999                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
3000                $mbox_stream = $this->open_mbox($folder);
3001                $return = imap_delete($mbox_stream,'1:*');
3002                if($mbox_stream)
3003                        imap_close($mbox_stream, CL_EXPUNGE);
3004                return $return;
3005        }
3006
3007        function search($params)
3008        {
3009                include("class.imap_attachment.inc.php");
3010                $imap_attachment = new imap_attachment();
3011                $criteria = $params['criteria'];
3012                $return = array();
3013                $folders = $this->get_folders_list();
3014
3015                $j = 0;
3016                foreach($folders as $folder)
3017                {
3018                        $mbox_stream = $this->open_mbox($folder);
3019                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
3020
3021                        if ($messages == '')
3022                                continue;
3023
3024                        $i = 0;
3025                        $return[$j] = array();
3026                        $return[$j]['folder_name'] = $folder['name'];
3027
3028                        foreach($messages as $msg_number)
3029                        {
3030                                $header = $this->get_header($msg_number);
3031                                if (!is_object($header))
3032                                        return false;
3033
3034                                $return[$j][$i]['msg_folder']   = $folder['name'];
3035                                $return[$j][$i]['msg_number']   = $msg_number;
3036                                $return[$j][$i]['Recent']               = $header->Recent;
3037                                $return[$j][$i]['Unseen']               = $header->Unseen;
3038                                $return[$j][$i]['Answered']     = $header->Answered;
3039                                $return[$j][$i]['Deleted']              = $header->Deleted;
3040                                $return[$j][$i]['Draft']                = $header->Draft;
3041                                $return[$j][$i]['Flagged']              = $header->Flagged;
3042
3043                                $date_msg = gmdate("d/m/Y",$header->udate);
3044                                if (gmdate("d/m/Y") == $date_msg)
3045                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
3046                                else
3047                                        $return[$j][$i]['udate'] = $date_msg;
3048
3049                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3050                                $return[$j][$i]['fromaddress'] = '';
3051                                foreach ($fromaddress as $tmp)
3052                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
3053
3054                                $from = $header->from;
3055                                $return[$j][$i]['from'] = array();
3056                                $tmp = imap_mime_header_decode($from[0]->personal);
3057                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3058                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
3059                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
3060
3061                                $to = $header->to;
3062                                $return[$j][$i]['to'] = array();
3063                                $tmp = imap_mime_header_decode($to[0]->personal);
3064                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3065                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
3066                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
3067
3068                                $subject = imap_mime_header_decode($header->fetchsubject);
3069                                $return[$j][$i]['subject'] = '';
3070                                foreach ($subject as $tmp)
3071                                        $return[$j][$i]['subject'] .= $tmp->text;
3072
3073                                $return[$j][$i]['Size'] = $header->Size;
3074                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
3075
3076                                $return[$j][$i]['attachment'] = array();
3077                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
3078
3079                                $i++;
3080                        }
3081                        $j++;
3082                        if($mbox_stream)
3083                                imap_close($mbox_stream);
3084                }
3085
3086                return $return;
3087        }
3088       
3089       
3090        function mobile_search($params)
3091        {
3092                include("class.imap_attachment.inc.php");
3093                $imap_attachment = new imap_attachment();
3094                $criterias = array ("TO","SUBJECT","FROM","CC");
3095                $return = array();
3096                $folders = $this->get_folders_list();
3097                $num_msgs = 0;
3098                                         
3099                foreach($folders as $id =>$folder)
3100                {
3101                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3102                                foreach($criterias as $criteria_fixed)
3103                    {
3104                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3105                                        $mbox_stream = $this->open_mbox($folder['folder_name']);
3106       
3107                                        $messages = imap_search($mbox_stream, $_filter, SE_UID);
3108                                       
3109                                        if ($messages == ''){
3110                                                if($mbox_stream)
3111                                                        imap_close($mbox_stream);
3112                                                continue;       
3113                                        }
3114                                                                       
3115                                        foreach($messages as $msg_number)
3116                                        {                                       
3117                                                $temp = $this->get_info_head_msg($msg_number);
3118                                                if(!$temp)
3119                                                        return false;
3120               
3121                                                $return[$num_msgs] = $temp;
3122                                                $num_msgs++;
3123                                        }
3124                                        $return['num_msgs'] = $num_msgs;
3125                                       
3126                                        if($mbox_stream)
3127                                                imap_close($mbox_stream);
3128                                }
3129                        }
3130                               
3131                }
3132                return $return;
3133        }
3134
3135        function delete_and_show_previous_message($params)
3136        {
3137                $return = $this->get_info_previous_msg($params);
3138
3139                $params_tmp1 = array();
3140                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3141                $params_tmp1['folder'] = $params['msg_folder'];
3142                $return_tmp1 = $this->delete_msg($params_tmp1);
3143
3144                $return['msg_number_deleted'] = $return_tmp1;
3145
3146                return $return;
3147        }
3148
3149
3150        function automatic_trash_cleanness($params)
3151        {
3152                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3153                $criteria =  'BEFORE "'.$before_date.'"';
3154                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
3155                // Free others requests
3156                session_write_close();
3157                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3158                if (is_array($messages)){
3159                        foreach ($messages as $msg_number){
3160                                imap_delete($mbox_stream, $msg_number, FT_UID);
3161                        }
3162                }
3163                if($mbox_stream)
3164                        imap_close($mbox_stream, CL_EXPUNGE);
3165                return $messages;
3166        }
3167//      Fix the search problem with special characters!!!!
3168        function remove_accents($string) {
3169                return strtr($string,
3170                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
3171                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3172        }
3173
3174        function make_search_date($date){
3175
3176            $months = array(
3177                1   => 'jan',
3178                2   => 'feb',
3179                3   => 'mar',
3180                4   => 'apr',
3181                5   => 'may',
3182                6   => 'jun',
3183                7   => 'jul',
3184                8   => 'aug',
3185                9   => 'sep',
3186                10  => 'oct',
3187                11  => 'nov',
3188                12  => 'dec'
3189            );
3190
3191            //TODO: Adaptar a data de acordo com o locale do sistema.
3192            list($day,$month,$year) = explode("/", $date);
3193            $search_date = $day."-".$months[intval($month)]."-".$year;
3194            return $search_date;
3195
3196        }
3197
3198        function search_msg($params = ''){
3199                $retorno = "";
3200                $mbox_stream = "";
3201                if(strpos($params['condition'],"#")===false) { //local messages
3202                        $search=false;
3203                }
3204                else {
3205                        $search = explode(",",$params['condition']);
3206                }
3207
3208                if($search){
3209                        $search_criteria = '';
3210                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
3211                        foreach($search as $tmp)
3212                        {
3213                                $tmp1 = explode("##",$tmp);
3214                                $sum = 0;
3215                                $name_box = $tmp1[0];
3216                                unset($filter);
3217                                foreach($tmp1 as $index => $criteria)
3218                                {
3219                                    if ($index != 0 && strlen($criteria) != 0)
3220                                    {
3221                                        $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
3222                                        $filter .= " ".$filter_array[0];
3223                                        if (strlen($filter_array[1]) != 0){
3224                                            if (trim($filter_array[0]) != 'BEFORE' &&
3225                                                trim($filter_array[0]) != 'SINCE' &&
3226                                                trim($filter_array[0]) != 'ON')
3227                                            {
3228                                                // Remove accents from criteria, because method remove accents is broken.
3229                                                $filter .= '"'.strtr($filter_array[1],
3230                                                    "áàâãäéèêëíìîïóòôõöúùûüçÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ",
3231                                                    "aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC").'"';
3232                                            }
3233                                            else {
3234                                                $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3235                                            }
3236                                        }
3237                                    }
3238                                }
3239                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3240
3241                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
3242                                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
3243                                {
3244                                        $folder_name = explode($this->imap_delimiter,$name_box);
3245                                        $this->ldap = new ldap_functions();
3246                                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3247                                        {
3248                                                $folder_name[1] = $cn;
3249                                        }
3250                                        $folder_name = implode($this->imap_delimiter,$folder_name);
3251                                }
3252                                else
3253                                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3254
3255                                if(!is_resource($mbox_stream))
3256                                        $mbox_stream = $this->open_mbox($name_box);
3257                                else
3258                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
3259
3260                                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search
3261
3262                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3263
3264                                        foreach($all_criterias as $criteria_fixed)
3265                                        {
3266                                                $_filter = $criteria_fixed . substr($filter,4);
3267
3268                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
3269                                                // Testa aqui
3270                                                if($search_criteria) // && count($search_criteria) < $search_result_number)
3271                                                {
3272                                                        foreach($search_criteria as $new_search){
3273                                                                if ($search_result_number != '65536' && $sum == $search_result_number)
3274                                                                {
3275                                                                  return $retorno ? $sum . "=sumResults=" . $retorno : "none";
3276                                                                }
3277
3278                                                                $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");
3279                                                                if(!@strstr($retorno,$m_token))
3280                                                                {
3281                                                                    $retorno .= $m_token;
3282                                                                    $sum++;
3283                                                                }
3284                                                        }
3285                                                }
3286                                        }
3287                                }
3288                                else {
3289                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3290                                        if( is_array( $search_criteria) )
3291                                        {
3292                                                foreach($search_criteria as $new_search)
3293                                                {
3294                                                    if ($search_result_number != '65536' && $sum == $search_result_number)
3295                                                    {
3296                                                        return $retorno ? $sum . "=sumResults=" . $retorno : "none";
3297                                                    }
3298                                                    $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");
3299                                                    $sum++;
3300                                                }
3301                                        }
3302                                }
3303
3304//                                $acumulated_results += $sum;
3305//
3306//                                if ($search_result_number != '65536' && $acumulated_results >= $search_result_number)
3307//                                {
3308//                                    return "many results";
3309//                                }
3310                        }
3311                }
3312                if($mbox_stream)
3313                        imap_close($mbox_stream);
3314
3315                if ($retorno){
3316                    return $retorno;
3317                }
3318                else
3319                {
3320                    return 'none';
3321                }
3322                //return $retorno ? $retorno : "none";
3323        }
3324
3325        function get_msg($uid_msg,$name_box, $mbox_stream )
3326        {
3327                $header = $this->get_header($uid_msg);
3328                include_once("class.imap_attachment.inc.php");
3329                $imap_attachment = new imap_attachment();
3330                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3331                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3332                $flag = $header->Unseen
3333                        .$header->Recent
3334                        .$header->Flagged
3335                        .$header->Draft
3336                        .$header->Answered
3337                        .$header->Deleted
3338                        .$attachments;
3339
3340
3341                $subject = $this->decode_string($header->fetchsubject);
3342                $from = $header->from[0]->mailbox;
3343                if($header->from[0]->personal != "")
3344                        $from = $header->from[0]->personal;
3345                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size) ."--". $flag;
3346                return $ret_msg;
3347        }
3348
3349
3350        function size_msg($size){
3351                $var = floor($size/1024);
3352                if($var >= 1){
3353                        return $var." kb";
3354                }else{
3355                        return $size ." b";
3356                }
3357        }
3358       
3359        function ob_array($the_object)
3360        {
3361           $the_array=array();
3362           if(!is_scalar($the_object))
3363           {
3364               foreach($the_object as $id => $object)
3365               {
3366                   if(is_scalar($object))
3367                   {
3368                       $the_array[$id]=$object;
3369                   }
3370                   else
3371                   {
3372                       $the_array[$id]=$this->ob_array($object);
3373                   }
3374               }
3375               return $the_array;
3376           }
3377           else
3378           {
3379               return $the_object;
3380           }
3381        }
3382
3383        function getacl()
3384        {
3385                $this->ldap = new ldap_functions();
3386
3387                $return = array();
3388                $mbox_stream = $this->open_mbox();
3389                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3390
3391                $i = 0;
3392                foreach ($mbox_acl as $user => $acl)
3393                {
3394                        if ($user != $this->username)
3395                        {
3396                                $return[$i]['uid'] = $user;
3397                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3398                        }
3399                        $i++;
3400                }
3401                return $return;
3402        }
3403
3404        function setacl($params)
3405        {
3406                $old_users = $this->getacl();
3407                if (!count($old_users))
3408                        $old_users = array();
3409
3410                $tmp_array = array();
3411                foreach ($old_users as $index => $user_info)
3412                {
3413                        $tmp_array[$index] = $user_info['uid'];
3414                }
3415                $old_users = $tmp_array;
3416
3417                $users = unserialize($params['users']);
3418                if (!count($users))
3419                        $users = array();
3420
3421                //$add_share = array_diff($users, $old_users);
3422                $remove_share = array_diff($old_users, $users);
3423
3424                $mbox_stream = $this->open_mbox();
3425
3426                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3427                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3428
3429                /*if (count($add_share))
3430                {
3431                        foreach ($add_share as $index=>$uid)
3432                        {
3433                        if (is_array($mailboxes_list))
3434                        {
3435                        foreach ($mailboxes_list as $key => $val)
3436                        {
3437                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3438                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3439                        }
3440                        }
3441                        }
3442                }*/
3443
3444                if (count($remove_share))
3445                {
3446                        foreach ($remove_share as $index=>$uid)
3447                        {
3448                        if (is_array($mailboxes_list))
3449                        {
3450                        foreach ($mailboxes_list as $key => $val)
3451                        {
3452                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3453                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3454                        }
3455                        }
3456                        }
3457                }
3458
3459                return true;
3460        }
3461
3462        function getaclfromuser($params)
3463        {
3464                $useracl = $params['user'];
3465
3466                $return = array();
3467                $return[$useracl] = 'false';
3468                $mbox_stream = $this->open_mbox();
3469                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3470
3471                foreach ($mbox_acl as $user => $acl)
3472                {
3473                        if (($user != $this->username) && ($user == $useracl))
3474                        {
3475                                $return[$user] = $acl;
3476                        }
3477                }
3478                return $return;
3479        }
3480
3481        function getacltouser($user)
3482        {
3483                $return = array();
3484                $mbox_stream = $this->open_mbox();
3485                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3486                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3487                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3488                if(substr($user,0,4) != 'user')
3489                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3490                else
3491                  $mbox_acl = imap_getacl($mbox_stream, $user);
3492                return $mbox_acl[$this->username];
3493        }
3494
3495
3496        function setaclfromuser($params)
3497        {
3498                $user = $params['user'];
3499                $acl = $params['acl'];
3500
3501                $mbox_stream = $this->open_mbox();
3502
3503                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3504                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3505
3506                if (is_array($mailboxes_list))
3507                {
3508                        foreach ($mailboxes_list as $key => $val)
3509                        {
3510                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3511                                $folder = str_replace("&-", "&", $folder);
3512                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3513                                {
3514                                        $return = imap_last_error();
3515                                }
3516                        }
3517                }
3518                if (isset($return))
3519                        return $return;
3520                else
3521                        return true;
3522        }
3523
3524        function download_attachment($msg,$msgno)
3525        {
3526                $array_parts_attachments = array();
3527                //$array_parts_attachments['names'] = '';
3528                include_once("class.imap_attachment.inc.php");
3529                $imap_attachment = new imap_attachment();
3530
3531                if (count($msg->fname[$msgno]) > 0)
3532                {
3533                        $i = 0;
3534                        foreach ($msg->fname[$msgno] as $index=>$fname)
3535                        {
3536                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3537                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
3538                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3539                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3540                                //$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3541                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3542                                $i++;
3543                        }
3544                }
3545                //$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3546                return $array_parts_attachments;
3547        }
3548
3549        function spam($params)
3550        {
3551                $is_spam = $params['spam'];
3552                $folder = $params['folder'];
3553                $mbox_stream = $this->open_mbox($folder);
3554                $msgs_number = explode(',',$params['msgs_number']);
3555
3556                foreach($msgs_number as $msg_number) {
3557                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3558                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3559                        $body = imap_body($mbox_stream, $imap_msg_number);
3560                        $msg = $header . $body;
3561                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3562                        $username = $this->username;
3563                        strtok($email, '@');
3564                        $domain = strtok('@');
3565
3566                        //Encontrar a assinatura do dspam no cabecalho
3567                        $v = explode("\r\n", $header);
3568                        foreach ($v as $linha){
3569                                if (eregi("^Message-ID", $linha)) {
3570                                        $args = explode(" ", $linha);
3571                                        $msg_id = "'$args[1]'";
3572                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
3573                                        $args = explode(" ",$linha);
3574                                        $signature = $args[1];
3575                                }
3576                        }
3577
3578                        // Seleciona qual comando a ser executado
3579                        switch($is_spam){
3580                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
3581                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
3582                        }
3583
3584                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3585                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
3586                        system($cmd);
3587                }
3588                imap_close($mbox_stream);
3589                return false;
3590        }
3591        function get_header($msg_number){
3592                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3593                if (!is_object($header))
3594                        return false;
3595                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
3596                $pdate = date_parse($header->MailDate);
3597                $header->udate +=  $pdate['zone']*(-60);
3598
3599                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3600                        $flag = preg_match('/importance *: *(.*)\r/i',
3601                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3602                                                ,$importance);
3603                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3604                }
3605
3606                return $header;
3607        }
3608
3609//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
3610///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.
3611
3612    function insert_email($source,$folder,$timestamp){
3613        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3614        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
3615        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3616        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
3617        $imap_options = '/notls/novalidate-cert';
3618        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3619        if(imap_last_error())
3620        {
3621            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3622       }
3623        if($timestamp){
3624            $tempDir = ini_get("session.save_path");
3625            $file = $tempDir."imap_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
3626                $f = fopen($file,"w");
3627                fputs($f,base64_encode($source));
3628            fclose($f);
3629            $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);
3630            $return['command']=exec(escapeshellcmd($command));
3631        }else{
3632            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3633        }
3634        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3635        $return['msg_no'] = $status->uidnext - 1;
3636                $return['error'] = imap_last_error();
3637        if($mbox_stream)
3638                        imap_close($mbox_stream);
3639        return $return;
3640
3641    }
3642
3643    function show_decript($params){
3644        $source = $params['source'];
3645        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3646        $source = str_replace(" ", "+", $source,$i);
3647
3648        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3649            if(!$source = base64_decode($source,true))
3650                return "error ".$source."Espaços ".$i;
3651
3652        }
3653        else {
3654            if(!$source = base64_decode($source))
3655                return "error ".$source."Espaços ".$i;
3656        }
3657
3658        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3659
3660                $get['msg_number'] = $insert['msg_no'];
3661                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
3662                $return = $this->get_info_msg($get);
3663                $get['msg_number'] = $params['ID'];
3664                $get['msg_folder'] = $params['folder'];
3665                $tmp = $this->get_info_msg($get);
3666                if(!$tmp['status_get_msg_info'])
3667                {
3668                        $return['msg_day']=$tmp['msg_day'];
3669                        $return['msg_hour']=$tmp['msg_hour'];
3670                        $return['fulldate']=$tmp['fulldate'];
3671                        $return['smalldate']=$tmp['smalldate'];
3672                }
3673                else
3674                {
3675                        $return['msg_day']='';
3676                        $return['msg_hour']='';
3677                        $return['fulldate']='';
3678                        $return['smalldate']='';
3679                }
3680        $return['msg_no'] =$insert['msg_no'];
3681        $return['error'] = $insert['error'];
3682        $return['folder'] = $params['folder'];
3683        //$return['acls'] = $insert['acls'];
3684        $return['original_ID'] =  $params['ID'];
3685
3686        return $return;
3687
3688    }
3689
3690//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
3691//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
3692
3693    function treat_base64_from_post($source){
3694            $offset = 0;
3695            do
3696            {
3697                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
3698                    {
3699                            $inicio = strpos($source, "\n\r", $inicio);
3700                            $fim = strpos($source, '--', $inicio);
3701                            if(!$fim)
3702                                    $fim = strpos($source,"\n\r", $inicio);
3703                            $length = $fim-$inicio;
3704                            $parte = substr( $source,$inicio,$length-1);
3705                            $parte = str_replace(" ", "+", $parte);
3706                            $source = substr_replace($source, $parte, $inicio, $length-1);
3707                    }
3708                    if($offset > $inicio)
3709                    $offset=FALSE;
3710                    else
3711                    $offset = $inicio;
3712            }
3713            while($offset);
3714            return $source;
3715    }
3716
3717//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.
3718
3719    function unarchive_mail($params)
3720    {
3721        $dest_folder = $params['folder'];
3722        $sources = explode("#@#@#@",$params['source']);
3723        $timestamps = explode("#@#@#@",$params['timestamp']);
3724        foreach($sources as $index=>$src) {
3725                        if($src!=""){
3726                                $source = $this->treat_base64_from_post($src);
3727                                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index]);
3728                        }
3729                }
3730        return $insert;
3731    }
3732
3733    function download_all_local_attachments($params)
3734    {
3735        $source = $params['source'];
3736        $source = $this->treat_base64_from_post($source);
3737        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3738        $exporteml = new ExportEml();
3739        $params['num_msg']=$insert['msg_no'];
3740        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
3741        return $exporteml->download_all_attachments($params);
3742    }
3743    function get_quota_folders(){
3744
3745            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
3746            include_once("class.imapfp.inc.php");           
3747            $imapfp = new imapfp();
3748
3749            if(!$imapfp->open($this->imap_server,$this->imap_port))
3750                    return $imapfp->get_error();             
3751            if (!$imapfp->login( $this->username,$this->password ))
3752                    return $imapfp->get_error();
3753
3754            $response_array = $imapfp->get_mailboxes_size();
3755            if ($imapfp->error)
3756                    return $imapfp->get_error();
3757
3758            $data = array();
3759            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
3760            $data["quota_root"] = $quota_root;
3761
3762            foreach ($response_array as $idx=>$line) {
3763                    $line2 = str_replace('"', "", $line);
3764                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
3765                    list($folder,$size) = explode(";",$line2);
3766                    $size = str_replace(")","",$size);
3767                    $quotaPercent = (($size / 1048576) / $data["quota_root"]["quota_limit"])*100;
3768                    if ($size < 1048576 && $size > 1024)
3769                            $quota_used = round($size / 1024, 0).' Kb';
3770                    else if($size > 1024)
3771                            $quota_used = round($size / (1024*1024), 1).' Mb';
3772                    else
3773                            $quota_used = $size." b";
3774                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
3775                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
3776                            $folder = $this->functions->getLang("Inbox");
3777                    }
3778                    else
3779                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
3780
3781                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
3782            }
3783            $imapfp->close();
3784            return $data;
3785    } 
3786}
3787?>
Note: See TracBrowser for help on using the repository browser.