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

Revision 1036, 122.6 KB checked in by amuller, 15 years ago (diff)

Ticket #559 - Atualização de segurança

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