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

Revision 2106, 128.2 KB checked in by niltonneto, 14 years ago (diff)

Ticket #921 - Correção de problema na visualização de mensagem multipart.

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