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

Revision 1475, 123.1 KB checked in by amuller, 15 years ago (diff)

Ticket #672 - Correção do replace links para visualizar links

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