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

Revision 1057, 122.7 KB checked in by amuller, 15 years ago (diff)

Ticket #475 - #559 - Atualização de segurança e adição de tema

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