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

Revision 2103, 127.1 KB checked in by niltonneto, 14 years ago (diff)

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