source: branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php @ 3265

Revision 3265, 138.4 KB checked in by amuller, 14 years ago (diff)

Ticket #1305 - Refresh remove as mensagens que não estão mais na caixa

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