source: trunk/expressoMail1_2/inc/class.imap_functions.inc.php @ 1247

Revision 1247, 122.8 KB checked in by amuller, 15 years ago (diff)

Ticket #000 - Defazendo commit errado para refazer o certo em seguida

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