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

Revision 1246, 122.8 KB checked in by fpcorrea, 15 years ago (diff)

Ticket #573 - Importação de mensagens é limitado pelo tamanho máximo de anexos

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2
3include_once("class.functions.inc.php");
4include_once("class.ldap_functions.inc.php");
5include_once("class.exporteml.inc.php");
6
7class imap_functions
8{
9        var $public_functions = array
10        (       
11                'get_range_msgs'                                => True,
12                'get_info_msg'                                  => True,
13                'get_info_msgs'                                 => True,
14                'get_folders_list'                              => True,
15                'import_msgs'                                   => True
16        );
17
18        var $ldap;
19        var $mbox;
20        var $imap_port;
21        var $has_cid;
22        var $imap_options = '';
23        var $functions;
24        var $foldersLimit;
25
26        function imap_functions (){
27                $this->foldersLimit = 200; //Limit of folders (mailboxes) user can see
28                $this->username           = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
29                $this->password           = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
30                $this->imap_server        = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
31                $this->imap_port          = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
32                $this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
33                $this->functions          = new functions();           
34                $this->has_cid = false;
35               
36                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
37                {
38                        $this->imap_options = '/tls/novalidate-cert';
39                }
40                else
41                {
42                        $this->imap_options = '/notls/novalidate-cert';
43                }
44        }
45        // BEGIN of functions.
46        function open_mbox($folder = False)
47        {
48                if (is_resource($this->mbox))
49                        return $this->mbox;
50                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
51                $this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
52                return $this->mbox;
53         }
54
55        function parse_error($error){
56                // This error is returned from Imap.
57                if(strstr($error,'Connection refused')) {
58                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
59                }
60                // This error is returned from Postfix.
61                elseif(strstr($error,'message file too big')) {
62                        return str_replace("%1", $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']."M",$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        /**
214        * Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
215        * com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
216        */
217/**
218        * Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
219        * com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
220        */
221        function import_msgs($params) {
222                if(!$this->mbox)
223                        $this->mbox = $this->open_mbox();
224
225                if( preg_match('/local_/',$params["folder"]) )
226                {
227
228                        $tmp_box = mb_convert_encoding('INBOX/Lixeira/tmpMoveToLocal', "UTF7-IMAP", "UTF-8");
229                        if ( ! imap_createmailbox( $this -> mbox,"{".$this -> imap_server."}$tmp_box" ) )
230                                return $this->functions->getLang( 'Import to Local : fail...' );
231                        imap_reopen($this->mbox, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$tmp_box);
232                        $params["folder"] = $tmp_box;
233                }
234                $errors = array();
235                $invalid_format = false;
236                $filename = $params['FILES'][0]['name'];
237                $quota = imap_get_quotaroot($this->mbox, $params["folder"]);
238                if((($quota['limit'] - $quota['usage'])*1024) <= $params['FILES'][0]['size']){
239                        return array( 'error' => $this->functions->getLang("fail in import:").
240                                                        " ".$this->functions->getLang("Over quota"));
241                }
242                if(substr($filename,strlen($filename)-4)==".zip") {
243                        $zip = zip_open($params['FILES'][0]['tmp_name']);
244
245                        if ($zip) {
246                                while ($zip_entry = zip_read($zip)) {
247
248                                        if (zip_entry_open($zip, $zip_entry, "r")) {
249                                                $email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
250                                                $status = @imap_append($this->mbox,
251                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
252                                                                        $email
253                                                                        );
254                                                if(!$status)
255                                                        array_push($errors,zip_entry_name($zip_entry));
256                                                zip_entry_close($zip_entry);
257                                        }
258                                }
259                                zip_close($zip);
260                        }
261
262                        if ( isset( $tmp_box ) && ! sizeof( $errors ) )
263                        {
264
265                                $mc = imap_check($this->mbox);
266
267                                $result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 );
268
269                                $ids = array( );
270                                foreach ($result as $overview)
271                                        $ids[ ] = $overview -> uid;
272
273                                return implode( ',', $ids );
274                        }
275                        }
276                else if(substr($filename,strlen($filename)-4)==".eml") {
277                        $email = implode("",file($params['FILES'][0]['tmp_name']));
278                        $status = @imap_append($this->mbox,
279                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
280                                                                        $email
281                                                                        );
282                        if(!$status){
283                                array_push($errors,zip_entry_name($zip_entry));
284                                zip_entry_close($zip_entry);
285                        }
286                }
287                else
288                {
289                        if ( isset( $tmp_box ) )
290                                imap_deletemailbox( $this->mbox,"{".$this -> imap_server."}$tmp_box" );
291
292                        return array("error" => $this->functions->getLang("wrong file format"));
293                        $invalid_format = true;
294                }
295
296                if(!$invalid_format) {
297                        if(count($errors)>0) {
298                                $message = $this->functions->getLang("fail in import:")."\n";
299                                foreach($errors as $arquivo) {
300                                        $message.=$arquivo."\n";
301                                }
302                                return array("error" => $message);
303                        }
304                        else
305                                return $this->functions->getLang("The import was executed successfully.");
306                }
307        }
308        /*
309                Remove os anexos de uma mensagem. A estratégia para isso é criar uma mensagem nova sem os anexos, mantendo apenas
310                a primeira parte do e-mail, que é o texto, sem anexos.
311                O método considera que o email é multpart.
312        */
313        function remove_attachments($params) {
314                include_once("class.message_components.inc.php");
315                if(!$this->mbox || !is_resource($this->mbox))
316                        $this->mbox = $this->open_mbox($params["folder"]);
317                $return["status"] = true;
318                $return["msg_num"] = $params["msg_num"];
319                $header = "";
320               
321                $headertemp = explode("\n",imap_fetchheader($this->mbox, imap_msgno($this->mbox, $params["msg_num"])));
322                foreach($headertemp as $head) {//Se eu colocar todo o header do email dá pau no append, então procuro apenas o que interessa.
323                        $head1 = explode(":",$head);
324                        if ( (strtoupper($head1[0]) == strtoupper("to")) ||
325                                        (strtoupper($head1[0]) == strtoupper("from")) ||
326                                        (strtoupper($head1[0]) == strtoupper("subject")) ||
327                                        (strtoupper($head1[0]) == strtoupper("date")) )
328                                $header .= $head."\r\n";
329                }
330                               
331                $msg = &new message_components($this->mbox);
332                $msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
333                                                             Então uso essa classe para verificar a codificação e o charset,
334                                                             para que o método decodeBody do expresso possa trazer tudo certinho*/
335               
336                $status = @imap_append($this->mbox,
337                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
338                                        $header.
339                                        "\r\n".
340                                        str_replace("\n","\r\n",$this->decodeBody(
341                                                        imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),"1"),
342                                                        $msg->encoding[$params["msg_num"]][0], $msg->charset[$params["msg_num"]][0]
343                                                        )                                       
344                                        )); //Append do novo email, só com header e conteúdo sem anexos.
345               
346                if(!$status) {
347                        $return["status"] = false;
348                        $return["msg"] = lang("error appending mail on delete attachments");
349                }
350       
351                @imap_delete($this->mbox, imap_msgno($this->mbox, $params["msg_num"])); //Insere o novo e-mail sem anexos.
352                @imap_expunge($this->mbox); //Deleta o e-mail com anexos
353               
354                return $return;
355               
356        }
357
358/**
359         *
360         * @return
361         * @param $params Object
362         */
363        function get_info_msgs($params) {
364                include_once("class.exporteml.inc.php");
365                $return = array();
366                $new_params = array();
367                $attach_params = array();
368                $new_params["msg_folder"]=$params["folder"];
369                $attach_params["folder"] = $params["folder"];
370                $msgs = explode(",",$params["msgs_number"]);
371                $exporteml = new ExportEml();
372                foreach($msgs as $msg_number) {
373                        $new_params["msg_number"] = $msg_number;
374                        //ini_set("display_errors","1");
375                        $msg_info = $this->get_info_msg($new_params);
376
377                        $this->mbox = $this->open_mbox($params['folder']); //Não sei porque, mas se não abrir de novo a caixa dá erro.
378                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
379
380                        $attach_params["num_msg"] = $msg_number;
381                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
382                        $msg_info['url_export_file'] = $exporteml->export_to_archive($msg_number,$params["folder"]);
383                        imap_close($this->mbox);
384                        $this->mbox=false;
385                        array_push($return,serialize($msg_info));
386                }
387                return $return;
388        }
389
390        function get_info_msg($params)
391        {
392                $return = array();
393                $msg_number = $params['msg_number'];
394                $msg_folder = $params['msg_folder'];
395               
396                if(!$this->mbox || !is_resource($this->mbox))
397                        $this->mbox = $this->open_mbox($msg_folder);           
398               
399                $header = $this->get_header($msg_number);
400                if (!$header) {
401                        $return['status_get_msg_info'] = "false";                       
402                        return $return;
403                }
404               
405                $header_ = imap_fetchheader($this->mbox, $msg_number, FT_UID);
406
407                $return_get_body = $this->get_body_msg($msg_number, $msg_folder);
408               
409                //Substituição de links em email para abrir no próprio expresso
410                $body = mb_ereg_replace("<a[^>]*href=[\'\"]mailto:([^\"\']+)[\'\"]>([^<]+)</a>","<a href=\"javascript:new_message_to('\\1')\">\\2</a>",$return_get_body['body']);
411
412                if($return_get_body['body']=='isCripted'){
413                        $exporteml = new ExportEml();
414                        $return['source']=$exporteml->export_msg_data($msg_number,$msg_folder);
415                        $return['body']                 = "";
416                        $return['attachments']  =  "";
417                        $return['thumbs']               =  "";
418                        $return['signature']    =  "";
419                        //return $return;
420                }else{
421            $return['body']             = $body;
422            $return['attachments']      = $return_get_body['attachments'];
423            $return['thumbs']           = $return_get_body['thumbs'];
424            $return['signature']        = $return_get_body['signature'];
425        }
426                $pattern = '/^[ \t]*Disposition-Notification-To(^:)*:(.+)*@(.+)*$/isUm';
427                if (preg_match($pattern, $header_, $fields))
428                {
429                        preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches);
430                        $return['DispositionNotificationTo'] = "<".$matches[0].">";
431                }
432
433                $return['Recent']       = $header->Recent;
434                $return['Unseen']       = $header->Unseen;
435                $return['Deleted']      = $header->Deleted;             
436                $return['Flagged']      = $header->Flagged;
437
438                if($header->Answered =='A' && $header->Draft == 'X'){
439                        $return['Forwarded'] = 'F';
440                }
441 
442                else {
443                        $return['Answered']     = $header->Answered;
444                        $return['Draft']        = $header->Draft;       
445                }
446
447                $return['msg_number'] = $msg_number;
448                $return['msg_folder'] = $msg_folder;
449       
450                $date_msg = gmdate("d/m/Y",$header->udate);
451                if (date("d/m/Y") == $date_msg)
452                        $return['udate'] = gmdate("H:i",$header->udate);
453                else
454                        $return['udate'] = $date_msg;
455               
456                $return['msg_day'] = $date_msg;
457                $return['msg_hour'] = gmdate("H:i",$header->udate);
458               
459                if (date("d/m/Y") == $date_msg) //no dia
460                {
461                        $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
462                        $return['smalldate'] = gmdate("H:i",$header->udate);
463
464                        $timestamp_now = strtotime("now");                     
465                        $timestamp_msg_time = $header->udate;
466                        // $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ.
467                        // The variable $timestamp_diff is calculated without MailDate TZ.
468                        $pdate = date_parse($header->MailDate);
469                        $timestamp_diff = $timestamp_now - $timestamp_msg_time  + ($pdate['zone']*(-60));
470                       
471                        if (gmdate("H",$timestamp_diff) > 0)
472                        {
473                                $return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
474                        }
475                        else
476                        {
477                                if (gmdate("i",$timestamp_diff) == 0){
478                                        $return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
479                                }
480                                elseif (gmdate("i",$timestamp_diff) == 1){
481                                        $return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
482                                }
483                                else{
484                                        $return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
485                                }
486                        }
487                }
488                else{
489                        $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
490                        $return['smalldate'] = gmdate("d/m/Y",$header->udate);
491                }
492               
493                $from = $header->from;
494                $return['from'] = array();
495                $tmp = imap_mime_header_decode($from[0]->personal);
496                $return['from']['name'] = $this->decode_string($tmp[0]->text);
497                $return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
498                if ($return['from']['name'])
499                {
500                        if (substr($return['from']['name'], 0, 1) == '"')
501                                $return['from']['full'] = $return['from']['name'] . ' ' . '&lt;' . $return['from']['email'] . '&gt;';
502                        else
503                                $return['from']['full'] = '"' . $return['from']['name'] . '" ' . '&lt;' . $return['from']['email'] . '&gt;';
504                }
505                else
506                        $return['from']['full'] = $return['from']['email'];
507               
508                // Sender attribute
509                $sender = $header->sender;
510                $return['sender'] = array();
511                $tmp = imap_mime_header_decode($sender[0]->personal);
512                $return['sender']['name'] = $this->decode_string($tmp[0]->text);
513                $return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
514                if ($return['sender']['name'])
515                {
516                        if (substr($return['sender']['name'], 0, 1) == '"')
517                                $return['sender']['full'] = $return['sender']['name'] . ' ' . '&lt;' . $return['sender']['email'] . '&gt;';
518                        else
519                                $return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '&lt;' . $return['sender']['email'] . '&gt;';
520                }
521                else
522                        $return['sender']['full'] = $return['sender']['email'];
523
524                if($return['from']['full'] == $return['sender']['full'])
525                        $return['sender'] = null;
526                $to = $header->to;
527                $return['toaddress2'] = "";
528                if (!empty($to))
529                {
530                        foreach ($to as $tmp)
531                        {
532                                if (!empty($tmp->personal))
533                                {
534                                        $personal_tmp = imap_mime_header_decode($tmp->personal);
535                                        $return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
536                                        $return['toaddress2'] .= " ";
537                                        $return['toaddress2'] .= "&lt;";
538                                        if ($tmp->host != 'unspecified-domain')
539                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
540                                        else
541                                                $return['toaddress2'] .= $tmp->mailbox;
542                                        $return['toaddress2'] .= "&gt;";
543                                        $return['toaddress2'] .= ", ";
544                                }
545                                else
546                                {
547                                        if ($tmp->host != 'unspecified-domain')
548                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
549                                        else
550                                                $return['toaddress2'] .= $tmp->mailbox;
551                                        $return['toaddress2'] .= ", ";
552                                }
553                        }
554                        $return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
555                }
556                else
557                {
558                        $return['toaddress2'] = "&lt;Empty&gt;";
559                }       
560               
561                $cc = $header->cc;
562                $return['cc'] = "";
563                if (!empty($cc))
564                {
565                        foreach ($cc as $tmp_cc)
566                        {
567                                if (!empty($tmp_cc->personal))
568                                {
569                                        $personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
570                                        $return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
571                                        $return['cc'] .= " ";
572                                        $return['cc'] .= "&lt;";
573                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
574                                        $return['cc'] .= "&gt;";
575                                        $return['cc'] .= ", ";
576                                }
577                                else
578                                {
579                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
580                                        $return['cc'] .= ", ";
581                                }
582                        }
583                        $return['cc'] = $this->del_last_two_caracters($return['cc']);
584                }
585                else
586                {
587                        $return['cc'] = "";
588                }       
589
590                ##
591                # @AUTHOR Rodrigo Souza dos Santos
592                # @DATE 2008/09/12
593                # @BRIEF Adding the BCC field.
594                ##
595                $bcc = $header->bcc;
596                $return['bcc'] = "";
597                if (!empty($bcc))
598                {
599                        foreach ($bcc as $tmp_bcc)
600                        {
601                                if (!empty($tmp_bcc->personal))
602                                {
603                                        $personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
604                                        $return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
605                                        $return['bcc'] .= " ";
606                                        $return['bcc'] .= "&lt;";
607                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
608                                        $return['bcc'] .= "&gt;";
609                                        $return['bcc'] .= ", ";
610                                }
611                                else
612                                {
613                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
614                                        $return['bcc'] .= ", ";
615                                }
616                        }
617                        $return['bcc'] = $this->del_last_two_caracters($return['bcc']);
618                }
619                else
620                {
621                        $return['bcc'] = "";
622                }       
623
624                $reply_to = $header->reply_to;
625                $return['reply_to'] = "";
626                if (is_object($reply_to[0]))
627                {
628                        if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
629                        {
630                                if (!empty($reply_to[0]->personal))
631                                {
632                                        $personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
633                                        if(!empty($personal_reply_to[0]->text)) {
634                                                $return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
635                                                $return['reply_to'] .= " ";
636                                                $return['reply_to'] .= "&lt;";
637                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
638                                                $return['reply_to'] .= "&gt;";
639                                        }
640                                        else {
641                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
642                                        }
643                                }
644                                else
645                                {
646                                        $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
647                                }
648                        }
649                }
650                $return['reply_to'] = $this->decode_string($return['reply_to']);
651                $return['subject'] = $this->decode_string($header->fetchsubject);
652                $return['Size'] = $header->Size;
653                $return['reply_toaddress'] = $header->reply_toaddress;
654
655                //All this is to help in local messages
656                $return['timestamp'] = $header->udate;
657                $return['login'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];//$GLOBALS['phpgw_info']['user']['account_id'];
658                $return['reply_toaddress'] = $header->reply_toaddress;
659
660                return $return;
661        }
662       
663        function get_body_msg($msg_number, $msg_folder)
664        {
665                include_once("class.message_components.inc.php");
666                $msg = &new message_components($this->mbox);
667                $msg->fetch_structure($msg_number);
668                $return = array();
669                $return['attachments'] = $this-> download_attachment($msg,$msg_number);         
670                if(!$this->has_cid)
671                {
672                        $return['thumbs']  = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
673                        $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
674                }                       
675               
676                if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
677                {
678            if(strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime'){
679                $return['body']='isCripted';
680                return $return;
681            }
682
683                        $attachment = array(); //No attachments
684
685            if(strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime'){
686                                        $return['body']='isCripted';
687                                        return $return;
688                        }
689
690                        $content = '';
691                        if (strtolower($msg->structure[$msg_number]->subtype) == "plain")
692                        {
693                                $content .= nl2br($this->decodeBody((imap_body($this->mbox, $msg_number, FT_UID)), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]));
694                        }
695                        else if (strtolower($msg->structure[$msg_number]->subtype) == "html")
696                        {
697                                $content .= $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
698                        }
699                }
700                else
701                { //Complicated message, multiple parts
702                        $html_body = '';
703                        $content = '';
704                        $has_multipart = true;
705                        $this->has_cid = false;
706                       
707                        if (strtolower($msg->structure[$msg_number]->subtype) == "related")
708                                $this->has_cid = true;
709                       
710                        if (strtolower($msg->structure[$msg_number]->subtype) == "alternative") {
711                                $show_only_html = false;
712                                foreach($msg->pid[$msg_number] as $values => $msg_part) {
713                                        $file_type = strtolower($msg->file_type[$msg_number][$values]);
714                                        if($file_type == "text/html")
715                                                $show_only_html = true;                 
716                                }
717                        }
718                        else
719                                $show_only_html = false;
720
721                        foreach($msg->pid[$msg_number] as $values => $msg_part)
722                        {
723                               
724                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
725                                if($file_type == "message/rfc822")
726                                        $has_multipart = false;
727       
728                                if($file_type == "multipart/alternative")
729                                        $has_multipart = false;
730       
731                                if(($file_type == "text/plain"
732                                        || $file_type == "text/html")
733                                        && $file_type != 'attachment')
734                                {
735                                        if($file_type == "text/plain" && !$show_only_html && $has_multipart)
736                                        {
737                                                // if TXT file size > 100kb, then it will not expand.
738                                                if(!($file_type == "text/plain" && $msg->fsize[$msg_number][$values] > 102400)) {
739                                                        $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])));                                                     
740                                                }
741                                        }
742                                        // if HTML attachment file size > 300kb, then it will not expand.
743                                        else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < 307200)
744                                        {
745                                                $content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
746                                                $show_only_html = true;
747                                        }
748                                }
749                                else if($file_type == "message/delivery-status"){
750                                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
751                                        $content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));                                           
752
753                                }
754                                else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
755                                       
756                                        include_once("class.imap_attachment.inc.php");
757                                        $att = new imap_attachment();
758                                        $attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
759                                        if($attachments['number_attachments'] > 0) {                                                                                           
760                                                foreach($attachments ['attachment'] as $index => $attachment){
761                                                        if(strtolower($attachment['type']) == "delivery-status" ||
762                                                                strtolower($attachment['type']) == "rfc822" ||                                                         
763                                                                strtolower($attachment['type']) == "rfc822-headers" ||
764                                                                strtolower($attachment['type']) == "plain"
765                                                        ){
766                                                                $obj = imap_rfc822_parse_headers(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values]);                                   
767                                                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";                                   
768                                                                $content .= "<br><table  style='margin:2px;border:1px solid black;background:#EAEAEA'>";
769                                                                $content .= "<tr><td><b>".$this->functions->getLang("Subject").":</b></td><td>".$this->decode_string($obj->subject)."</td></tr>";
770                                                                $content .= "<tr><td><b>".$this->functions->getLang("From").":</b></td><td>".$this->decode_string($obj->from[0]->mailbox."@".$obj->from[0]->host)."</td></tr>";
771                                                                $content .= "<tr><td><b>".$this->functions->getLang("Date").":</b></td><td>".$obj->date."</td></tr>";
772                                                                $content .= "<tr><td><b>".$this->functions->getLang("TO").":</b></td><td>".$this->decode_string($obj->to[0]->mailbox."@".$obj->to[0]->host)."</td></tr>";
773                                                                $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>";                                                               
774                                                                $ix_part =      strtolower($attachment['type']) == "delivery-status" ? 1 : 0;
775                                                                $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]));                                                         
776                                                                break;                 
777                                                        }
778                                                }
779                                        }
780                                }
781                        }
782                        if($file_type == "text/plain" && ($show_only_html &&  $msg_part == 1) ||  (!$show_only_html &&  $msg_part == 3)){
783                                if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" &&  $msg_part == 1)
784                                        $content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
785                                else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
786                                        $content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));                         
787                        }
788                }
789                // Force message with flag Seen (imap_fetchbody not works correctly)
790                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");                               
791                $this->set_messages_flag($params);
792                $content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
793                $content = $this->replace_special_characters($content);
794                $return['body'] = $content;
795                return $return;
796        }
797       
798        function htmlfilter($body)
799        {
800                require_once('htmlfilter.inc');
801               
802                $tag_list = Array(
803                                false,
804                                'blink',
805                                'object',
806                                'meta',
807                                'html',
808                                'link',
809                                'frame',
810                                'iframe',
811                                'layer',
812                                'ilayer',
813                                'plaintext'
814                );
815
816                /**
817                * A very exclusive set:
818                */
819                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
820                $rm_tags_with_content = Array(
821                                'script',
822                                'style',
823                                'applet',
824                                'embed',
825                                'head',
826                                'frameset',
827                                'xml',
828                                'xmp'
829                );
830
831                $self_closing_tags =  Array(
832                                'img',
833                                'br',
834                                'hr',
835                                'input'
836                );
837
838                $force_tag_closing = true;
839
840                $rm_attnames = Array(
841                        '/.*/' =>
842                                Array(
843                                        '/target/i',
844                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
845                                        '/^dynsrc/i',
846                                        '/^datasrc/i',
847                                        '/^data.*/i',
848                                        '/^lowsrc/i'
849                                )
850                );
851
852                /**
853                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
854                 * some idea of what's going on here. :)
855                 */
856
857                $bad_attvals = Array(
858                '/.*/' =>
859                Array(
860                      '/.*/' =>
861                              Array(
862                                Array(
863                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
864                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
865                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
866                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
867                                      ),
868                            Array(
869                                              '\\1oddjob:\\2\\1',
870                                          //'\\1uucp:\\2\\1', -> doclinks notes
871                                      '\\1amaretto:\\2\\1',
872                                          '\\1round:\\2\\1'
873                                        )
874                                    ),     
875         
876                          '/^style/i' =>
877                              Array(
878                                        Array(
879                                          '/expression/i',
880                                              '/behaviou*r/i',
881                                          '/binding/i',
882                                              '/include-source/i',
883                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
884                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
885                                         ),
886                                        Array(
887                                          'idiocy',
888                                              'idiocy',
889                                          'idiocy',
890                                              'idiocy',
891                                          'url(\\1http://securityfocus.com/\\1)',
892                                          'url(\\1http://securityfocus.com/\\1)'
893                                         )
894                                )
895                          )
896                    );
897
898                $add_attr_to_tag = Array(
899                                '/^a$/i' => Array('target' => '"_new"')
900                );
901       
902       
903                $trusted_body = sanitize($body,
904                                $tag_list,
905                                $rm_tags_with_content,
906                                $self_closing_tags,
907                                $force_tag_closing,
908                                $rm_attnames,
909                                $bad_attvals,
910                                $add_attr_to_tag
911                );
912       
913            return $trusted_body;
914        }
915       
916        function decodeBody($body, $encoding, $charset=null)
917        {
918                /**
919                * replace e-mail by anchor.
920                */
921                // HTML Filter
922                //$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);
923        //$body = str_replace("\r\n", "\n", $body);
924                if ($encoding == 'quoted-printable')
925                {
926                        /*
927                       
928                        for($i=0;$i<256;$i++) {
929                                $c1=dechex($i);
930                                if(strlen($c1)==1){$c1="0".$c1;}
931                                $c1="=".$c1;
932                                $myqprinta[]=$c1;
933                                $myqprintb[]=chr($i);
934                        }               
935                         */
936                        $body = str_replace($myqprinta,$myqprintb,($body));
937                        $body = quoted_printable_decode($body);
938                while (ereg("=\n", $body))
939                {
940                        $body = ereg_replace ("=\n", '', $body);
941                }
942        }
943        else if ($encoding == 'base64')
944        {
945                $body = base64_decode($body);
946        }
947        else if ($encoding == '7bit')
948        {
949                $body = quoted_printable_decode($body);                                         
950        }
951                // All other encodings are returned raw.
952                if (strtolower($charset) == "utf-8")
953                        return utf8_decode($body);
954        else
955                        return $body;
956        }
957       
958        function process_embedded_images($msg, $msgno, $body, $msg_folder)
959        {
960                if (count($msg->inline_id[$msgno]) > 0)
961                {
962                        foreach ($msg->inline_id[$msgno] as $index => $cid)
963                        {
964                                $cid = eregi_replace("<", "", $cid);
965                                $cid = eregi_replace(">", "", $cid);
966                                $msg_part = $msg->pid[$msgno][$index];
967                                //$body = eregi_replace("alt=\"\"", "", $body);
968                                $body = eregi_replace("<br/>", "", $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                                $body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
972                        }
973                }
974               
975                return $body;
976        }
977       
978        function replace_special_characters($body)
979        {
980                // Suspected TAGS!
981                /*$tag_list = Array(   
982                        'blink','object','meta',
983                        'html','link','frame',
984                        'iframe','layer','ilayer',
985                        'plaintext','script','style','img',
986                        'applet','embed','head',
987                        'frameset','xml','xmp');
988                */
989
990                // Layout problem: Change html elements
991                // with absolute position to relate position, CASE INSENSITIVE.
992                $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
993
994                $tag_list = Array('head','blink','object','frame',
995                        'iframe','layer','ilayer','plaintext','script',
996                        'applet','embed','frameset','xml','xmp','style');
997
998                $body = $this-> replace_links($body);
999                $blocked_tags = array();               
1000                foreach($tag_list as $index => $tag) {
1001                        $new_body = @mb_eregi_replace("<$tag", "<!--$tag", $body);
1002                        if($body != $new_body) {
1003                                $blocked_tags[] = $tag;
1004                        }
1005                        $body = @mb_eregi_replace("</$tag>", "</$tag-->", $new_body);
1006                }
1007                // Malicious Code Remove
1008                $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";
1009                preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
1010                foreach($rest[0] as $i => $val)
1011                        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
1012                        $body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
1013
1014                return  "<span>".$body;
1015        }
1016
1017        function replace_links($body) {                                 
1018                $matches = array();
1019                // Verify exception.
1020                @preg_match("/<a href=\"notes:\/\/\//",$body,$matches);
1021                // If there is no exception,then open the link in new window.
1022                if(count($matches))
1023                        return $body;
1024       
1025                $pattern = '/(?<=[\s|(<br>)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[:\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\:\/\w.\-~&=?%;@+]*))/i';
1026                $replacement = '<a href="http$3://$4$5" target="_blank">$1</a>';
1027                return preg_replace($pattern, $replacement, $body);
1028               
1029                // Original
1030                //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);
1031        }
1032
1033        function get_signature($msg, $msg_number, $msg_folder)
1034        {
1035        include_once("../security/classes/CertificadoB.php");
1036                include_once("class.db_functions.inc.php");
1037                foreach ($msg->file_type[$msg_number] as $index => $file_type)
1038                {
1039            $sign = array();
1040                        $temp = $this->get_info_head_msg($msg_number);
1041                        if($temp['ContentType'] =='normal') return $sign;
1042                        $file_type = strtolower($file_type);
1043                        if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
1044                        {
1045                                if ($file_type == 'application/x-pkcs7-signature' || $file_type == 'application/pkcs7-signature')
1046                                {
1047                                        if(!$this->mbox || !is_resource($this->mbox))
1048                                        $this->mbox = $this->open_mbox($msg_folder);
1049
1050                                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
1051
1052                                        $imap_msg               = @imap_fetchheader($this->mbox, $msg_number, FT_UID);
1053                                        $imap_msg               .= @imap_body($this->mbox, $msg_number, FT_UID);
1054
1055                                        $certificado = new certificadoB();
1056                                        $validade = $certificado->verificar($imap_msg);
1057
1058                                        if ($certificado->apresentado)
1059                                        {
1060                                                $from = $header->from;
1061                                                foreach ($from as $id => $object) {
1062                                                        $fromname = $object->personal;
1063                                                    $fromaddress = $object->mailbox . "@" . $object->host;
1064                                        }
1065                                                $sign_alert = '';
1066                                                foreach ($certificado->erros_ssl as $item)
1067                                                {
1068                                                        $check_error_msg = $this->functions->getLang($item);
1069                                                        /*
1070                                                         * Desabilite o teste abaixo para mostrar todas as mensagem
1071                                                         * de erro.
1072                                                         */
1073                                                        //if (!strpos($check_error_msg,'*',strlen($check_error_msg-1)))
1074                                                        //{
1075                                                        $sign[] = "<span style=color:red>" . $check_error_msg . " </span>";
1076                                                        //}
1077                                                }
1078                                                if (count($certificado->erros_ssl) < 1)
1079                                                {
1080                                                        $check_msg = $this->functions->getLang('Message untouched') . " ";
1081                                                        if($fromaddress == $certificado->dados['EMAIL'])
1082                                                        {
1083                                                                $check_msg .= $this->functions->getLang('and') . " ";
1084                                                                $check_msg .= $this->functions->getLang('authentic');
1085                                                        }
1086                                                        $sign[] = "<strong>".$check_msg."</strong>";
1087                                                }
1088                                                if($fromaddress != $certificado->dados['EMAIL'])
1089                                                {
1090                                                        $sign[] =       "<span style=color:red>" .
1091                                                                                $this->functions->getLang('message') . " " .
1092                                                                        $this->functions->getLang('with signer different from sender') .
1093                                                                        " </span>";
1094                                                }
1095                                                $sign[] = "<strong>" . $this->functions->getLang('Message signed by: ') . "</strong>" . $certificado->dados['NOME'];
1096                                                $sign[] = "<strong>" . $this->functions->getLang('Certificate email: ') . "</strong>" . $certificado->dados['EMAIL'];
1097                                                $sign[] = "<strong>" . $this->functions->getLang('Mail from: ') . "</strong>" . $fromaddress;
1098                                                $sign[] = "<strong>" . $this->functions->getLang('Certificate Authority: ') . "</strong>" . $certificado->dados['EMISSOR'];
1099                                                $sign[] = "<strong>" . $this->functions->getLang('Validity of certificate: ') . "</strong>" . gmdate('r',openssl_to_timestamp($certificado->dados['FIM_VALIDADE']));
1100                                                $sign[] = "<strong>" . $this->functions->getLang('Message date: ') . "</strong>" . $header->Date;
1101
1102                                            $cert = openssl_x509_parse($certificado->cert_assinante);
1103                                                /*
1104                                                $sign[] = '<table>';
1105                                                $sign[] = '<tr><td colspan=1><b>Expedido para:</b></td></tr>';
1106                                                $sign[] = '<tr><td>Nome Comum (CN) </td><td>' . $cert[subject]['CN'] .  '</td></tr>';
1107                                                $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1108                                                $sign[] = '<tr><td>Data de nascimento </td><td>' . $certificado->dados['NASCIMENTO'] .  '</td></tr>';
1109                                                $sign[] = '<tr><td>CPF </td><td>' . $certificado->dados['CPF'] .  '</td></tr>';
1110                                                $sign[] = '<tr><td>Documento identidade </td><td>' . $certificado->dados['RG'] .  '</td></tr>';
1111                                                $sign[] = '<tr><td>Empresa (O) </td><td>' . $cert[subject]['O'] .  '</td></tr>';
1112                                                $sign[] = '<tr><td>Unidade Organizacional (OU) </td><td>' . $cert[subject]['OU'][0] .  '</td></tr>';
1113                                                //$sign[] = '<tr><td>Numero de serie </td><td>' . $cert['serialNumber'] .  '</td></tr>';
1114                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1115                                                $sign[] = '<tr><td colspan=1><b>Expedido por:</b></td></tr>';
1116                                                $sign[] = '<tr><td>Nome Comum (CN) </td><td>' . $cert[issuer]['CN'] .  '</td></tr>';
1117                                                $sign[] = '<tr><td>Empresa (O) </td><td>' . $cert[issuer]['O'] .  '</td></tr>';
1118                                                $sign[] = '<tr><td>Unidade Organizacional (OU) </td><td>' . $cert[issuer]['OU'][0] .  '</td></tr>';
1119                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1120                                                $sign[] = '<tr><td colspan=1><b>Validade:</b></td></tr>';
1121                                                $H = data_hora($cert[validFrom]);
1122                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1123                                                $sign[] = '<tr><td>Expedido em </td><td>' . $X .  '</td></tr>';
1124                                                $H = data_hora($cert[validTo]);
1125                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1126                                                $sign[] = '<tr><td>Valido ate </td><td>' . $X .  '</td></tr>';
1127                                                $sign[] = '<tr><td colspan=1> </td></tr>';
1128                                                $sign[] = '</table>';
1129                                                */
1130                                                $sign_alert .= 'Expedido para:\n';
1131                                                $sign_alert .= 'Nome Comum (CN)  ' . $cert[subject]['CN'] .  '\n';
1132                                                $X = substr($certificado->dados['NASCIMENTO'] ,0,2) . '-' . substr($certificado->dados['NASCIMENTO'] ,2,2) . '-'  . substr($certificado->dados['NASCIMENTO'] ,4,4);
1133                                                $sign_alert .= 'Data de nascimento ' . $X .  '\n';
1134                                                $sign_alert .= 'CPF ' . $certificado->dados['CPF'] .  '\n';
1135                                                $sign_alert .= 'Documento identidade ' . $certificado->dados['RG'] .  '\n';
1136                                                $sign_alert .= 'Empresa (O)  ' . $cert[subject]['O'] .  '\n';
1137                                                $sign_alert .= 'Unidade Organizacional (OU) ' . $cert[subject]['OU'][0] .  '\n';
1138                                                //$sign_alert[] = '<tr><td>Numero de serie </td><td>' . $cert['serialNumber'] .  '</td></tr>';
1139                                                $sign_alert .= '\n';
1140                                                $sign_alert .= 'Expedido por:\n';
1141                                                $sign_alert .= 'Nome Comum (CN) ' . $cert[issuer]['CN'] . '\n';
1142                                                $sign_alert .= 'Empresa (O)  ' . $cert[issuer]['O'] .  '\n';
1143                                                $sign_alert .= 'Unidade Organizacional (OU) ' . $cert[issuer]['OU'][0] .  '\n';
1144                                                $sign_alert .= '\n';
1145                                                $sign_alert .= 'Validade:\n';
1146                                                $H = data_hora($cert[validFrom]);
1147                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1148                                                $sign_alert .= 'Expedido em ' . $X .  '\n';
1149                                                $H = data_hora($cert[validTo]);
1150                                                $X = substr($H,6,2) . '-' . substr($H,4,2) . '-'  . substr($H,0,4);
1151                                                $sign_alert .= 'Valido ate ' . $X .  '\n';
1152
1153                                                $sign[] = "<a onclick=\"javascript:alert('" . $sign_alert . "')\"><b><font color=\"#0000FF\">".$this->functions->getLang("More")."...</font></b></a>";
1154                                                $this->db = new db_functions();
1155
1156                                                // TODO: testar se existe um certificado no banco e verificar qual ï¿œ o mais atual.
1157                        if(!$certificado->dados['EXPIRADO'] && !$certificado->dados['REVOGADO'] && count($certificado->erros_ssl) < 1)
1158                            $this->db->insert_certificate(strtolower($certificado->dados['EMAIL']), $certificado->cert_assinante, $certificado->dados['SERIALNUMBER'], $certificado->dados['AUTHORITYKEYIDENTIFIER']);
1159                                        }
1160                                     else
1161                                    {
1162                                        $sign[] = "<span style=color:red>" . $this->functions->getLang('Invalid signature') . "</span>";
1163                                        foreach($certificado->erros_ssl as $item)
1164                                        $sign[] = "<span style=color:red>" . $this->functions->getLang($item) . "</span>";
1165                    }
1166                                }
1167                        }
1168                }
1169                return $sign;   
1170        }
1171
1172        function get_thumbs($msg, $msg_number, $msg_folder)
1173        {
1174                $thumbs_array = array();
1175                $i = 0;
1176        foreach ($msg->file_type[$msg_number] as $index => $file_type)
1177        {
1178                $file_type = strtolower($file_type);
1179                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
1180                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
1181                                $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].">";
1182                                $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>";
1183                                        $thumbs_array[] = $href;
1184                        }
1185                        $i++;
1186                }
1187        }
1188        return $thumbs_array;
1189        }
1190               
1191        /*function delete_msg($params)
1192        {
1193                $folder = $params['folder'];
1194                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
1195               
1196                $mbox_stream = $this->open_mbox($folder);
1197               
1198                foreach ($msgs_to_delete as $msg_number){
1199                        imap_delete($mbox_stream, $msg_number, FT_UID);
1200                }
1201                imap_close($mbox_stream, CL_EXPUNGE);
1202                return $params['msgs_to_delete'];
1203        }*/
1204
1205        // Novo
1206        function delete_msgs($params)
1207        {
1208               
1209                $folder = $params['folder'];
1210                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
1211                $msgs_number = explode(",",$params['msgs_number']);
1212                $border_ID = $params['border_ID'];
1213               
1214                $return = array();
1215               
1216                if ($params['get_previous_msg']){
1217                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1218                        // Fix problem in unserialize function JS.
1219                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1220                }
1221
1222                //$mbox_stream = $this->open_mbox($folder);             
1223                $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()))));
1224               
1225                foreach ($msgs_number as $msg_number)
1226                {
1227                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1228                                $return['msgs_number'][] = $msg_number;
1229                }
1230               
1231                $return['folder'] = $folder;
1232                $return['border_ID'] = $border_ID;
1233               
1234                if($mbox_stream)
1235                        imap_close($mbox_stream, CL_EXPUNGE);
1236                return $return;
1237        }
1238
1239               
1240        function refresh($params)
1241        {
1242                include_once("class.imap_attachment.inc.php");
1243                $imap_attachment = new imap_attachment();               
1244                $folder = $params['folder'];
1245                $msg_range_begin = $params['msg_range_begin'];
1246                $msg_range_end = $params['msg_range_end'];
1247                $msgs_existent = $params['msgs_existent'];
1248                $sort_box_type = $params['sort_box_type'];             
1249                $sort_box_reverse = $params['sort_box_reverse'];
1250                $msgs_in_the_server = array();
1251                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1252                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1253                $msgs_in_the_server = array_keys($msgs_in_the_server);
1254                if(!count($msgs_in_the_server))
1255                        return array();
1256                       
1257                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
1258                $msgs_in_the_client = explode(",", $msgs_existent);     
1259
1260                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
1261                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
1262               
1263                $msgs_to_exec = array();
1264                if ((count($msg_to_insert)) && ($msgs_existent))
1265                {
1266                        foreach($msg_to_insert as $index => $msg_number)
1267                        {
1268                                if ($msgs_in_the_server[$index+1])
1269                                {
1270                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
1271                                        $msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
1272                                }
1273                                else
1274                                {
1275                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
1276                                        $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1277                                }
1278                        }
1279                        ksort($msgs_to_exec);
1280                }
1281                elseif(!$msgs_existent)
1282                {
1283                        foreach($msgs_in_the_server as $index => $msg_number)
1284                        {
1285                                $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1286                        }
1287                }
1288               
1289                $return = array();
1290                $i = 0;
1291                foreach($msgs_to_exec as $msg_number => $command)
1292                {
1293                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
1294                        * atributos do cabeçalho. Como eu preciso do atributo Importance
1295                        * para saber se o email é importante ou não, uso abaixo a função
1296                        * imap_fetchheader e busco o atributo importance nela para passar
1297                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1298                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1299                        * não preciso reimplementar o método utilizando o fetchheader.
1300                        * Como na atualização são poucas as mensagens que devem ser renderizadas,
1301                        * a perda em performance é insignificante.
1302                        */
1303            $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1304                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
1305                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
1306                       
1307                        $header = $this->get_header($msg_number);
1308                        if (!is_object($header))
1309                                continue;
1310
1311                        $return[$i]['msg_number']       = $msg_number;
1312                        $return[$i]['command']          = $command;
1313                       
1314                        $return[$i]['msg_folder']       = $folder;
1315            // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1316            $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
1317                        $return[$i]['Recent']           = $header->Recent;
1318                        $return[$i]['Unseen']           = $header->Unseen;
1319                        $return[$i]['Answered']         = $header->Answered;
1320                        $return[$i]['Deleted']          = $header->Deleted;
1321                        $return[$i]['Draft']            = $header->Draft;
1322                        $return[$i]['Flagged']          = $header->Flagged;
1323
1324                        $date_msg = gmdate("d/m/Y",$header->udate);
1325                        if (gmdate("d/m/Y") == $date_msg)
1326                                $return[$i]['udate'] = gmdate("H:i",$header->udate);
1327                        else
1328                                $return[$i]['udate'] = $date_msg;
1329                       
1330                        $from = $header->from;
1331                        $return[$i]['from'] = array();
1332                        $tmp = imap_mime_header_decode($from[0]->personal);
1333                        $return[$i]['from']['name'] = $tmp[0]->text;
1334                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
1335                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
1336                        if(!$return[$i]['from']['name'])
1337                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
1338                       
1339                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1340                        $return[$i]['toaddress'] = '';
1341                        foreach ($toaddress as $tmp)
1342                                $return[$i]['toaddress'] .= $tmp->text;*/
1343                        $to = $header->to;
1344                        $return[$i]['to'] = array();
1345                        $tmp = imap_mime_header_decode($to[0]->personal);
1346                        $return[$i]['to']['name'] = $tmp[0]->text;
1347                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1348                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
1349                       
1350                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1351
1352                        $return[$i]['Size'] = $header->Size;
1353                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
1354                       
1355                        $return[$i]['attachment'] = array();
1356                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
1357                        $i++;
1358                }
1359                $return['new_msgs'] = imap_num_recent($this->mbox);
1360                $return['msgs_to_delete'] = $msg_to_delete;
1361                if($this->mbox && is_resource($this->mbox))
1362                        imap_close($this->mbox);
1363
1364                return $return;
1365        }
1366
1367     /**
1368     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1369     * assinado ou cifrado.
1370     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1371     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1372     * @param $msg_number O número da mesagem
1373     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1374     */
1375    function getMessageType($msg_number, $headers = false){
1376
1377            $contentType = "normal";
1378            if (!$headers){
1379                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1380            }
1381            //$header2 = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1382            if (preg_match("/Content-Type:.*pkcs7-signature/i", $headers) == 1){
1383                $contentType = "signature";
1384            } else if (preg_match("/Content-Type:.*x-pkcs7-mime/i", $headers) == 1){
1385                $contentType = "cipher";
1386            }
1387
1388            return $contentType;
1389    }
1390
1391        function get_folders_list($params = null)
1392        {
1393                $mbox_stream = $this->open_mbox();             
1394                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
1395                $folders_list = imap_getmailboxes($mbox_stream, $serverString, "*");
1396                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1397
1398                $tmp = array();
1399                $result = array();
1400               
1401                if (is_array($folders_list)) {
1402                        reset($folders_list);
1403            $this->ldap = new ldap_functions();
1404                       
1405                        $i = 0;
1406                        while (list($key, $val) = each($folders_list)) {
1407                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
1408
1409                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1410                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
1411                if($tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas'){
1412                    //error_log('passou', 3,'/tmp/imap_get_list.log');
1413                    //imap_deletemailbox($mbox_stream,imap_utf7_encode("{".$this->imap_server."}".'INBOX/decifradas'));
1414                    continue;
1415                }
1416                $result[$i]['folder_unseen'] = $status->unseen;
1417                                $folder_id = $tmp_folder_id[1];
1418                                $result[$i]['folder_id'] = $folder_id;
1419                               
1420                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1421                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1422                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1423                                if (is_numeric($result[$i]['folder_name']))     {
1424                                        //$this->ldap = new ldap_functions();
1425                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])){
1426                                                $result[$i]['folder_name'] = $cn;
1427                                        }
1428                                }
1429                               
1430                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1431                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
1432                                       
1433                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1434                                        $result[$i]['folder_hasChildren'] = 1;
1435                                else
1436                                        $result[$i]['folder_hasChildren'] = 0;
1437
1438                                $i++;                           
1439                        }
1440                }
1441               
1442                foreach ($result as $folder_info)
1443                {
1444                        $array_tmp[] = $folder_info['folder_id'];
1445                }
1446               
1447                natcasesort($array_tmp);
1448               
1449                foreach ($array_tmp as $key => $folder_id)
1450                {
1451                        $result2[] = $result[$key];
1452                }
1453               
1454                $current_folder = "INBOX";
1455                if($params && $params['folder'])
1456                        $current_folder = $params['folder'];
1457                return array_merge($result2, $this->get_quota(array(folder_id => $current_folder)));
1458        }
1459       
1460        function create_mailbox($arr)
1461        {
1462                $namebox        = $arr['newp'];
1463                $mbox_stream = $this->open_mbox();
1464                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1465                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
1466               
1467                $result = "Ok";
1468                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
1469                {
1470                        $result = implode("<br />\n", imap_errors());
1471                }       
1472               
1473                if($mbox_stream)
1474                        imap_close($mbox_stream);
1475                                       
1476                return $result;
1477               
1478        }
1479       
1480        function create_extra_mailbox($arr)
1481        {
1482                $nameboxs = explode(";",$arr['nw_folders']);
1483                $result = "";
1484                $mbox_stream = $this->open_mbox();
1485                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1486                foreach($nameboxs as $key=>$tmp){                       
1487                        if($tmp != ""){
1488                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1489                                        $result = implode("<br />\n", imap_errors());
1490                                        if($mbox_stream)
1491                                                imap_close($mbox_stream);                                       
1492                                        return $result;
1493                                }
1494                        }
1495                }
1496                if($mbox_stream)
1497                        imap_close($mbox_stream);
1498                return true;
1499        }
1500       
1501        function delete_mailbox($arr)
1502        {
1503                $namebox = $arr['del_past'];
1504                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1505                $mbox_stream = $this->open_mbox();
1506                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
1507               
1508                $result = "Ok";
1509                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1510                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1511                {
1512                        $result = implode("<br />\n", imap_errors());
1513                }
1514                if($mbox_stream)
1515                        imap_close($mbox_stream);
1516                return $result;
1517        }
1518       
1519        function ren_mailbox($arr)
1520        {
1521                $namebox = $arr['current'];
1522                $new_box = $arr['rename'];
1523                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1524                $mbox_stream = $this->open_mbox();
1525                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
1526               
1527                $result = "Ok";
1528                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1529                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
1530               
1531                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1532                {
1533                        $result = imap_errors();                       
1534                }
1535                if($mbox_stream)
1536                        imap_close($mbox_stream);
1537                return $result;
1538               
1539        }
1540       
1541        function get_num_msgs($params)
1542        {
1543                $folder = $params['folder'];
1544                if(!$this->mbox || !is_resource($this->mbox)) {
1545                        $this->mbox = $this->open_mbox($folder);
1546                        if(!$this->mbox || !is_resource($this->mbox))
1547                        return imap_last_error();
1548                }               
1549                $num_msgs = imap_num_msg($this->mbox);
1550                if($this->mbox && is_resource($this->mbox))
1551                        imap_close($this->mbox);
1552               
1553                return $num_msgs;
1554        }
1555       
1556        function send_mail($params)
1557        {
1558                include_once("class.phpmailer.php");
1559                $mail = new PHPMailer();
1560                include_once("class.db_functions.inc.php");
1561                $db = new db_functions();
1562                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
1563                ##
1564                # @AUTHOR Rodrigo Souza dos Santos
1565                # @DATE 2008/09/17
1566                # @BRIEF Checks if the user has permission to send an email with the email address used.
1567                ##
1568                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
1569                {
1570                        $deny = true;
1571                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
1572                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
1573                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
1574
1575                        if ( $deny )
1576                                return "The server denied your request to send a mail, you cannot use this mail address.";
1577                }
1578
1579                //new_message_to backs to mailto: pattern
1580                $params['body'] = eregi_replace("<a href=\"javascript:new_message_to\('([^>]+)'\)\">[^>]+</a>","<a href='mailto:\\1'>\\1</a>",$params['body']);
1581
1582                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1583                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1584                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1585                $subject = $params['input_subject'];
1586                $msg_uid = $params['msg_id'];
1587                $return_receipt = $params['input_return_receipt'];
1588                $is_important = $params['input_important_message'];
1589        $encrypt = $params['input_return_cripto'];
1590                $signed = $params['input_return_digital'];
1591
1592                if($params['smime'])
1593        {
1594            $body = $params['smime'];
1595            $mail->SMIME = true;
1596            // A MSG assinada deve ser testada neste ponto.
1597            // Testar o certificado e a integridade da msg....
1598            include_once("../security/classes/CertificadoB.php");
1599            $erros_acumulados = '';
1600            $certificado = new certificadoB();
1601            $validade = $certificado->verificar($body);
1602            if(!$validade)
1603            {
1604                foreach($certificado->erros_ssl as $linha_erro)
1605                {
1606                    $erros_acumulados .= $linha_erro;
1607                }
1608            }
1609            else
1610            {
1611                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
1612                if ($certificado->apresentado)
1613                {
1614                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
1615                    if($certificado->dados['CPF'] != $this->username) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
1616                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
1617                }
1618                else
1619                {
1620                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
1621                }
1622            }
1623            if(!$erros_acumulados =='')
1624            {
1625                return $erros_acumulados;
1626            }
1627        }
1628        else
1629        {
1630            $body = $params['body'];
1631        }
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_".$GLOBALS['phpgw']->session->sessionid.".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 = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'];
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_".$GLOBALS['phpgw']->session->sessionid.".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                                                include_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_".$GLOBALS['phpgw']->session->sessionid.".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_".$GLOBALS['phpgw']->session->sessionid;
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.