source: branches/2.0/expressoMail1_2/inc/class.imap_functions.inc.php @ 2768

Revision 2768, 126.0 KB checked in by niltonneto, 14 years ago (diff)

Ticket #1068 - Corrigido problema na visualização de mensagem 'message/rfc822'.

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