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

Revision 3242, 138.8 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #1271 - Corrigido comentarios do html, para correta exibicao nos navegadores IE.

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