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

Revision 1489, 123.2 KB checked in by rodsouza, 15 years ago (diff)

Ticket #2 - Permitir que imagens no corpo do e-mail sejam visualizadas corretamente.

  • 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>".$attachment['type'].' - '.$attachment['part_in_msg']."<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                                                                $content .= $this->decodeBody(
794                                                                        imap_fetchbody(
795                                                                                $this->mbox,
796                                                                                $msg_number,
797                                                                                ( $attachment['part_in_msg'] + (
798                                                                                        ( strtolower( $attachment[ 'type' ] ) == 'delivery-status' ) ? 0 : 1 )
799                                                                                ) . ".1",
800                                                                                FT_UID
801                                                                        ),
802                                                                        $msg->encoding[ $msg_number ][ $values ],
803                                                                        $msg->charset[ $msg_number ][ $values ]
804                                                                );
805                                                                break;
806                                                        }
807                                                }
808                                        }
809                                }
810                        }
811                        if($file_type == "text/plain" && ($show_only_html &&  $msg_part == 1) ||  (!$show_only_html &&  $msg_part == 3)){
812                                if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" &&  $msg_part == 1)
813                                        $content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
814                                else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
815                                        $content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));
816                        }
817                }
818                // Force message with flag Seen (imap_fetchbody not works correctly)
819                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");
820                $this->set_messages_flag($params);
821                $content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
822                $content = $this->replace_special_characters($content);
823                $return['body'] = $content;
824                return $return;
825        }
826
827        function htmlfilter($body)
828        {
829                require_once('htmlfilter.inc');
830
831                $tag_list = Array(
832                                false,
833                                'blink',
834                                'object',
835                                'meta',
836                                'html',
837                                'link',
838                                'frame',
839                                'iframe',
840                                'layer',
841                                'ilayer',
842                                'plaintext'
843                );
844
845                /**
846                * A very exclusive set:
847                */
848                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
849                $rm_tags_with_content = Array(
850                                'script',
851                                'style',
852                                'applet',
853                                'embed',
854                                'head',
855                                'frameset',
856                                'xml',
857                                'xmp'
858                );
859
860                $self_closing_tags =  Array(
861                                'img',
862                                'br',
863                                'hr',
864                                'input'
865                );
866
867                $force_tag_closing = true;
868
869                $rm_attnames = Array(
870                        '/.*/' =>
871                                Array(
872                                        '/target/i',
873                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
874                                        '/^dynsrc/i',
875                                        '/^datasrc/i',
876                                        '/^data.*/i',
877                                        '/^lowsrc/i'
878                                )
879                );
880
881                /**
882                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
883                 * some idea of what's going on here. :)
884                 */
885
886                $bad_attvals = Array(
887                '/.*/' =>
888                Array(
889                      '/.*/' =>
890                              Array(
891                                Array(
892                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
893                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
894                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
895                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
896                                      ),
897                            Array(
898                                              '\\1oddjob:\\2\\1',
899                                          //'\\1uucp:\\2\\1', -> doclinks notes
900                                      '\\1amaretto:\\2\\1',
901                                          '\\1round:\\2\\1'
902                                        )
903                                    ),
904
905                          '/^style/i' =>
906                              Array(
907                                        Array(
908                                          '/expression/i',
909                                              '/behaviou*r/i',
910                                          '/binding/i',
911                                              '/include-source/i',
912                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
913                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
914                                         ),
915                                        Array(
916                                          'idiocy',
917                                              'idiocy',
918                                          'idiocy',
919                                              'idiocy',
920                                          'url(\\1http://securityfocus.com/\\1)',
921                                          'url(\\1http://securityfocus.com/\\1)'
922                                         )
923                                )
924                          )
925                    );
926
927                $add_attr_to_tag = Array(
928                                '/^a$/i' => Array('target' => '"_new"')
929                );
930
931
932                $trusted_body = sanitize($body,
933                                $tag_list,
934                                $rm_tags_with_content,
935                                $self_closing_tags,
936                                $force_tag_closing,
937                                $rm_attnames,
938                                $bad_attvals,
939                                $add_attr_to_tag
940                );
941
942            return $trusted_body;
943        }
944
945        function decodeBody($body, $encoding, $charset=null)
946        {
947                /**
948                * replace e-mail by anchor.
949                */
950                // HTML Filter
951                //$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);
952        //$body = str_replace("\r\n", "\n", $body);
953                if ($encoding == 'quoted-printable')
954                {
955                        /*
956
957                        for($i=0;$i<256;$i++) {
958                                $c1=dechex($i);
959                                if(strlen($c1)==1){$c1="0".$c1;}
960                                $c1="=".$c1;
961                                $myqprinta[]=$c1;
962                                $myqprintb[]=chr($i);
963                        }
964                         */
965                        $body = str_replace($myqprinta,$myqprintb,($body));
966                        $body = quoted_printable_decode($body);
967                while (ereg("=\n", $body))
968                {
969                        $body = ereg_replace ("=\n", '', $body);
970                }
971        }
972        else if ($encoding == 'base64')
973        {
974                $body = base64_decode($body);
975        }
976        else if ($encoding == '7bit')
977        {
978                $body = quoted_printable_decode($body);
979        }
980                // All other encodings are returned raw.
981                if (strtolower($charset) == "utf-8")
982                        return utf8_decode($body);
983        else
984                        return $body;
985        }
986
987        function process_embedded_images($msg, $msgno, $body, $msg_folder)
988        {
989                if (count($msg->inline_id[$msgno]) > 0)
990                {
991                        foreach ($msg->inline_id[$msgno] as $index => $cid)
992                        {
993                                $cid = eregi_replace("<", "", $cid);
994                                $cid = eregi_replace(">", "", $cid);
995                                $msg_part = $msg->pid[$msgno][$index];
996                                //$body = eregi_replace("alt=\"\"", "", $body);
997                                $body = eregi_replace("<br/>", "", $body);
998                                $body = str_replace("src=\"cid:".$cid."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
999                                $body = str_replace("src='cid:".$cid."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1000                                $body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
1001                        }
1002                }
1003
1004                return $body;
1005        }
1006
1007        function replace_special_characters($body)
1008        {
1009                // Suspected TAGS!
1010                /*$tag_list = Array(
1011                        'blink','object','meta',
1012                        'html','link','frame',
1013                        'iframe','layer','ilayer',
1014                        'plaintext','script','style','img',
1015                        'applet','embed','head',
1016                        'frameset','xml','xmp');
1017                */
1018
1019                // Layout problem: Change html elements
1020                // with absolute position to relate position, CASE INSENSITIVE.
1021                $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
1022
1023                $tag_list = Array('head','blink','object','frame',
1024                        'iframe','layer','ilayer','plaintext','script',
1025                        'applet','embed','frameset','xml','xmp','style');
1026
1027                $body = $this-> replace_links($body);
1028                $blocked_tags = array();
1029                foreach($tag_list as $index => $tag) {
1030                        $new_body = @mb_eregi_replace("<$tag", "<!--$tag", $body);
1031                        if($body != $new_body) {
1032                                $blocked_tags[] = $tag;
1033                        }
1034                        $body = @mb_eregi_replace("</$tag>", "</$tag-->", $new_body);
1035                }
1036                // Malicious Code Remove
1037                $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";
1038                preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
1039                foreach($rest[0] as $i => $val)
1040                        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
1041                        $body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
1042
1043                return  "<span>".$body;
1044        }
1045
1046        function replace_links($body) {
1047                $matches = array();
1048                // Verify exception.
1049                @preg_match("/<a href=\"notes:\/\/\//",$body,$matches);
1050                // If there is no exception,then open the link in new window.
1051                if(count($matches))
1052                        return $body;
1053               
1054                $pattern = '/(?<=[\s\><\n\r;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[\/.\-~&=?%;@#,+\w:]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\/\w.\-~&=?%;@+]*))/i';
1055               
1056                $replacement = '<a href="http$3://$4$5" target="_blank">$1</a>';
1057                return preg_replace($pattern, $replacement, $body);
1058
1059                // Original
1060                //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);
1061        }
1062
1063        function get_signature($msg, $msg_number, $msg_folder)
1064        {
1065        include_once("../security/classes/CertificadoB.php");
1066                include_once("class.db_functions.inc.php");
1067                foreach ($msg->file_type[$msg_number] as $index => $file_type)
1068                {
1069            $sign = array();
1070                        $temp = $this->get_info_head_msg($msg_number);
1071                        if($temp['ContentType'] =='normal') return $sign;
1072                        $file_type = strtolower($file_type);
1073                        if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
1074                        {
1075                                if ($file_type == 'application/x-pkcs7-signature' || $file_type == 'application/pkcs7-signature')
1076                                {
1077                                        if(!$this->mbox || !is_resource($this->mbox))
1078                                        $this->mbox = $this->open_mbox($msg_folder);
1079
1080                                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
1081
1082                                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1083                                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
1084
1085                                        $certificado = new certificadoB();
1086                                        $validade = $certificado->verificar($imap_msg);
1087
1088                                        if ($certificado->apresentado)
1089                                        {
1090                                                $from = $header->from;
1091                                                foreach ($from as $id => $object) {
1092                                                        $fromname = $object->personal;
1093                                                    $fromaddress = $object->mailbox . "@" . $object->host;
1094                                        }
1095                                                $sign_alert = '';
1096                                                foreach ($certificado->erros_ssl as $item)
1097                                                {
1098                                                        $check_error_msg = $this->functions->getLang($item);
1099                                                        /*
1100                                                         * Desabilite o teste abaixo para mostrar todas as mensagem
1101                                                         * de erro.
1102                                                         */
1103                                                        //if (!strpos($check_error_msg,'*',strlen($check_error_msg-1)))
1104                                                        //{
1105                                                        $sign[] = "<span style=color:red>" . $check_error_msg . " </span>";
1106                                                        //}
1107                                                }
1108                                                if (count($certificado->erros_ssl) < 1)
1109                                                {
1110                                                        $check_msg = $this->functions->getLang('Message untouched') . " ";
1111                                                        if($fromaddress == $certificado->dados['EMAIL'])
1112                                                        {
1113                                                                $check_msg .= $this->functions->getLang('and') . " ";
1114                                                                $check_msg .= $this->functions->getLang('authentic');
1115                                                        }
1116                                                        $sign[] = "<strong>".$check_msg."</strong>";
1117                                                }
1118                                                if($fromaddress != $certificado->dados['EMAIL'])
1119                                                {
1120                                                        $sign[] =       "<span style=color:red>" .
1121                                                                                $this->functions->getLang('message') . " " .
1122                                                                        $this->functions->getLang('with signer different from sender') .
1123                                                                        " </span>";
1124                                                }
1125                                                $sign[] = "<strong>" . $this->functions->getLang('Message signed by: ') . "</strong>" . $certificado->dados['NOME'];
1126                                                $sign[] = "<strong>" . $this->functions->getLang('Certificate email: ') . "</strong>" . $certificado->dados['EMAIL'];
1127                                                $sign[] = "<strong>" . $this->functions->getLang('Mail from: ') . "</strong>" . $fromaddress;
1128                                                $sign[] = "<strong>" . $this->functions->getLang('Certificate Authority: ') . "</strong>" . $certificado->dados['EMISSOR'];
1129                                                $sign[] = "<strong>" . $this->functions->getLang('Validity of certificate: ') . "</strong>" . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
1130                                                $sign[] = "<strong>" . $this->functions->getLang('Message date: ') . "</strong>" . $header->Date;
1131
1132                                            $cert = openssl_x509_parse($certificado->cert_assinante);
1133                                                /*
1134                                                $sign[] = '<table>';
1135                                                $sign[] = '<tr><td colspan=1><b>Expedido para:</b></td></tr>';
1136                                                $sign[] = '<tr><td>Nome Comum (CN) </td><td>' . $cert[subject]['CN'] .  '</td></tr>';
1137                                                $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1138                                                $sign[] = '<tr><td>Data de nascimento </td><td>' . $certificado->dados['NASCIMENTO'] .  '</td></tr>';
1139                                                $sign[] = '<tr><td>CPF </td><td>' . $certificado->dados['CPF'] .  '</td></tr>';
1140                                                $sign[] = '<tr><td>Documento identidade </td><td>' . $certificado->dados['RG'] .  '</td></tr>';
1141                                                $sign[] = '<tr><td>Empresa (O) </td><td>' . $cert[subject]['O'] .  '</td></tr>';
1142                                                $sign[] = '<tr><td>Unidade Organizacional (OU) </td><td>' . $cert[subject]['OU'][0] .  '</td></tr>';
1143                                                //$sign[] = '<tr><td>Numero de serie </td><td>' . $cert['serialNumber'] .  '</td></tr>';
1144                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1145                                                $sign[] = '<tr><td colspan=1><b>Expedido por:</b></td></tr>';
1146                                                $sign[] = '<tr><td>Nome Comum (CN) </td><td>' . $cert[issuer]['CN'] .  '</td></tr>';
1147                                                $sign[] = '<tr><td>Empresa (O) </td><td>' . $cert[issuer]['O'] .  '</td></tr>';
1148                                                $sign[] = '<tr><td>Unidade Organizacional (OU) </td><td>' . $cert[issuer]['OU'][0] .  '</td></tr>';
1149                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1150                                                $sign[] = '<tr><td colspan=1><b>Validade:</b></td></tr>';
1151                                                $H = data_hora($cert[validFrom]);
1152                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1153                                                $sign[] = '<tr><td>Expedido em </td><td>' . $X .  '</td></tr>';
1154                                                $H = data_hora($cert[validTo]);
1155                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1156                                                $sign[] = '<tr><td>Valido ate </td><td>' . $X .  '</td></tr>';
1157                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1158                                                $sign[] = '</table>';
1159                                                */
1160                                                $sign_alert .= 'Expedido para:\n';
1161                                                $sign_alert .= 'Nome Comum (CN)  ' . $cert[subject]['CN'] .  '\n';
1162                                                $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1163                                                $sign_alert .= 'Data de nascimento ' . $X .  '\n';
1164                                                $sign_alert .= 'CPF ' . $certificado->dados['CPF'] .  '\n';
1165                                                $sign_alert .= 'Documento identidade ' . $certificado->dados['RG'] .  '\n';
1166                                                $sign_alert .= 'Empresa (O)  ' . $cert[subject]['O'] .  '\n';
1167                                                $sign_alert .= 'Unidade Organizacional (OU) ' . $cert[subject]['OU'][0] .  '\n';
1168                                                //$sign_alert[] = '<tr><td>Numero de serie </td><td>' . $cert['serialNumber'] .  '</td></tr>';
1169                                                $sign_alert .= '\n';
1170                                                $sign_alert .= 'Expedido por:\n';
1171                                                $sign_alert .= 'Nome Comum (CN) ' . $cert[issuer]['CN'] . '\n';
1172                                                $sign_alert .= 'Empresa (O)  ' . $cert[issuer]['O'] .  '\n';
1173                                                $sign_alert .= 'Unidade Organizacional (OU) ' . $cert[issuer]['OU'][0] .  '\n';
1174                                                $sign_alert .= '\n';
1175                                                $sign_alert .= 'Validade:\n';
1176                                                $H = data_hora($cert[validFrom]);
1177                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1178                                                $sign_alert .= 'Expedido em ' . $X .  '\n';
1179                                                $H = data_hora($cert[validTo]);
1180                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1181                                                $sign_alert .= 'Valido ate ' . $X .  '\n';
1182
1183                                                $sign[] = "<a onclick=\"javascript:alert('" . $sign_alert . "')\"><b><font color=\"#0000FF\">".$this->functions->getLang("More")."...</font></b></a>";
1184                                                $this->db = new db_functions();
1185
1186                                                // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
1187                        if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
1188                            $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
1189                                        }
1190                                     else
1191                                    {
1192                                        $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
1193                                        foreach($certificado->erros_ssl as $item)
1194                                        $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
1195                    }
1196                                }
1197                        }
1198                }
1199                return $sign;
1200        }
1201
1202        function get_thumbs($msg, $msg_number, $msg_folder)
1203        {
1204                $thumbs_array = array();
1205                $i = 0;
1206        foreach ($msg->file_type[$msg_number] as $index => $file_type)
1207        {
1208                $file_type = strtolower($file_type);
1209                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
1210                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
1211                                $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].">";
1212                                $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>";
1213                                        $thumbs_array[] = $href;
1214                        }
1215                        $i++;
1216                }
1217        }
1218        return $thumbs_array;
1219        }
1220
1221        /*function delete_msg($params)
1222        {
1223                $folder = $params['folder'];
1224                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
1225
1226                $mbox_stream = $this->open_mbox($folder);
1227
1228                foreach ($msgs_to_delete as $msg_number){
1229                        imap_delete($mbox_stream, $msg_number, FT_UID);
1230                }
1231                imap_close($mbox_stream, CL_EXPUNGE);
1232                return $params['msgs_to_delete'];
1233        }*/
1234
1235        // Novo
1236        function delete_msgs($params)
1237        {
1238
1239                $folder = $params['folder'];
1240                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
1241                $msgs_number = explode(",",$params['msgs_number']);
1242                $border_ID = $params['border_ID'];
1243
1244                $return = array();
1245
1246                if ($params['get_previous_msg']){
1247                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1248                        // Fix problem in unserialize function JS.
1249                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1250                }
1251
1252                //$mbox_stream = $this->open_mbox($folder);
1253                $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()))));
1254
1255                foreach ($msgs_number as $msg_number)
1256                {
1257                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1258                                $return['msgs_number'][] = $msg_number;
1259                }
1260
1261                $return['folder'] = $folder;
1262                $return['border_ID'] = $border_ID;
1263
1264                if($mbox_stream)
1265                        imap_close($mbox_stream, CL_EXPUNGE);
1266                return $return;
1267        }
1268
1269
1270        function refresh($params)
1271        {
1272                include_once("class.imap_attachment.inc.php");
1273                $imap_attachment = new imap_attachment();
1274                $folder = $params['folder'];
1275                $msg_range_begin = $params['msg_range_begin'];
1276                $msg_range_end = $params['msg_range_end'];
1277                $msgs_existent = $params['msgs_existent'];
1278                $sort_box_type = $params['sort_box_type'];
1279                $sort_box_reverse = $params['sort_box_reverse'];
1280                $msgs_in_the_server = array();
1281                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1282                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1283                $msgs_in_the_server = array_keys($msgs_in_the_server);
1284                if(!count($msgs_in_the_server))
1285                        return array();
1286
1287                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
1288                $msgs_in_the_client = explode(",", $msgs_existent);
1289
1290                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
1291                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
1292
1293                $msgs_to_exec = array();
1294                if ((count($msg_to_insert)) && ($msgs_existent))
1295                {
1296                        foreach($msg_to_insert as $index => $msg_number)
1297                        {
1298                                if ($msgs_in_the_server[$index+1])
1299                                {
1300                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
1301                                        $msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
1302                                }
1303                                else
1304                                {
1305                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
1306                                        $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1307                                }
1308                        }
1309                        ksort($msgs_to_exec);
1310                }
1311                elseif(!$msgs_existent)
1312                {
1313                        foreach($msgs_in_the_server as $index => $msg_number)
1314                        {
1315                                $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1316                        }
1317                }
1318
1319                $return = array();
1320                $i = 0;
1321                foreach($msgs_to_exec as $msg_number => $command)
1322                {
1323                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
1324                        * atributos do cabeçalho. Como eu preciso do atributo Importance
1325                        * para saber se o email é importante ou não, uso abaixo a função
1326                        * imap_fetchheader e busco o atributo importance nela para passar
1327                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1328                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1329                        * não preciso reimplementar o método utilizando o fetchheader.
1330                        * Como na atualização são poucas as mensagens que devem ser renderizadas,
1331                        * a perda em performance é insignificante.
1332                        */
1333            $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1334                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
1335                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
1336
1337                        $header = $this->get_header($msg_number);
1338                        if (!is_object($header))
1339                                continue;
1340
1341                        $return[$i]['msg_number']       = $msg_number;
1342                        $return[$i]['command']          = $command;
1343
1344                        $return[$i]['msg_folder']       = $folder;
1345            // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1346            $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
1347                        $return[$i]['Recent']           = $header->Recent;
1348                        $return[$i]['Unseen']           = $header->Unseen;
1349                        $return[$i]['Answered']         = $header->Answered;
1350                        $return[$i]['Deleted']          = $header->Deleted;
1351                        $return[$i]['Draft']            = $header->Draft;
1352                        $return[$i]['Flagged']          = $header->Flagged;
1353
1354                        $date_msg = gmdate("d/m/Y",$header->udate);
1355                        if (gmdate("d/m/Y") == $date_msg)
1356                                $return[$i]['udate'] = gmdate("H:i",$header->udate);
1357                        else
1358                                $return[$i]['udate'] = $date_msg;
1359
1360                        $from = $header->from;
1361                        $return[$i]['from'] = array();
1362                        $tmp = imap_mime_header_decode($from[0]->personal);
1363                        $return[$i]['from']['name'] = $tmp[0]->text;
1364                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
1365                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
1366                        if(!$return[$i]['from']['name'])
1367                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
1368
1369                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1370                        $return[$i]['toaddress'] = '';
1371                        foreach ($toaddress as $tmp)
1372                                $return[$i]['toaddress'] .= $tmp->text;*/
1373                        $to = $header->to;
1374                        $return[$i]['to'] = array();
1375                        $tmp = imap_mime_header_decode($to[0]->personal);
1376                        $return[$i]['to']['name'] = $tmp[0]->text;
1377                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1378                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
1379
1380                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1381
1382                        $return[$i]['Size'] = $header->Size;
1383                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
1384
1385                        $return[$i]['attachment'] = array();
1386                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
1387                        $i++;
1388                }
1389                $return['new_msgs'] = imap_num_recent($this->mbox);
1390                $return['msgs_to_delete'] = $msg_to_delete;
1391                if($this->mbox && is_resource($this->mbox))
1392                        imap_close($this->mbox);
1393
1394                return $return;
1395        }
1396
1397     /**
1398     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1399     * assinado ou cifrado.
1400     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1401     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1402     * @param $msg_number O número da mesagem
1403     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1404     */
1405    function getMessageType($msg_number, $headers = false){
1406
1407            $contentType = "normal";
1408            if (!$headers){
1409                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1410            }
1411            //$header2 = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1412            if (preg_match("/Content-Type:.*pkcs7-signature/i", $headers) == 1){
1413                $contentType = "signature";
1414            } else if (preg_match("/Content-Type:.*x-pkcs7-mime/i", $headers) == 1){
1415                $contentType = "cipher";
1416            }
1417
1418            return $contentType;
1419    }
1420
1421         /**
1422     * Metodo que retorna todas as pastas do usuario logado.
1423     * @param $params array opcional para repassar os argumentos ao metodo.
1424     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
1425     * excluindo as compartilhadas para ele.
1426     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
1427     * folder_id, folder_name, folder_parent e folder_hasChildren.
1428     */
1429        function get_folders_list($params = null)
1430        {
1431                $mbox_stream = $this->open_mbox();
1432                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
1433                $folders_list = imap_getmailboxes($mbox_stream, $serverString, ($params && $params['noSharedFolders']) ? "INBOX/*" : "*");
1434                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1435
1436                $tmp = array();
1437                $result = array();
1438
1439                if (is_array($folders_list)) {
1440                        reset($folders_list);
1441            $this->ldap = new ldap_functions();
1442
1443                        $i = 0;
1444                        while (list($key, $val) = each($folders_list)) {
1445                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
1446
1447                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1448                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
1449                if($tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas'){
1450                    //error_log('passou', 3,'/tmp/imap_get_list.log');
1451                    //imap_deletemailbox($mbox_stream,imap_utf7_encode("{".$this->imap_server."}".'INBOX/decifradas'));
1452                    continue;
1453                }
1454                $result[$i]['folder_unseen'] = $status->unseen;
1455                                $folder_id = $tmp_folder_id[1];
1456                                $result[$i]['folder_id'] = $folder_id;
1457
1458                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1459                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1460                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1461                                if (substr($folder_id,0,4) == 'user' && is_numeric($result[$i]['folder_name'])) {
1462                                        //$this->ldap = new ldap_functions();
1463                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])){
1464                                                $result[$i]['folder_name'] = $cn;
1465                                        }
1466                                }
1467
1468                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1469                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
1470
1471                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1472                                        $result[$i]['folder_hasChildren'] = 1;
1473                                else
1474                                        $result[$i]['folder_hasChildren'] = 0;
1475
1476                                $i++;
1477                        }
1478                }
1479
1480                foreach ($result as $folder_info)
1481                {
1482                        $array_tmp[] = $folder_info['folder_id'];
1483                }
1484
1485                natcasesort($array_tmp);
1486
1487                foreach ($array_tmp as $key => $folder_id)
1488                {
1489                        $result2[] = $result[$key];
1490                }
1491
1492                $current_folder = "INBOX";
1493                if($params && $params['folder'])
1494                        $current_folder = $params['folder'];
1495                return array_merge($result2, $this->get_quota(array(folder_id => $current_folder)));
1496        }
1497
1498        function create_mailbox($arr)
1499        {
1500                $namebox        = $arr['newp'];
1501                $mbox_stream = $this->open_mbox();
1502                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1503                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
1504
1505                $result = "Ok";
1506                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
1507                {
1508                        $result = implode("<br />\n", imap_errors());
1509                }
1510
1511                if($mbox_stream)
1512                        imap_close($mbox_stream);
1513
1514                return $result;
1515
1516        }
1517
1518        function create_extra_mailbox($arr)
1519        {
1520                $nameboxs = explode(";",$arr['nw_folders']);
1521                $result = "";
1522                $mbox_stream = $this->open_mbox();
1523                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1524                foreach($nameboxs as $key=>$tmp){
1525                        if($tmp != ""){
1526                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1527                                        $result = implode("<br />\n", imap_errors());
1528                                        if($mbox_stream)
1529                                                imap_close($mbox_stream);
1530                                        return $result;
1531                                }
1532                        }
1533                }
1534                if($mbox_stream)
1535                        imap_close($mbox_stream);
1536                return true;
1537        }
1538
1539        function delete_mailbox($arr)
1540        {
1541                $namebox = $arr['del_past'];
1542                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1543                $mbox_stream = $this->open_mbox();
1544                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
1545
1546                $result = "Ok";
1547                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1548                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1549                {
1550                        $result = implode("<br />\n", imap_errors());
1551                }
1552                if($mbox_stream)
1553                        imap_close($mbox_stream);
1554                return $result;
1555        }
1556
1557        function ren_mailbox($arr)
1558        {
1559                $namebox = $arr['current'];
1560                $new_box = $arr['rename'];
1561                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1562                $mbox_stream = $this->open_mbox();
1563                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
1564
1565                $result = "Ok";
1566                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1567                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
1568
1569                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1570                {
1571                        $result = imap_errors();
1572                }
1573                if($mbox_stream)
1574                        imap_close($mbox_stream);
1575                return $result;
1576
1577        }
1578
1579        function get_num_msgs($params)
1580        {
1581                $folder = $params['folder'];
1582                if(!$this->mbox || !is_resource($this->mbox)) {
1583                        $this->mbox = $this->open_mbox($folder);
1584                        if(!$this->mbox || !is_resource($this->mbox))
1585                        return imap_last_error();
1586                }
1587                $num_msgs = imap_num_msg($this->mbox);
1588                if($this->mbox && is_resource($this->mbox))
1589                        imap_close($this->mbox);
1590
1591                return $num_msgs;
1592        }
1593
1594        function send_mail($params)
1595        {
1596                include_once("class.phpmailer.php");
1597                $mail = new PHPMailer();
1598                include_once("class.db_functions.inc.php");
1599                $db = new db_functions();
1600                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
1601                ##
1602                # @AUTHOR Rodrigo Souza dos Santos
1603                # @DATE 2008/09/17
1604                # @BRIEF Checks if the user has permission to send an email with the email address used.
1605                ##
1606                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
1607                {
1608                        $deny = true;
1609                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
1610                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
1611                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
1612
1613                        if ( $deny )
1614                                return "The server denied your request to send a mail, you cannot use this mail address.";
1615                }
1616
1617                //new_message_to backs to mailto: pattern
1618                $params['body'] = eregi_replace("<a href=\"javascript:new_message_to\('([^>]+)'\)\">[^>]+</a>","<a href='mailto:\\1'>\\1</a>",$params['body']);
1619
1620                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1621                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1622                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1623                $subject = $params['input_subject'];
1624                $msg_uid = $params['msg_id'];
1625                $return_receipt = $params['input_return_receipt'];
1626                $is_important = $params['input_important_message'];
1627        $encrypt = $params['input_return_cripto'];
1628                $signed = $params['input_return_digital'];
1629
1630                if($params['smime'])
1631        {
1632            $body = $params['smime'];
1633            $mail->SMIME = true;
1634            // A MSG assinada deve ser testada neste ponto.
1635            // Testar o certificado e a integridade da msg....
1636            include_once("../security/classes/CertificadoB.php");
1637            $erros_acumulados = '';
1638            $certificado = new certificadoB();
1639            $validade = $certificado->verificar($body);
1640            if(!$validade)
1641            {
1642                foreach($certificado->erros_ssl as $linha_erro)
1643                {
1644                    $erros_acumulados .= $linha_erro;
1645                }
1646            }
1647            else
1648            {
1649                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
1650                if ($certificado->apresentado)
1651                {
1652                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
1653                    if($certificado->dados['CPF'] != $this->username) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
1654                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
1655                }
1656                else
1657                {
1658                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
1659                }
1660            }
1661            if(!$erros_acumulados =='')
1662            {
1663                return $erros_acumulados;
1664            }
1665        }
1666        else
1667        {
1668            $body = $params['body'];
1669        }
1670                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
1671                $attachments = $params['FILES'];
1672                $forwarding_attachments = $params['forwarding_attachments'];
1673                $local_attachments = $params['local_attachments'];
1674
1675                $folder =$params['folder'];
1676                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
1677                $folder_name = $params['folder_name'];
1678                // Fix problem with cyrus delimiter changes.
1679                // Dots in names: enabled/disabled.
1680                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1681                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1682                // End Fix.
1683                if ($folder != 'null'){
1684                        $mail->SaveMessageInFolder = $folder;
1685                }
1686////////////////////////////////////////////////////////////////////////////////////////////////////
1687                $mail->SMTPDebug = false;
1688
1689                if($signed && !$params['smime'])
1690                {
1691            $mail->Mailer = "smime";
1692                        $mail->SignedBody = true;
1693                }
1694                else
1695            $mail->IsSMTP();
1696
1697                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1698                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1699                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1700                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1701                if($fromaddress){
1702                        $mail->Sender = $mail->From;
1703                        $mail->SenderName = $mail->FromName;
1704                        $mail->FromName = $fromaddress[0];
1705                        $mail->From = $fromaddress[1];
1706                }
1707
1708                $this->add_recipients("to", $toaddress, &$mail);
1709                $this->add_recipients("cc", $ccaddress, &$mail);
1710                $this->add_recipients("cco", $ccoaddress, &$mail);
1711                $mail->Subject = $subject;
1712                $mail->IsHTML(true);
1713                $mail->Body = $body;
1714
1715        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
1716                {
1717                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
1718            $email = explode(",",$email);
1719            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
1720            // Deve ser verificado um numero limite de destinatarios.
1721            // Deve ser verificado se os certificados sao validos.
1722            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
1723            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
1724            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
1725            $erros_acumulados = "";
1726            $aux_mails = array();
1727            $mail_list = array();
1728            if(count($email) > $numero_maximo)
1729            {
1730                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
1731                return $erros_acumulados;
1732            }
1733            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
1734            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1735            foreach($email as $item)
1736            {
1737                $certificate = $db->get_certificate(strtolower($item));
1738                if(!$certificate)
1739                {
1740                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
1741                    return $erros_acumulados;
1742                }
1743
1744                if (array_key_exists("dberr1", $certificate))
1745                {
1746
1747                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
1748                    return $erros_acumulados;
1749                                }
1750                if (array_key_exists("dberr2", $certificate))
1751                {
1752                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
1753                    //continue;
1754                }
1755                        /*  Retirado este teste para evitar mensagem de erro duplicada.
1756                if (!array_key_exists("certs", $certificate))
1757                {
1758                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
1759                    continue;
1760                }
1761            */
1762                include_once("../security/classes/CertificadoB.php");
1763
1764                foreach ($certificate['certs'] as $registro)
1765                {
1766                    $c1 = new certificadoB();
1767                    $c1->certificado($registro['chave_publica']);
1768                    if ($c1->apresentado)
1769                    {
1770                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
1771                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
1772                        {
1773                            $aux_mails[] = $registro['chave_publica'];
1774                            $mail_list[] = strtolower($item);
1775                        }
1776                        else
1777                        {
1778                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
1779                            {
1780                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
1781                                    $c1->dados['EXPIRADO'],$c2->revogado);
1782                            }
1783
1784                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
1785                            foreach($c2->erros_ssl as $linha)
1786                            {
1787                                $erros_acumulados .=  $linha . chr(0x0A);
1788                            }
1789                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
1790                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
1791                        }
1792                    }
1793                    else
1794                    {
1795                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
1796                    }
1797                }
1798                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
1799                                {
1800                                        return $erros_acumulados;
1801                        }
1802            }
1803
1804            $mail->Certs_crypt = $aux_mails;
1805        }
1806
1807////////////////////////////////////////////////////////////////////////////////////////////////////
1808                //      Build CID for embedded Images!!!
1809                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
1810                $cid_imgs = '';
1811                $name_cid_files = array();
1812                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1813                $cid_array = array();
1814                foreach($cid_imgs[6] as $j => $val){
1815                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
1816                        {
1817                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
1818                        }
1819                        $cid = $cid_array[$cid_imgs[4][$j].$val];
1820                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
1821
1822                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
1823                                {
1824                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
1825                                        $fileName = "image_".($j).".jpg";
1826                                        $fileCode = "base64";
1827                                        $fileType = "image/jpg";
1828                                }
1829                                else
1830                                {
1831                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
1832                                        $file_description = unserialize(rawurldecode($attach_img));
1833
1834                                        foreach($file_description as $i => $descriptor){
1835                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
1836                                        }
1837                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
1838                                        $fileName = $file_description[2];
1839                                        $fileCode = $file_description[4];
1840                                        $fileType = $this->get_file_type($file_description[2]);
1841                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
1842                                }
1843                                $tempDir = ini_get("session.save_path");
1844                                $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";
1845                                $f = fopen($tempDir.'/'.$file,"w");
1846                                fputs($f,$fileContent);
1847                                fclose($f);
1848                                if ($fileContent)
1849                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
1850                                //else
1851                                //      return "Error loading image attachment content";
1852
1853                }
1854////////////////////////////////////////////////////////////////////////////////////////////////////
1855                //      Build Uploading Attachments!!!
1856                if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
1857                {
1858                        $total_uploaded_size = 0;
1859                        $upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
1860                        foreach ($attachments as $attach)
1861                        {
1862                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
1863                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
1864                        }
1865                        if( $total_uploaded_size > $upload_max_filesize)
1866                                return $this->parse_error("message file too big");
1867                }
1868                else if(($params['is_local_forward']=="1") && (count($local_attachments))) { //Caso seja forward de mensagens locais
1869
1870                        $total_uploaded_size = 0;
1871                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
1872                        foreach($local_attachments as $local_attachment) {
1873                                $file_description = unserialize(rawurldecode($local_attachment));
1874                                $tmp = array_values($file_description);
1875                                foreach($file_description as $i => $descriptor){
1876                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1877                                }
1878                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
1879                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
1880                        }
1881                        if( $total_uploaded_size > $upload_max_filesize)
1882                                return 'false';
1883                }
1884////////////////////////////////////////////////////////////////////////////////////////////////////
1885                //      Build Forwarding Attachments!!!
1886                if (count($forwarding_attachments) > 0)
1887                {
1888                        // Bug fixed for array_search function
1889                        if(count($name_cid_files) > 0) {
1890                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
1891                                $name_cid_files[0] = null;
1892                        }
1893
1894                        foreach($forwarding_attachments as $forwarding_attachment)
1895                        {
1896                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
1897                                        $tmp = array_values($file_description);
1898                                        foreach($file_description as $i => $descriptor){
1899                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1900                                        }
1901                                        $file_description = $tmp;
1902                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
1903                                        $fileName = $file_description[2];
1904                                        if(!array_search(trim($fileName),$name_cid_files)) {
1905                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
1906                                }
1907                        }
1908                }
1909
1910////////////////////////////////////////////////////////////////////////////////////////////////////
1911                // Important message
1912                if($is_important)
1913                        $mail->isImportant();
1914
1915////////////////////////////////////////////////////////////////////////////////////////////////////
1916                // Disposition-Notification-To
1917                if ($return_receipt)
1918                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1919////////////////////////////////////////////////////////////////////////////////////////////////////
1920
1921                $sent = $mail->Send();
1922
1923                if(!$sent)
1924                {
1925                        return $this->parse_error($mail->ErrorInfo);
1926                }
1927                else
1928                {
1929            if ($signed && !$params['smime'])
1930                        {
1931                                return $sent;
1932                        }
1933                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
1934                        {
1935                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
1936                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
1937                                $now = date("d/m/y H:i:s");
1938                                $addrs = $toaddress.$ccaddress.$ccoaddress;
1939                                $sent = trim($sent);
1940                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
1941                        }
1942                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
1943                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
1944                                $contacts = new dynamic_contacts();
1945                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
1946                                return array("success" => true, "new_contacts" => $new_contacts);
1947                        }
1948                        return array("success" => true);
1949                }
1950        }
1951
1952    function add_recipients_cert($full_address)
1953        {
1954                $result = "";
1955                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
1956                foreach ($parse_address as $val)
1957                {
1958                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
1959                        if ($val->mailbox == "INVALID_ADDRESS")
1960                                continue;
1961                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
1962                                continue;
1963                        if (empty($val->personal))
1964                                $result .= $val->mailbox."@".$val->host . ",";
1965                        else
1966                                $result .= $val->mailbox."@".$val->host . ",";
1967                }
1968
1969                return substr($result,0,-1);
1970        }
1971
1972        function add_recipients($recipient_type, $full_address, $mail)
1973        {
1974                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
1975                foreach ($parse_address as $val)
1976                {
1977                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
1978                        if ($val->mailbox == "INVALID_ADDRESS")
1979                                continue;
1980
1981                        if (empty($val->personal))
1982                        {
1983                                switch($recipient_type)
1984                                {
1985                                        case "to":
1986                                                $mail->AddAddress($val->mailbox."@".$val->host);
1987                                                break;
1988                                        case "cc":
1989                                                $mail->AddCC($val->mailbox."@".$val->host);
1990                                                break;
1991                                        case "cco":
1992                                                $mail->AddBCC($val->mailbox."@".$val->host);
1993                                                break;
1994                                }
1995                        }
1996                        else
1997                        {
1998                                switch($recipient_type)
1999                                {
2000                                        case "to":
2001                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2002                                                break;
2003                                        case "cc":
2004                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2005                                                break;
2006                                        case "cco":
2007                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2008                                                break;
2009                                }
2010                        }
2011                }
2012                return true;
2013        }
2014
2015        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2016        {
2017                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
2018                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
2019                if($encoding == 'base64')
2020                        # The function imap_base64 adds a new line
2021                        # at ASCII text, with CRLF line terminators.
2022                        # So is being exchanged for base64_decode.
2023                        #
2024                        #$fileContent = imap_base64($fileContent);
2025                        $fileContent = base64_decode($fileContent);
2026                else if($encoding == 'quoted-printable')
2027                        $fileContent = quoted_printable_decode($fileContent);
2028                return $fileContent;
2029        }
2030
2031        function del_last_caracter($string)
2032        {
2033                $string = substr($string,0,(strlen($string) - 1));
2034                return $string;
2035        }
2036
2037        function del_last_two_caracters($string)
2038        {
2039                $string = substr($string,0,(strlen($string) - 2));
2040                return $string;
2041        }
2042
2043        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
2044        {
2045                if ($sort_box_type != "SORTFROM"){
2046                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2047                        foreach($imapsort as $iuid)
2048                                $sort[$iuid] = "";
2049                        $slice_array = true;
2050                }
2051                else
2052                {
2053                        $sort = array();
2054                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2055                        $num_msgs = imap_num_msg($this->mbox);
2056                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
2057                        $slice_array = true;
2058
2059                        for ($i=$num_msgs; $i>0; $i--)
2060                        {
2061                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2062                                        break;
2063                                $iuid = @imap_uid($this->mbox,$i);
2064                                $header = $this->get_header($iuid);
2065                                // List UNSEEN messages.
2066                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2067                                        continue;
2068                                }
2069                                // List SEEN messages.
2070                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2071                                        continue;
2072                                }
2073                                // List ANSWERED messages.
2074                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2075                                        continue;
2076                                }
2077                                // List FLAGGED messages.
2078                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2079                                        continue;
2080                                }
2081
2082                                if($sort_box_type=='SORTFROM') {
2083                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
2084                                                $from = $header->to;
2085                                        else
2086                                                $from = $header->from;
2087
2088                                        $tmp = imap_mime_header_decode($from[0]->personal);
2089
2090                                        if ($tmp[0]->text != "")
2091                                                $sort[$iuid] = $tmp[0]->text;
2092                                        else
2093                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2094                                }
2095                                else if($sort_box_type=='SORTSUBJECT') {
2096                                        $sort[$iuid] = $header->subject;
2097                                }
2098                                else if($sort_box_type=='SORTSIZE') {
2099                                        $sort[$iuid] = $header->Size;
2100                                }
2101                                else {
2102                                        $sort[$iuid] = $header->udate;
2103                                }
2104
2105                        }
2106                        natcasesort($sort);
2107
2108                        if ($sort_box_reverse)
2109                                $sort = array_reverse($sort,true);
2110                }
2111
2112                if(!is_array($sort))
2113                        $sort = array();
2114
2115                if ($slice_array)
2116                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
2117
2118
2119                return $sort;
2120
2121        }
2122
2123
2124        function move_search_messages($params){
2125                $params['selected_messages'] = urldecode($params['selected_messages']);
2126                $params['new_folder'] = urldecode($params['new_folder']);
2127                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2128                $sel_msgs = explode(",", $params['selected_messages']);
2129                @reset($sel_msgs);
2130                $sorted_msgs = array();
2131                foreach($sel_msgs as $idx => $sel_msg) {
2132                        $sel_msg = explode(";", $sel_msg);
2133                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2134                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
2135                         }
2136                         else {
2137                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2138                         }
2139                }
2140                @ksort($sorted_msgs);
2141                $last_return = false;
2142                foreach($sorted_msgs as $folder => $msgs_number) {
2143                        $params['msgs_number'] = $msgs_number;
2144                        $params['folder'] = $folder;
2145                        if($params['new_folder'] && $folder != $params['new_folder']){
2146                                $last_return = $this -> move_messages($params);
2147                        }
2148                        elseif(!$params['new_folder'] || $params['delete'] ){
2149                                $last_return = $this -> delete_msgs($params);
2150                                $last_return['deleted'] = true;
2151                        }
2152                }
2153                return $last_return;
2154        }
2155
2156        function move_messages($params)
2157        {
2158                $folder = $params['folder'];
2159                $mbox_stream = $this->open_mbox($folder);
2160                $newmailbox = ($params['new_folder']);
2161                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
2162                $new_folder_name = $params['new_folder_name'];
2163                $msgs_number = $params['msgs_number'];
2164                $return = array('msgs_number' => $msgs_number,
2165                                                'folder' => $folder,
2166                                                'new_folder_name' => $new_folder_name,
2167                                                'border_ID' => $params['border_ID'],
2168                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
2169
2170                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2171        if (substr($folder,0,4) == 'user'){
2172                $acl = $this->getacltouser($folder);
2173                /*
2174                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2175                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2176                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2177                 *   w - write (STORE flags other than SEEN and DELETED)
2178                 *   i - insert (perform APPEND, COPY into mailbox)
2179                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2180                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2181                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2182                 *   a - administer (perform SETACL)
2183                        */
2184                        if (strpos($acl, "d") === false){
2185                                $return['status'] = false;
2186                                return $return;
2187                        }
2188        }
2189        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
2190        if (substr($new_folder_name,0,4) == 'user'){
2191                $this->ldap = new ldap_functions();
2192                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
2193                        $return['new_folder_name'] = array_pop($tmp_folder_name);
2194                        if (is_numeric($return['new_folder_name']))
2195                                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2196                                        $return['new_folder_name'] = $cn;
2197        }
2198
2199                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
2200                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
2201                {
2202                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2203                        // Fix problem in unserialize function JS.
2204                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2205                }
2206
2207                $mbox_stream = $this->open_mbox($folder);
2208                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2209                        imap_expunge($mbox_stream);
2210                        if($mbox_stream)
2211                                imap_close($mbox_stream);
2212                        return $return;
2213                }else {
2214                        if(strstr(imap_last_error(),'Over quota')) {
2215                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
2216                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
2217                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2218                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2219                                $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()))));
2220                                if(!$mbox)
2221                                        return imap_last_error();
2222                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
2223                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
2224                                        if($mbox_stream)
2225                                                imap_close($mbox_stream);
2226                                        if($mbox)
2227                                                imap_close($mbox);
2228                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
2229                                }
2230                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2231                                        imap_expunge($mbox_stream);
2232                                        if($mbox_stream)
2233                                                imap_close($mbox_stream);
2234                                        // return to original quota limit.
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 $return;
2241                                }
2242                                else {
2243                                        if($mbox_stream)
2244                                                imap_close($mbox_stream);
2245                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2246                                                if($mbox)
2247                                                        imap_close($mbox);
2248                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2249                                        }
2250                                        return imap_last_error();
2251                                }
2252
2253                        }
2254                        else {
2255                                if($mbox_stream)
2256                                        imap_close($mbox_stream);
2257                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
2258                        }
2259                }
2260        }
2261
2262        function save_msg($params)
2263        {
2264
2265                include_once("class.phpmailer.php");
2266                $mail = new PHPMailer();
2267                include_once("class.db_functions.inc.php");
2268                $toaddress = $params['input_to'];
2269                $ccaddress = $params['input_cc'];
2270                $subject = $params['input_subject'];
2271                $msg_uid = $params['msg_id'];
2272                $body = $params['body'];
2273                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
2274                $body = preg_replace("/\n/"," ",$body);
2275                $body = preg_replace("/\r/","",$body);
2276                $forwarding_attachments = $params['forwarding_attachments'];
2277                $attachments = $params['FILES'];
2278                $return_files = $params['FILES'];
2279
2280                $folder = $params['folder'];
2281                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2282                // Fix problem with cyrus delimiter changes.
2283                // Dots in names: enabled/disabled.
2284                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2285                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2286                // End Fix.
2287
2288                $mail->SaveMessageInFolder = $folder;
2289                $mail->SMTPDebug = false;
2290
2291                $mail->IsSMTP();
2292                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2293                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2294                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2295                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2296
2297                $mail->Sender = $mail->From;
2298                $mail->SenderName = $mail->FromName;
2299                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2300                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
2301
2302                $this->add_recipients("to", $toaddress, &$mail);
2303                $this->add_recipients("cc", $ccaddress, &$mail);
2304                $mail->Subject = $subject;
2305                $mail->IsHTML(true);
2306                $mail->Body = $body;
2307
2308                //      Build CID for embedded Images!!!
2309                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2310                $cid_imgs = '';
2311                $name_cid_files = array();
2312                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2313                $cid_array = array();
2314                foreach($cid_imgs[6] as $j => $val){
2315                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2316                        {
2317                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2318                        }
2319                        $cid = $cid_array[$cid_imgs[4][$j].$val];
2320                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2321
2322                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
2323                                {
2324                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2325                                        //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
2326                                        $fileName = "image_".($j).".jpg";
2327                                        $fileCode = "base64";
2328                                        $fileType = "image/jpg";
2329                                        $file_attached[0] = $cid_imgs[2][$j];
2330                                        $file_attached[1] = $cid_imgs[4][$j];
2331                                        $file_attached[2] = $fileName;
2332                                        $file_attached[3] = $cid_imgs[6][$j];
2333                                        $file_attached[4] = 'base64';
2334                                        $file_attached[5] = strlen($fileContent); //Size of file
2335                                        $return_forward[] = $file_attached;
2336                                }
2337                                else
2338                                {
2339                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2340                                        $file_description = unserialize(rawurldecode($attach_img));
2341                                        foreach($file_description as $i => $descriptor){
2342                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2343                                        }
2344                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2345                                        $fileName = $file_description[2];
2346                                        $fileCode = $file_description[4];
2347                                        $fileType = $this->get_file_type($file_description[2]);
2348                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2349                                        if (!empty($file_description))
2350                                        {
2351                                                $file_description[5] = strlen($fileContent); //Size of file
2352                                                $return_forward[] = $file_description;
2353                                        }
2354                                }
2355                                $tempDir = ini_get("session.save_path");
2356                                $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";
2357                                $f = fopen($tempDir.'/'.$file,"w");
2358                                fputs($f,$fileContent);
2359                                fclose($f);
2360                                if ($fileContent)
2361                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2362                                //else
2363                                //      return "Error loading image attachment content";
2364
2365                }
2366
2367        //      Build Forwarding Attachments!!!
2368                if (count($forwarding_attachments) > 0)
2369                {
2370                        foreach($forwarding_attachments as $forwarding_attachment)
2371                        {
2372                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2373                                $tmp = array_values($file_description);
2374                                foreach($file_description as $i => $descriptor){
2375                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2376                                }
2377                                $file_description = $tmp;
2378
2379                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2380                                $fileName = $file_description[2];
2381
2382                                $file_description[5] = strlen($fileContent); //Size of file
2383                                $return_forward[] = $file_description;
2384
2385                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2386                        }
2387                }
2388
2389                if ((count($return_forward) > 0) && (count($return_files) > 0))
2390                        $return_files = array_merge_recursive($return_forward,$return_files);
2391                else
2392                        if (count($return_files) < 1)
2393                                $return_files = $return_forward;
2394
2395                //      Build Uploading Attachments!!!
2396                $sizeof_attachments = count($attachments);
2397                if ($sizeof_attachments)
2398                        foreach ($attachments as $numb => $attach){
2399                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2400                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2401                                        switch ($image_type)
2402                                        {
2403                                        // Do not corrupt animated gif
2404                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
2405                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2406                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2407                                        case 6:
2408                                                require_once("gd_functions.php");
2409                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2410                                        default:
2411                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2412                                                break;
2413                                        }
2414                                        header('Content-type: image/jpeg');
2415                                        $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
2416                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2417                                        if ($width < $max_resolution && $height < $max_resolution){
2418                                                $new_width = $width;
2419                                                $new_height = $height;
2420                                        }
2421                                        else if ($width > $max_resolution){
2422                                                $new_width = $max_resolution;
2423                                                $new_height = $height*($new_width/$width);
2424                                        }
2425                                        else {
2426                                                $new_height = $max_resolution;
2427                                                $new_width = $width*($new_height/$height);
2428                                        }
2429                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2430                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2431                                        $tmpDir = ini_get("session.save_path");
2432                                        $_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
2433                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2434                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2435                                }
2436                                else
2437                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2438                                // optional name
2439                                }
2440
2441
2442
2443
2444                if(!empty($mail->AltBody))
2445            $mail->ContentType = "multipart/alternative";
2446
2447                $mail->error_count = 0; // reset errors
2448                $mail->SetMessageType();
2449                $header = $mail->CreateHeader();
2450                $body = $mail->CreateBody();
2451
2452                $mbox_stream = $this->open_mbox($folder);
2453                $new_header = str_replace("\n", "\r\n", $header);
2454                $new_body = str_replace("\n", "\r\n", $body);
2455                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2456                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2457                $return['msg_no'] = $status->uidnext - 1;
2458                $return['folder_id'] = $folder;
2459
2460                if($mbox_stream)
2461                        imap_close($mbox_stream);
2462                if (is_array($return_files))
2463                        foreach ($return_files as $index => $_attachment) {
2464                                if (array_key_exists("name",$_attachment)){
2465                                unset($return_files[$index]);
2466                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2467                        }
2468                        else
2469                        {
2470                                unset($return_files[$index]);
2471                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2472                        }
2473                }
2474
2475                $return['files'] = serialize($return_files);
2476                $return["subject"] = $subject;
2477
2478                if (!$return['append'])
2479                        $return['append'] = imap_last_error();
2480
2481                return $return;
2482        }
2483
2484        function set_messages_flag($params)
2485        {
2486                $folder = $params['folder'];
2487                $msgs_to_set = $params['msgs_to_set'];
2488                $flag = $params['flag'];
2489                $return = array();
2490                $return["msgs_to_set"] = $msgs_to_set;
2491                $return["flag"] = $flag;
2492
2493                if(!$this->mbox && !is_resource($this->mbox))
2494                        $this->mbox = $this->open_mbox($folder);
2495
2496                if ($flag == "unseen")
2497                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2498                elseif ($flag == "seen")
2499                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2500                elseif ($flag == "answered"){
2501                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2502                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2503                }
2504                elseif ($flag == "forwarded")
2505                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2506                elseif ($flag == "flagged")
2507                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2508                elseif ($flag == "unflagged") {
2509                        $flag_importance = false;
2510                        $msgs_number = explode(",",$msgs_to_set);
2511                        $unflagged_msgs = "";
2512                        foreach($msgs_number as $msg_number) {
2513                                preg_match('/importance *: *(.*)\r/i',
2514                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2515                                        ,$importance);
2516                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2517                                        $flag_importance=true;
2518                                }
2519                                else {
2520                                        $unflagged_msgs.=$msg_number.",";
2521                                }
2522                        }
2523
2524                        if($unflagged_msgs!="") {
2525                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2526                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2527                        }
2528                        else {
2529                                $return["msgs_unflageds"] = false;
2530                        }
2531
2532                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2533                                $return["status"] = false;
2534                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2535                        }
2536                        else {
2537                                $return["status"] = true;
2538                        }
2539                }
2540
2541                if($this->mbox && is_resource($this->mbox))
2542                        imap_close($this->mbox);
2543                return $return;
2544        }
2545
2546        function get_file_type($file_name)
2547        {
2548                $file_name = strtolower($file_name);
2549                $strFileType = strrev(substr(strrev($file_name),0,4));
2550                if ($strFileType == ".asf")
2551                        return "video/x-ms-asf";
2552                if ($strFileType == ".avi")
2553                        return "video/avi";
2554                if ($strFileType == ".doc")
2555                        return "application/msword";
2556                if ($strFileType == ".zip")
2557                        return "application/zip";
2558                if ($strFileType == ".xls")
2559                        return "application/vnd.ms-excel";
2560                if ($strFileType == ".gif")
2561                        return "image/gif";
2562                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2563                        return "image/jpeg";
2564                if ($strFileType == ".png")
2565                        return "image/png";
2566                if ($strFileType == ".wav")
2567                        return "audio/wav";
2568                if ($strFileType == ".mp3")
2569                        return "audio/mpeg3";
2570                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2571                        return "video/mpeg";
2572                if ($strFileType == ".rtf")
2573                        return "application/rtf";
2574                if ($strFileType == ".htm" || $strFileType == "html")
2575                        return "text/html";
2576                if ($strFileType == ".xml")
2577                        return "text/xml";
2578                if ($strFileType == ".xsl")
2579                        return "text/xsl";
2580                if ($strFileType == ".css")
2581                        return "text/css";
2582                if ($strFileType == ".php")
2583                        return "text/php";
2584                if ($strFileType == ".asp")
2585                        return "text/asp";
2586                if ($strFileType == ".pdf")
2587                        return "application/pdf";
2588                if ($strFileType == ".txt")
2589                        return "text/plain";
2590                if ($strFileType == ".wmv")
2591                        return "video/x-ms-wmv";
2592                if ($strFileType == ".sxc")
2593                        return "application/vnd.sun.xml.calc";
2594                if ($strFileType == ".stc")
2595                        return "application/vnd.sun.xml.calc.template";
2596                if ($strFileType == ".sxd")
2597                        return "application/vnd.sun.xml.draw";
2598                if ($strFileType == ".std")
2599                        return "application/vnd.sun.xml.draw.template";
2600                if ($strFileType == ".sxi")
2601                        return "application/vnd.sun.xml.impress";
2602                if ($strFileType == ".sti")
2603                        return "application/vnd.sun.xml.impress.template";
2604                if ($strFileType == ".sxm")
2605                        return "application/vnd.sun.xml.math";
2606                if ($strFileType == ".sxw")
2607                        return "application/vnd.sun.xml.writer";
2608                if ($strFileType == ".sxq")
2609                        return "application/vnd.sun.xml.writer.global";
2610                if ($strFileType == ".stw")
2611                        return "application/vnd.sun.xml.writer.template";
2612
2613
2614                return "application/octet-stream";
2615        }
2616
2617        function htmlspecialchars_encode($str)
2618        {
2619                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
2620        }
2621        function htmlspecialchars_decode($str)
2622        {
2623                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
2624        }
2625
2626        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2627        {
2628                if(!$this->mbox || !is_resource($this->mbox))
2629                        $this->mbox = $this->open_mbox($folder);
2630
2631                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2632        }
2633
2634        function get_info_next_msg($params)
2635        {
2636                $msg_number = $params['msg_number'];
2637                $folder = $params['msg_folder'];
2638                $sort_box_type = $params['sort_box_type'];
2639                $sort_box_reverse = $params['sort_box_reverse'];
2640                $reuse_border = $params['reuse_border'];
2641                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2642                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2643
2644                $success = false;
2645                if (is_array($sort_array_msg))
2646                {
2647                        foreach ($sort_array_msg as $i => $value){
2648                                if ($value == $msg_number)
2649                                {
2650                                        $success = true;
2651                                        break;
2652                                }
2653                        }
2654                }
2655
2656                if (! $success || $i >= sizeof($sort_array_msg)-1)
2657                {
2658                        $params['status'] = 'false';
2659                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2660                        return $params;
2661                }
2662
2663                $params = array();
2664                $params['msg_number'] = $sort_array_msg[($i+1)];
2665                $params['msg_folder'] = $folder;
2666
2667                $return = $this->get_info_msg($params);
2668                $return["reuse_border"] = $reuse_border;
2669                return $return;
2670        }
2671
2672        function get_info_previous_msg($params)
2673        {
2674                $msg_number = $params['msgs_number'];
2675                $folder = $params['folder'];
2676                $sort_box_type = $params['sort_box_type'];
2677                $sort_box_reverse = $params['sort_box_reverse'];
2678                $reuse_border = $params['reuse_border'];
2679                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2680                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2681
2682                $success = false;
2683                if (is_array($sort_array_msg))
2684                {
2685                        foreach ($sort_array_msg as $i => $value){
2686                                if ($value == $msg_number)
2687                                {
2688                                        $success = true;
2689                                        break;
2690                                }
2691                        }
2692                }
2693                if (! $success || $i == 0)
2694                {
2695                        $params['status'] = 'false';
2696                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2697                        return $params;
2698                }
2699
2700                $params = array();
2701                $params['msg_number'] = $sort_array_msg[($i-1)];
2702                $params['msg_folder'] = $folder;
2703
2704                $return = $this->get_info_msg($params);
2705                $return["reuse_border"] = $reuse_border;
2706                return $return;
2707        }
2708
2709        // This function updates the values: quota, paging and new messages menu.
2710        function get_menu_values($params){
2711                $return_array = array();
2712                $return_array = $this->get_quota($params);
2713
2714                $mbox_stream = $this->open_mbox($params['folder']);
2715                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
2716                if($mbox_stream)
2717                        imap_close($mbox_stream);
2718
2719                return $return_array;
2720        }
2721
2722        function get_quota($params){
2723                // folder_id = user/{uid} for shared folders
2724                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
2725                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
2726                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
2727                }
2728                // folder_id = INBOX for inbox folders
2729                else
2730                        $folder_id = "INBOX";
2731
2732                if(!$this->mbox || !is_resource($this->mbox))
2733                        $this->mbox = $this->open_mbox();
2734
2735                $quota = imap_get_quotaroot($this->mbox, $folder_id);
2736                if($this->mbox && is_resource($this->mbox))
2737                        imap_close($this->mbox);
2738
2739                if (!$quota){
2740                        return array(
2741                                'quota_percent' => 0,
2742                                'quota_used' => 0,
2743                                'quota_limit' =>  0
2744                        );
2745                }
2746
2747                if(count($quota) && $quota['limit']) {
2748                        $quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
2749                        $quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
2750                        if($quota_used >= $quota_limit)
2751                        {
2752                                $quotaPercent = 100;
2753                        }
2754                        else
2755                        {
2756                        $quotaPercent = ($quota_used / $quota_limit)*100;
2757                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
2758                        }
2759                        return array(
2760                                'quota_percent' => floor($quotaPercent),
2761                                'quota_used' => floor($quota_used),
2762                                'quota_limit' =>  floor($quota_limit)
2763                        );
2764                }
2765                else
2766                        return array();
2767        }
2768
2769        function send_notification($params){
2770                require_once("class.phpmailer.php");
2771                $mail = new PHPMailer();
2772
2773                $toaddress = $params['notificationto'];
2774
2775                $subject = 'Confirmação de leitura: ' . $params['subject'];
2776                $body = 'Sua mensagem: ' . $params['subject'] . '<br>';
2777                $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");
2778                $mail->SMTPDebug = false;
2779                $mail->IsSMTP();
2780                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2781                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2782                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2783                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2784                $mail->AddAddress($toaddress);
2785                $mail->Subject = $this->htmlspecialchars_decode($subject);
2786
2787                $mail->IsHTML(true);
2788                $mail->Body = $body;
2789
2790                if(!$mail->Send()){
2791                        return $mail->ErrorInfo;
2792                }
2793                else
2794                        return true;
2795        }
2796
2797        function empty_trash()
2798        {
2799                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
2800                $mbox_stream = $this->open_mbox($folder);
2801                $return = imap_delete($mbox_stream,'1:*');
2802                if($mbox_stream)
2803                        imap_close($mbox_stream, CL_EXPUNGE);
2804                return $return;
2805        }
2806
2807        function search($params)
2808        {
2809                include("class.imap_attachment.inc.php");
2810                $imap_attachment = new imap_attachment();
2811                $criteria = $params['criteria'];
2812                $return = array();
2813                $folders = $this->get_folders_list();
2814
2815                $j = 0;
2816                foreach($folders as $folder)
2817                {
2818                        $mbox_stream = $this->open_mbox($folder);
2819                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
2820
2821                        if ($messages == '')
2822                                continue;
2823
2824                        $i = 0;
2825                        $return[$j] = array();
2826                        $return[$j]['folder_name'] = $folder['name'];
2827
2828                        foreach($messages as $msg_number)
2829                        {
2830                                $header = $this->get_header($msg_number);
2831                                if (!is_object($header))
2832                                        return false;
2833
2834                                $return[$j][$i]['msg_folder']   = $folder['name'];
2835                                $return[$j][$i]['msg_number']   = $msg_number;
2836                                $return[$j][$i]['Recent']               = $header->Recent;
2837                                $return[$j][$i]['Unseen']               = $header->Unseen;
2838                                $return[$j][$i]['Answered']     = $header->Answered;
2839                                $return[$j][$i]['Deleted']              = $header->Deleted;
2840                                $return[$j][$i]['Draft']                = $header->Draft;
2841                                $return[$j][$i]['Flagged']              = $header->Flagged;
2842
2843                                $date_msg = gmdate("d/m/Y",$header->udate);
2844                                if (gmdate("d/m/Y") == $date_msg)
2845                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
2846                                else
2847                                        $return[$j][$i]['udate'] = $date_msg;
2848
2849                                $fromaddress = imap_mime_header_decode($header->fromaddress);
2850                                $return[$j][$i]['fromaddress'] = '';
2851                                foreach ($fromaddress as $tmp)
2852                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
2853
2854                                $from = $header->from;
2855                                $return[$j][$i]['from'] = array();
2856                                $tmp = imap_mime_header_decode($from[0]->personal);
2857                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
2858                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
2859                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
2860
2861                                $to = $header->to;
2862                                $return[$j][$i]['to'] = array();
2863                                $tmp = imap_mime_header_decode($to[0]->personal);
2864                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
2865                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
2866                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
2867
2868                                $subject = imap_mime_header_decode($header->fetchsubject);
2869                                $return[$j][$i]['subject'] = '';
2870                                foreach ($subject as $tmp)
2871                                        $return[$j][$i]['subject'] .= $tmp->text;
2872
2873                                $return[$j][$i]['Size'] = $header->Size;
2874                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
2875
2876                                $return[$j][$i]['attachment'] = array();
2877                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
2878
2879                                $i++;
2880                        }
2881                        $j++;
2882                        if($mbox_stream)
2883                                imap_close($mbox_stream);
2884                }
2885
2886                return $return;
2887        }
2888
2889        function delete_and_show_previous_message($params)
2890        {
2891                $return = $this->get_info_previous_msg($params);
2892
2893                $params_tmp1 = array();
2894                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
2895                $params_tmp1['folder'] = $params['msg_folder'];
2896                $return_tmp1 = $this->delete_msg($params_tmp1);
2897
2898                $return['msg_number_deleted'] = $return_tmp1;
2899
2900                return $return;
2901        }
2902
2903
2904        function automatic_trash_cleanness($params)
2905        {
2906                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
2907                $criteria =  'BEFORE "'.$before_date.'"';
2908                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
2909                $messages = imap_search($mbox_stream, $criteria, SE_UID);
2910                if (is_array($messages)){
2911                        foreach ($messages as $msg_number){
2912                                imap_delete($mbox_stream, $msg_number, FT_UID);
2913                        }
2914                }
2915                if($mbox_stream)
2916                        imap_close($mbox_stream, CL_EXPUNGE);
2917                return $messages;
2918        }
2919//      Fix the search problem with special characters!!!!
2920        function remove_accents($string) {
2921                return strtr($string,
2922                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
2923                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
2924        }
2925
2926        function search_msg($params = ''){
2927                $retorno = "";
2928                $mbox_stream = "";
2929                if(strpos($params['condition'],"#")===false) { //local messages
2930                        $search=false;
2931                }
2932                else {
2933                        $search = explode(",",$params['condition']);
2934                }
2935
2936                if($search){
2937                        $search_criteria = '';
2938                        foreach($search as $tmp)
2939                        {
2940                                $tmp1 = explode("##",$tmp);
2941                                $name_box = $tmp1[0];
2942                                unset($filter);
2943                                foreach($tmp1 as $index => $criteria)
2944                                {
2945                                        if ($index != 0 && strlen($criteria) != 0)
2946                                        {
2947                                                $filter_array = explode("<=>",rawurldecode($criteria));
2948                                                $filter .= " ".$filter_array[0];
2949                                                $filter .= '"'.$filter_array[1].'"';
2950                                        }
2951                                }
2952                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
2953                                $filter = $this->remove_accents($filter);
2954                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
2955                                $folder_name = explode($this->imap_delimiter,$name_box);
2956                                if (is_numeric($folder_name[1])) {
2957                                        $this->ldap = new ldap_functions();
2958                                        if ($cn = $this->ldap->uid2cn($folder_name[1])) {
2959                                                $folder_name[1] = $cn;
2960                                        }
2961                                }
2962                                $folder_name = implode($this->imap_delimiter,$folder_name);
2963
2964                                if(!is_resource($mbox_stream))
2965                                        $mbox_stream = $this->open_mbox($name_box);
2966                                else
2967                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
2968
2969                                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search
2970
2971                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
2972                                        foreach($all_criterias as $criteria_fixed)
2973                                        {
2974                                                $_filter = $criteria_fixed . substr($filter,4);
2975
2976                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
2977
2978                                                if($search_criteria && count($search_criteria) < 50)
2979                                                {
2980                                                        foreach($search_criteria as $new_search){
2981                                                                $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");
2982                                                                if(!@strstr($retorno,$m_token))
2983                                                                        $retorno .= $m_token;
2984                                                        }
2985                                                }
2986                                                else if(count($search_criteria) >= 50)
2987                                                        return "many results";
2988                                        }
2989                                }
2990                                else {
2991                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
2992                                        if( is_array( $search_criteria) )
2993                                        {
2994                                                foreach($search_criteria as $new_search)
2995                                                        $retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
2996                                        }
2997                                }
2998                        }
2999                }
3000                if($mbox_stream)
3001                        imap_close($mbox_stream);
3002
3003                return $retorno ? $retorno : "none";
3004        }
3005
3006        function get_msg($uid_msg,$name_box, $mbox_stream )
3007        {
3008                $header = $this->get_header($uid_msg);
3009                include_once("class.imap_attachment.inc.php");
3010                $imap_attachment = new imap_attachment();
3011                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3012                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3013                $flag = $header->Unseen
3014                        .$header->Recent
3015                        .$header->Flagged
3016                        .$header->Draft
3017                        .$header->Answered
3018                        .$header->Deleted
3019                        .$attachments;
3020
3021
3022                $subject = $this->decode_string($header->fetchsubject);
3023                $from = $header->from[0]->mailbox;
3024                if($header->from[0]->personal != "")
3025                        $from = $header->from[0]->personal;
3026                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size) ."--". $flag;
3027                return $ret_msg;
3028        }
3029
3030        function size_msg($size){
3031                $var = floor($size/1024);
3032                if($var >= 1){
3033                        return $var." kb";
3034                }else{
3035                        return $size ." b";
3036                }
3037        }
3038
3039        function ob_array($the_object)
3040        {
3041           $the_array=array();
3042           if(!is_scalar($the_object))
3043           {
3044               foreach($the_object as $id => $object)
3045               {
3046                   if(is_scalar($object))
3047                   {
3048                       $the_array[$id]=$object;
3049                   }
3050                   else
3051                   {
3052                       $the_array[$id]=$this->ob_array($object);
3053                   }
3054               }
3055               return $the_array;
3056           }
3057           else
3058           {
3059               return $the_object;
3060           }
3061        }
3062
3063        function getacl()
3064        {
3065                $this->ldap = new ldap_functions();
3066
3067                $return = array();
3068                $mbox_stream = $this->open_mbox();
3069                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3070
3071                $i = 0;
3072                foreach ($mbox_acl as $user => $acl)
3073                {
3074                        if ($user != $this->username)
3075                        {
3076                                $return[$i]['uid'] = $user;
3077                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3078                        }
3079                        $i++;
3080                }
3081                return $return;
3082        }
3083
3084        function setacl($params)
3085        {
3086                $old_users = $this->getacl();
3087                if (!count($old_users))
3088                        $old_users = array();
3089
3090                $tmp_array = array();
3091                foreach ($old_users as $index => $user_info)
3092                {
3093                        $tmp_array[$index] = $user_info['uid'];
3094                }
3095                $old_users = $tmp_array;
3096
3097                $users = unserialize($params['users']);
3098                if (!count($users))
3099                        $users = array();
3100
3101                //$add_share = array_diff($users, $old_users);
3102                $remove_share = array_diff($old_users, $users);
3103
3104                $mbox_stream = $this->open_mbox();
3105
3106                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3107                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3108
3109                /*if (count($add_share))
3110                {
3111                        foreach ($add_share as $index=>$uid)
3112                        {
3113                        if (is_array($mailboxes_list))
3114                        {
3115                        foreach ($mailboxes_list as $key => $val)
3116                        {
3117                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3118                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3119                        }
3120                        }
3121                        }
3122                }*/
3123
3124                if (count($remove_share))
3125                {
3126                        foreach ($remove_share as $index=>$uid)
3127                        {
3128                        if (is_array($mailboxes_list))
3129                        {
3130                        foreach ($mailboxes_list as $key => $val)
3131                        {
3132                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3133                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3134                        }
3135                        }
3136                        }
3137                }
3138
3139                return true;
3140        }
3141
3142        function getaclfromuser($params)
3143        {
3144                $useracl = $params['user'];
3145
3146                $return = array();
3147                $return[$useracl] = 'false';
3148                $mbox_stream = $this->open_mbox();
3149                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3150
3151                foreach ($mbox_acl as $user => $acl)
3152                {
3153                        if (($user != $this->username) && ($user == $useracl))
3154                        {
3155                                $return[$user] = $acl;
3156                        }
3157                }
3158                return $return;
3159        }
3160
3161        function getacltouser($user)
3162        {
3163                $return = array();
3164                $mbox_stream = $this->open_mbox();
3165                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3166                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3167                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3168                if(substr($user,0,4) != 'user')
3169                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3170                else
3171                  $mbox_acl = imap_getacl($mbox_stream, $user);
3172                return $mbox_acl[$this->username];
3173        }
3174
3175
3176        function setaclfromuser($params)
3177        {
3178                $user = $params['user'];
3179                $acl = $params['acl'];
3180
3181                $mbox_stream = $this->open_mbox();
3182
3183                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3184                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3185
3186                if (is_array($mailboxes_list))
3187                {
3188                        foreach ($mailboxes_list as $key => $val)
3189                        {
3190                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3191                                $folder = str_replace("&-", "&", $folder);
3192                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3193                                {
3194                                        $return = imap_last_error();
3195                                }
3196                        }
3197                }
3198                if (isset($return))
3199                        return $return;
3200                else
3201                        return true;
3202        }
3203
3204        function download_attachment($msg,$msgno)
3205        {
3206                $array_parts_attachments = array();
3207                $array_parts_attachments['names'] = '';
3208                include_once("class.imap_attachment.inc.php");
3209                $imap_attachment = new imap_attachment();
3210
3211                if (count($msg->fname[$msgno]) > 0)
3212                {
3213                        $i = 0;
3214                        foreach ($msg->fname[$msgno] as $index=>$fname)
3215                        {
3216                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3217                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
3218                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3219                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3220                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3221                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3222                                $i++;
3223                        }
3224                }
3225                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3226                return $array_parts_attachments;
3227        }
3228
3229        function spam($params)
3230        {
3231                $is_spam = $params['spam'];
3232                $folder = $params['folder'];
3233                $mbox_stream = $this->open_mbox($folder);
3234                $msgs_number = explode(',',$params['msgs_number']);
3235
3236                foreach($msgs_number as $msg_number) {
3237                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3238                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3239                        $body = imap_body($mbox_stream, $imap_msg_number);
3240                        $msg = $header . $body;
3241                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3242                        $username = $this->username;
3243                        strtok($email, '@');
3244                        $domain = strtok('@');
3245
3246                        //Encontrar a assinatura do dspam no cabecalho
3247                        $v = explode("\r\n", $header);
3248                        foreach ($v as $linha){
3249                                if (eregi("^Message-ID", $linha)) {
3250                                        $args = explode(" ", $linha);
3251                                        $msg_id = "'$args[1]'";
3252                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
3253                                        $args = explode(" ",$linha);
3254                                        $signature = $args[1];
3255                                }
3256                        }
3257
3258                        // Seleciona qual comando a ser executado
3259                        switch($is_spam){
3260                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
3261                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
3262                        }
3263
3264                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3265                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
3266                        system($cmd);
3267                }
3268                imap_close($mbox_stream);
3269                return false;
3270        }
3271        function get_header($msg_number){
3272                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3273                if (!is_object($header))
3274                        return false;
3275                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
3276                $pdate = date_parse($header->MailDate);
3277                $header->udate +=  $pdate['zone']*(-60);
3278
3279                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3280                        $flag = preg_match('/importance *: *(.*)\r/i',
3281                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3282                                                ,$importance);
3283                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3284                }
3285
3286                return $header;
3287        }
3288
3289//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
3290///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.
3291
3292    function insert_email($source,$folder,$timestamp){
3293        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3294        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
3295        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3296        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
3297        $imap_options = '/notls/novalidate-cert';
3298        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3299        if(imap_last_error())
3300        {
3301            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3302       }
3303        if($timestamp){
3304            $tempDir = ini_get("session.save_path");
3305            $file = $tempDir."imap_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
3306                $f = fopen($file,"w");
3307                fputs($f,base64_encode($source));
3308            fclose($f);
3309            $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);
3310            $return['command']=exec(escapeshellcmd($command));
3311        }else{
3312            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3313        }
3314        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3315        $return['msg_no'] = $status->uidnext - 1;
3316                $return['error'] = imap_last_error();
3317        if($mbox_stream)
3318                        imap_close($mbox_stream);
3319        return $return;
3320
3321    }
3322
3323    function show_decript($params){
3324        $source = $params['source'];
3325        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3326        $source = str_replace(" ", "+", $source,$i);
3327
3328        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3329            if(!$source = base64_decode($source,true))
3330                return "error ".$source."Espaços ".$i;
3331
3332        }
3333        else {
3334            if(!$source = base64_decode($source))
3335                return "error ".$source."Espaços ".$i;
3336        }
3337
3338        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3339
3340                $get['msg_number'] = $insert['msg_no'];
3341                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
3342                $return = $this->get_info_msg($get);
3343                $get['msg_number'] = $params['ID'];
3344                $get['msg_folder'] = $params['folder'];
3345                $tmp = $this->get_info_msg($get);
3346                if(!$tmp['status_get_msg_info'])
3347                {
3348                        $return['msg_day']=$tmp['msg_day'];
3349                        $return['msg_hour']=$tmp['msg_hour'];
3350                        $return['fulldate']=$tmp['fulldate'];
3351                        $return['smalldate']=$tmp['smalldate'];
3352                }
3353                else
3354                {
3355                        $return['msg_day']='';
3356                        $return['msg_hour']='';
3357                        $return['fulldate']='';
3358                        $return['smalldate']='';
3359                }
3360        $return['msg_no'] =$insert['msg_no'];
3361        $return['error'] = $insert['error'];
3362        $return['folder'] = $params['folder'];
3363        //$return['acls'] = $insert['acls'];
3364        $return['original_ID'] =  $params['ID'];
3365
3366        return $return;
3367
3368    }
3369
3370//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
3371//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
3372
3373    function treat_base64_from_post($source){
3374            $offset = 0;
3375            do
3376            {
3377                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
3378                    {
3379                            $inicio = strpos($source, "\n\r", $inicio);
3380                            $fim = strpos($source, '--', $inicio);
3381                            if(!$fim)
3382                                    $fim = strpos($source,"\n\r", $inicio);
3383                            $length = $fim-$inicio;
3384                            $parte = substr( $source,$inicio,$length-1);
3385                            $parte = str_replace(" ", "+", $parte);
3386                            $source = substr_replace($source, $parte, $inicio, $length-1);
3387                    }
3388                    if($offset > $inicio)
3389                    $offset=FALSE;
3390                    else
3391                    $offset = $inicio;
3392            }
3393            while($offset);
3394            return $source;
3395    }
3396
3397//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.
3398
3399    function unarchive_mail($params)
3400    {
3401        $dest_folder = $params['folder'];
3402        $sources = explode("#@#@#@",$params['source']);
3403        $timestamps = explode("#@#@#@",$params['timestamp']);
3404        foreach($sources as $index=>$src) {
3405                        if($src!=""){
3406                                $source = $this->treat_base64_from_post($src);
3407                                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index]);
3408                        }
3409                }
3410        return $insert;
3411    }
3412
3413    function download_all_local_attachments($params)
3414    {
3415        $source = $params['source'];
3416        $source = $this->treat_base64_from_post($source);
3417        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3418        $exporteml = new ExportEml();
3419        $params['num_msg']=$insert['msg_no'];
3420        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
3421        return $exporteml->download_all_attachments($params);
3422    }
3423}
3424?>
Note: See TracBrowser for help on using the repository browser.