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

Revision 3389, 138.3 KB checked in by eduardoalex, 14 years ago (diff)

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