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

Revision 3676, 126.7 KB checked in by niltonneto, 13 years ago (diff)

Ticket #785 - Corrigido problema da navegação anterior/próximo no resultado da busca.

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