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

Revision 1940, 134.8 KB checked in by wmerlotto, 14 years ago (diff)

Ticket #890 - Corrigindo assinatura da função get_msg_sample

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