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

Revision 2957, 126.7 KB checked in by niltonneto, 14 years ago (diff)

Ticket #1111 - Correção de problema ao responder, encaminhar e imprimir email text/plain.

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