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

Revision 2057, 138.2 KB checked in by amuller, 14 years ago (diff)

Ticket #921 - Correção de alguns anexos multipart

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