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

Revision 2759, 125.6 KB checked in by rodsouza, 14 years ago (diff)

Ticket #405 - Corrige o problema que acontece ao encaminhar o email

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