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

Revision 3392, 138.5 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #1210 - Corrigido erro da paginacao na selecao de algum filtro

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