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

Revision 3250, 139.0 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #783 - Corrige endif tanto no Expresso quanto no Outlook.

  • 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                include_once("class.imap_attachment.inc.php");
1470                $imap_attachment = new imap_attachment();
1471                $folder = $params['folder'];
1472                $msg_range_begin = $params['msg_range_begin'];
1473                $msg_range_end = $params['msg_range_end'];
1474                $msgs_existent = $params['msgs_existent'];
1475                $sort_box_type = $params['sort_box_type'];
1476                $sort_box_reverse = $params['sort_box_reverse'];
1477                $msgs_in_the_server = array();
1478                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1479                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1480                $msgs_in_the_server = array_keys($msgs_in_the_server);
1481                if(!count($msgs_in_the_server))
1482                        return array();
1483
1484                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
1485                $msgs_in_the_client = explode(",", $msgs_existent);
1486
1487                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
1488                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
1489
1490                $msgs_to_exec = array();
1491                if ((count($msg_to_insert)) && ($msgs_existent))
1492                {
1493                        foreach($msg_to_insert as $index => $msg_number)
1494                        {
1495                                if ($msgs_in_the_server[$index+1])
1496                                {
1497                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
1498                                        $msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
1499                                }
1500                                else
1501                                {
1502                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
1503                                        $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1504                                }
1505                        }
1506                        ksort($msgs_to_exec);
1507                }
1508                elseif(!$msgs_existent)
1509                {
1510                        foreach($msgs_in_the_server as $index => $msg_number)
1511                        {
1512                                $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1513                        }
1514                }
1515
1516                $return = array();
1517                $i = 0;
1518                foreach($msgs_to_exec as $msg_number => $command)
1519                {
1520                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
1521                        * atributos do cabeçalho. Como eu preciso do atributo Importance
1522                        * para saber se o email é importante ou não, uso abaixo a função
1523                        * imap_fetchheader e busco o atributo importance nela para passar
1524                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1525                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1526                        * não preciso reimplementar o método utilizando o fetchheader.
1527                        * Como na atualização são poucas as mensagens que devem ser renderizadas,
1528                        * a perda em performance é insignificante.
1529                        */
1530            $tempHeader = @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1531                        $flag = preg_match('/importance *: *(.*)\r/i', $tempHeader, $importance);
1532                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
1533
1534                        $msg_sample = $this->get_msg_sample($msg_number);
1535                        $return[$i]['msg_sample'] = $msg_sample;
1536
1537                        $header = $this->get_header($msg_number);
1538                        if (!is_object($header))
1539                                continue;
1540
1541                        $return[$i]['msg_number']       = $msg_number;
1542                        $return[$i]['command']          = $command;
1543
1544                        $return[$i]['msg_folder']       = $folder;
1545            // Atribui o tipo (normal, signature ou cipher) ao campo Content-Type
1546            $return[$i]['ContentType']  = $this->getMessageType($msg_number, $tempHeader);
1547                        $return[$i]['Recent']           = $header->Recent;
1548                        $return[$i]['Unseen']           = $header->Unseen;
1549                        $return[$i]['Answered']         = $header->Answered;
1550                        $return[$i]['Deleted']          = $header->Deleted;
1551                        $return[$i]['Draft']            = $header->Draft;
1552                        $return[$i]['Flagged']          = $header->Flagged;
1553
1554                        $return[$i]['udate'] = $header->udate;
1555               
1556                        $from = $header->from;
1557                        $return[$i]['from'] = array();
1558                        $tmp = imap_mime_header_decode($from[0]->personal);
1559                        $return[$i]['from']['name'] = $tmp[0]->text;
1560                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
1561                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
1562                        if(!$return[$i]['from']['name'])
1563                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
1564
1565                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1566                        $return[$i]['toaddress'] = '';
1567                        foreach ($toaddress as $tmp)
1568                                $return[$i]['toaddress'] .= $tmp->text;*/
1569                        $to = $header->to;
1570                        $return[$i]['to'] = array();
1571                        $tmp = imap_mime_header_decode($to[0]->personal);
1572                        $return[$i]['to']['name'] = $tmp[0]->text;
1573                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1574                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
1575
1576                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1577
1578                        $return[$i]['Size'] = $header->Size;
1579                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
1580
1581                        $return[$i]['attachment'] = array();
1582                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
1583                        $i++;
1584                }
1585                $return['new_msgs'] = imap_num_recent($this->mbox);
1586                $return['msgs_to_delete'] = $msg_to_delete;
1587                if($this->mbox && is_resource($this->mbox))
1588                        imap_close($this->mbox);
1589
1590                return $return;
1591        }
1592
1593     /**
1594     * Método que faz a verificação do Content-Type do e-mail e verifica se é um e-mail normal,
1595     * assinado ou cifrado.
1596     * @author Mário César Kolling <mario.kolling@serpro.gov.br>
1597     * @param $headers Uma String contendo os Headers do e-mail retornados pela função imap_imap_fetchheader
1598     * @param $msg_number O número da mesagem
1599     * @return Retorna o tipo da mensagem (normal, signature, cipher).
1600     */
1601    function getMessageType($msg_number, $headers = false){
1602
1603            $contentType = "normal";
1604            if (!$headers){
1605                $headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1606            }
1607            //$header2 = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
1608            if (preg_match("/Content-Type:.*pkcs7-signature/i", $headers) == 1){
1609                $contentType = "signature";
1610            } else if (preg_match("/Content-Type:.*x-pkcs7-mime/i", $headers) == 1){
1611                $contentType = "cipher";
1612            }
1613
1614            return $contentType;
1615    }
1616
1617         /**
1618     * Metodo que retorna todas as pastas do usuario logado.
1619     * @param $params array opcional para repassar os argumentos ao metodo.
1620     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
1621     * excluindo as compartilhadas para ele.
1622     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
1623     * folder_id, folder_name, folder_parent e folder_hasChildren.
1624     */
1625        function get_folders_list($params = null)
1626        {
1627                $mbox_stream = $this->open_mbox();
1628                if($params && $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
1629                        $this->delete_mailbox(array("del_past" => "INBOX/decifradas"));
1630                }
1631
1632
1633                $inbox = 'INBOX';
1634                $trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
1635                $drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
1636                $spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
1637                $sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
1638                $uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'];
1639                // Free others requests
1640                session_write_close();
1641
1642                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
1643                $folders_list = imap_getmailboxes($mbox_stream, $serverString, ($params && $params['noSharedFolders']) ? "INBOX/*" : "*");
1644                if ( $params && $params['noSharedFolders'] )
1645                        $folders_list = imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ) + $folders_list;
1646                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1647
1648                $tmp = array();
1649                $resultMine = array();
1650                $resultDefault = array();
1651
1652                if (is_array($folders_list)) {
1653                        reset($folders_list);
1654                        $this->ldap = new ldap_functions();
1655
1656                        $i = 0;
1657                        while (list($key, $val) = each($folders_list)) {
1658                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
1659
1660                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1661                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
1662                                if($tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas') {
1663                                        //error_log('passou', 3,'/tmp/imap_get_list.log');
1664                                        //imap_deletemailbox($mbox_stream,imap_utf7_encode("{".$this->imap_server."}".'INBOX/decifradas'));
1665                                        continue;
1666                                }
1667                                $result[$i]['folder_unseen'] = $status->unseen;
1668                                $folder_id = $tmp_folder_id[1];
1669                                $result[$i]['folder_id'] = $folder_id;
1670
1671                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1672                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1673                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1674                                if ($uid2cn && substr($folder_id,0,4) == 'user') {
1675                                        //$this->ldap = new ldap_functions();
1676                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
1677                                                $result[$i]['folder_name'] = $cn;
1678                                        }
1679                                }
1680
1681                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1682                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
1683
1684                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1685                                        $result[$i]['folder_hasChildren'] = 1;
1686                                else
1687                                        $result[$i]['folder_hasChildren'] = 0;
1688
1689                                switch ($tmp_folder_id[1]) {
1690                                        case $inbox:
1691                                        case $sent:
1692                                        case $drafts:
1693                                        case $spam:
1694                                        case $trash:
1695                                                $resultDefault[]=$result[$i];
1696                                        default:
1697                                                $resultMine[]=$result[$i];
1698                                }
1699
1700                                $i++;
1701                        }
1702                }
1703
1704                // Sorting resultMine
1705                foreach ($resultMine as $folder_info)
1706                {
1707                        $array_tmp[] = $folder_info['folder_id'];
1708                }
1709
1710                natcasesort($array_tmp);
1711
1712                foreach ($array_tmp as $key => $folder_id)
1713                {
1714                        $result2[] = $resultMine[$key];
1715                }
1716               
1717                $resultDefault2=$resultDefault;
1718                // Sorting resultDefault
1719                foreach ($resultDefault as $key => $folder_id)
1720                {
1721
1722                        switch ($resultDefault[$key]['folder_id']) {
1723                                case $inbox:
1724                                        $resultDefault2[0] = $resultDefault[$key];
1725                                        break;
1726                                case $sent:
1727                                        $resultDefault2[1] = $resultDefault[$key];
1728                                        break;
1729                                case $drafts:
1730                                        $resultDefault2[2] = $resultDefault[$key];
1731                                        break;
1732                                case $spam:
1733                                        $resultDefault2[3] = $resultDefault[$key];
1734                                        break;
1735                                case $trash:
1736                                        $resultDefault2[4] = $resultDefault[$key];
1737                                        break;
1738                        }
1739                }
1740
1741                // Merge default folders and mines
1742                $result2 = array_merge($resultDefault2, $result2);
1743               
1744                $current_folder = "INBOX";
1745                if($params && $params['folder'])
1746                        $current_folder = $params['folder'];
1747                return array_merge($result2, $this->get_quota(array('folder_id' => $current_folder)));
1748        }
1749
1750        function create_mailbox($arr)
1751        {
1752                $namebox        = $arr['newp'];
1753                $mbox_stream = $this->open_mbox();
1754                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1755                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
1756
1757                $result = "Ok";
1758                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
1759                {
1760                        $result = implode("<br />\n", imap_errors());
1761                }
1762
1763                if($mbox_stream)
1764                        imap_close($mbox_stream);
1765
1766                return $result;
1767
1768        }
1769
1770        function create_extra_mailbox($arr)
1771        {
1772                $nameboxs = explode(";",$arr['nw_folders']);
1773                $result = "";
1774                $mbox_stream = $this->open_mbox();
1775                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1776                foreach($nameboxs as $key=>$tmp){
1777                        if($tmp != ""){
1778                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1779                                        $result = implode("<br />\n", imap_errors());
1780                                        if($mbox_stream)
1781                                                imap_close($mbox_stream);
1782                                        return $result;
1783                                }
1784                        }
1785                }
1786                if($mbox_stream)
1787                        imap_close($mbox_stream);
1788                return true;
1789        }
1790
1791        function delete_mailbox($arr)
1792        {
1793                $namebox = $arr['del_past'];
1794                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1795                $mbox_stream = $this->mbox ? $this->mbox : $this->open_mbox();
1796                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
1797
1798                $result = "Ok";
1799                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1800                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1801                {
1802                        $result = implode("<br />\n", imap_errors());
1803                }
1804                /*
1805                if($mbox_stream)
1806                        imap_close($mbox_stream);
1807                */
1808                return $result;
1809        }
1810
1811        function ren_mailbox($arr)
1812        {
1813                $namebox = $arr['current'];
1814                $new_box = $arr['rename'];
1815                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1816                $mbox_stream = $this->open_mbox();
1817                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
1818
1819                $result = "Ok";
1820                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1821                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
1822
1823                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1824                {
1825                        $result = imap_errors();
1826                }
1827                if($mbox_stream)
1828                        imap_close($mbox_stream);
1829                return $result;
1830
1831        }
1832
1833        function get_num_msgs($params)
1834        {
1835                $folder = $params['folder'];
1836                if(!$this->mbox || !is_resource($this->mbox)) {
1837                        $this->mbox = $this->open_mbox($folder);
1838                        if(!$this->mbox || !is_resource($this->mbox))
1839                        return imap_last_error();
1840                }
1841                $num_msgs = imap_num_msg($this->mbox);
1842                if($this->mbox && is_resource($this->mbox))
1843                        imap_close($this->mbox);
1844
1845                return $num_msgs;
1846        }
1847
1848        function folder_exists($folder){
1849                $mbox =  $this->open_mbox();
1850                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";           
1851                $list = imap_getmailboxes($mbox,$serverString, $folder);
1852                $return = is_array($list);             
1853                imap_close($mbox);
1854                return $return;
1855        }
1856       
1857        function send_mail($params)
1858        {
1859                include_once("class.phpmailer.php");
1860                $mail = new PHPMailer();
1861                include_once("class.db_functions.inc.php");
1862                $db = new db_functions();
1863                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
1864                ##
1865                # @AUTHOR Rodrigo Souza dos Santos
1866                # @DATE 2008/09/17
1867                # @BRIEF Checks if the user has permission to send an email with the email address used.
1868                ##
1869                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
1870                {
1871                        $deny = true;
1872                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
1873                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
1874                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
1875
1876                        if ( $deny )
1877                                return "The server denied your request to send a mail, you cannot use this mail address.";
1878                }
1879
1880                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1881                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1882                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1883                $subject = $params['input_subject'];
1884                $msg_uid = $params['msg_id'];
1885                $return_receipt = $params['input_return_receipt'];
1886                $is_important = $params['input_important_message'];
1887        $encrypt = $params['input_return_cripto'];
1888                $signed = $params['input_return_digital'];
1889
1890                if($params['smime'])
1891        {
1892            $body = $params['smime'];
1893            $mail->SMIME = true;
1894            // A MSG assinada deve ser testada neste ponto.
1895            // Testar o certificado e a integridade da msg....
1896            include_once("../security/classes/CertificadoB.php");
1897            $erros_acumulados = '';
1898            $certificado = new certificadoB();
1899            $validade = $certificado->verificar($body);
1900            if(!$validade)
1901            {
1902                foreach($certificado->erros_ssl as $linha_erro)
1903                {
1904                    $erros_acumulados .= $linha_erro;
1905                }
1906            }
1907            else
1908            {
1909                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
1910                if ($certificado->apresentado)
1911                {
1912                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
1913                    if($certificado->dados['CPF'] != $this->username) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
1914                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
1915                }
1916                else
1917                {
1918                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
1919                }
1920            }
1921            if(!$erros_acumulados =='')
1922            {
1923                return $erros_acumulados;
1924            }
1925        }
1926        else
1927        {
1928            $body = $params['body'];
1929            //Compatibilização com Outlook, ao encaminhar a mensagem
1930            $body = mb_ereg_replace('<!--\[','<!-- [',$body);
1931        }
1932                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
1933                $attachments = $params['FILES'];
1934                $forwarding_attachments = $params['forwarding_attachments'];
1935                $local_attachments = $params['local_attachments'];
1936               
1937                //Test if must be saved in shared folder and change if necessary
1938                if( $fromaddress[2] == 'y' ){
1939                        //build shared folder path
1940                        $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
1941                        if( $this->folder_exists($newfolder) ) $folder = $newfolder;
1942                        else $folder =  $params['folder'];                     
1943                } else  {
1944                        $folder = $params['folder'];                   
1945                }
1946               
1947                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
1948                $folder_name = $params['folder_name'];
1949                // Fix problem with cyrus delimiter changes.
1950                // Dots in names: enabled/disabled.
1951                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1952                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1953                // End Fix.
1954                if ($folder != 'null'){
1955                        $mail->SaveMessageInFolder = $folder;
1956                }
1957////////////////////////////////////////////////////////////////////////////////////////////////////
1958                $mail->SMTPDebug = false;
1959
1960                if($signed && !$params['smime'])
1961                {
1962            $mail->Mailer = "smime";
1963                        $mail->SignedBody = true;
1964                }
1965                else
1966            $mail->IsSMTP();
1967
1968                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1969                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1970                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1971                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1972                if($fromaddress){
1973                        $mail->Sender = $mail->From;
1974                        $mail->SenderName = $mail->FromName;
1975                        $mail->FromName = $fromaddress[0];
1976                        $mail->From = $fromaddress[1];
1977                }
1978
1979                $this->add_recipients("to", $toaddress, &$mail);
1980                $this->add_recipients("cc", $ccaddress, &$mail);
1981                $this->add_recipients("cco", $ccoaddress, &$mail);
1982                $mail->Subject = $subject;
1983                $mail->IsHTML($params['type'] != 'textplain');
1984                $mail->Body = $body;
1985
1986        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))        // a msg deve ser enviada cifrada...
1987                {
1988                        $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
1989            $email = explode(",",$email);
1990            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
1991            // Deve ser verificado um numero limite de destinatarios.
1992            // Deve ser verificado se os certificados sao validos.
1993            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
1994            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
1995            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
1996            $erros_acumulados = "";
1997            $aux_mails = array();
1998            $mail_list = array();
1999            if(count($email) > $numero_maximo)
2000            {
2001                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
2002                return $erros_acumulados;
2003            }
2004            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
2005            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2006            foreach($email as $item)
2007            {
2008                $certificate = $db->get_certificate(strtolower($item));
2009                if(!$certificate)
2010                {
2011                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
2012                    return $erros_acumulados;
2013                }
2014
2015                if (array_key_exists("dberr1", $certificate))
2016                {
2017
2018                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
2019                    return $erros_acumulados;
2020                                }
2021                if (array_key_exists("dberr2", $certificate))
2022                {
2023                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2024                    //continue;
2025                }
2026                        /*  Retirado este teste para evitar mensagem de erro duplicada.
2027                if (!array_key_exists("certs", $certificate))
2028                {
2029                        $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
2030                    continue;
2031                }
2032            */
2033                include_once("../security/classes/CertificadoB.php");
2034
2035                foreach ($certificate['certs'] as $registro)
2036                {
2037                    $c1 = new certificadoB();
2038                    $c1->certificado($registro['chave_publica']);
2039                    if ($c1->apresentado)
2040                    {
2041                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
2042                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
2043                        {
2044                            $aux_mails[] = $registro['chave_publica'];
2045                            $mail_list[] = strtolower($item);
2046                        }
2047                        else
2048                        {
2049                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
2050                            {
2051                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
2052                                    $c1->dados['EXPIRADO'],$c2->revogado);
2053                            }
2054
2055                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
2056                            foreach($c2->erros_ssl as $linha)
2057                            {
2058                                $erros_acumulados .=  $linha . chr(0x0A);
2059                            }
2060                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
2061                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
2062                        }
2063                    }
2064                    else
2065                    {
2066                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
2067                    }
2068                }
2069                if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
2070                                {
2071                                        return $erros_acumulados;
2072                        }
2073            }
2074
2075            $mail->Certs_crypt = $aux_mails;
2076        }
2077                // Build CID images
2078                $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2079
2080                //      Build Uploading Attachments!!!
2081                if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
2082                {
2083                        $total_uploaded_size = 0;
2084                        $upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
2085                        foreach ($attachments as $attach)
2086                        {
2087                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
2088                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
2089                        }
2090                        if( $total_uploaded_size > $upload_max_filesize)
2091                                return $this->parse_error("message file too big");
2092                }
2093                else if(($params['is_local_forward']=="1") && (count($local_attachments))) { //Caso seja forward de mensagens locais
2094
2095                        $total_uploaded_size = 0;
2096                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
2097                        foreach($local_attachments as $local_attachment) {
2098                                $file_description = unserialize(rawurldecode($local_attachment));
2099                                $tmp = array_values($file_description);
2100                                foreach($file_description as $i => $descriptor){
2101                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2102                                }
2103                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
2104                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
2105                        }
2106                        if( $total_uploaded_size > $upload_max_filesize)
2107                                return 'false';
2108                }
2109////////////////////////////////////////////////////////////////////////////////////////////////////
2110                //      Build Forwarding Attachments!!!
2111                if (count($forwarding_attachments) > 0)
2112                {
2113                        // Bug fixed for array_search function
2114                        $name_cid_files = array();
2115                        if(count($name_cid_files) > 0) {
2116                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
2117                                $name_cid_files[0] = null;
2118                        }
2119
2120                        foreach($forwarding_attachments as $forwarding_attachment)
2121                        {
2122                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
2123                                        $tmp = array_values($file_description);
2124                                        foreach($file_description as $i => $descriptor){
2125                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2126                                        }
2127                                        $file_description = $tmp;
2128                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2129                                        $fileName = $file_description[2];
2130                                        if(!array_search(trim($fileName),$name_cid_files)) {
2131                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2132                                }
2133                        }
2134                }
2135
2136////////////////////////////////////////////////////////////////////////////////////////////////////
2137                // Important message
2138                if($is_important)
2139                        $mail->isImportant();
2140
2141////////////////////////////////////////////////////////////////////////////////////////////////////
2142                // Disposition-Notification-To
2143                if ($return_receipt)
2144                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2145////////////////////////////////////////////////////////////////////////////////////////////////////
2146
2147                $sent = $mail->Send();
2148
2149                if(!$sent)
2150                {
2151                        return $this->parse_error($mail->ErrorInfo);
2152                }
2153                else
2154                {
2155            if ($signed && !$params['smime'])
2156                        {
2157                                return $sent;
2158                        }
2159                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
2160                        {
2161                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2162                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
2163                                $now = date("d/m/y H:i:s");
2164                                $addrs = $toaddress.$ccaddress.$ccoaddress;
2165                                $sent = trim($sent);
2166                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
2167                        }
2168                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
2169                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
2170                                $contacts = new dynamic_contacts();
2171                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
2172                                return array("success" => true, "new_contacts" => $new_contacts);
2173                        }
2174                        return array("success" => true);
2175                }
2176        }
2177        function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments)
2178        {
2179                //      Build CID for embedded Images!!!
2180                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
2181                $cid_imgs = '';
2182                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
2183                $cid_array = array();
2184                foreach($cid_imgs[6] as $j => $val){
2185                        if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
2186                        {
2187                                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
2188                        }
2189                        $cid = $cid_array[$cid_imgs[4][$j].$val]; 
2190                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
2191
2192                        if ($msg_uid != $cid_imgs[4][$j]) // The image is not in the same mail?
2193                        {
2194                                $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
2195                                //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
2196                                $fileName = "image_".($j).".jpg";
2197                                $fileCode = "base64";
2198                                $fileType = "image/jpg";
2199                                $file_attached[0] = $cid_imgs[2][$j];
2200                                $file_attached[1] = $cid_imgs[4][$j];
2201                                $file_attached[2] = $fileName;
2202                                $file_attached[3] = $cid_imgs[6][$j];
2203                                $file_attached[4] = 'base64';
2204                                $file_attached[5] = strlen($fileContent); //Size of file
2205                                $return_forward[] = $file_attached;
2206
2207                                $attachment_ = unserialize(rawurldecode($forwarding_attachments[$cid_imgs[6][$j]-2]));
2208                                if ($file_attached[3] == $attachment_[3])
2209                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);     
2210                        }
2211                        else
2212                        {
2213                                $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
2214                                $file_description = unserialize(rawurldecode($attach_img));
2215                                if (is_array($file_description))
2216                                        foreach($file_description as $i => $descriptor){                                 
2217                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
2218                                        }
2219                                $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
2220                                $fileName = $file_description[2];
2221                                $fileCode = $file_description[4];
2222                                $fileType = $this->get_file_type($file_description[2]);
2223                                unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2224                                if (!empty($file_description))
2225                                {
2226                                        $file_description[5] = strlen($fileContent); //Size of file
2227                                        $return_forward[] = $file_description;
2228                                }
2229                        }
2230                        $tempDir = ini_get("session.save_path");
2231                        $file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                       
2232                        $f = fopen($tempDir.'/'.$file,"w");
2233                        fputs($f,$fileContent);
2234                        fclose($f);
2235                        if ($fileContent)
2236                                $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2237                        //else
2238                        //      return "Error loading image attachment content";                                                 
2239
2240                }
2241                return $return_forward;
2242        }
2243        function add_recipients_cert($full_address)
2244        {
2245                $result = "";
2246                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2247                foreach ($parse_address as $val)
2248                {
2249                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2250                        if ($val->mailbox == "INVALID_ADDRESS")
2251                                continue;
2252                        if ($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS")
2253                                continue;
2254                        if (empty($val->personal))
2255                                $result .= $val->mailbox."@".$val->host . ",";
2256                        else
2257                                $result .= $val->mailbox."@".$val->host . ",";
2258                }
2259
2260                return substr($result,0,-1);
2261        }
2262
2263        function add_recipients($recipient_type, $full_address, $mail)
2264        {
2265                $parse_address = imap_rfc822_parse_adrlist($full_address, "");
2266                foreach ($parse_address as $val)
2267                {
2268                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
2269                        if ($val->mailbox == "INVALID_ADDRESS")
2270                                continue;
2271
2272                        if (empty($val->personal))
2273                        {
2274                                switch($recipient_type)
2275                                {
2276                                        case "to":
2277                                                $mail->AddAddress($val->mailbox."@".$val->host);
2278                                                break;
2279                                        case "cc":
2280                                                $mail->AddCC($val->mailbox."@".$val->host);
2281                                                break;
2282                                        case "cco":
2283                                                $mail->AddBCC($val->mailbox."@".$val->host);
2284                                                break;
2285                                }
2286                        }
2287                        else
2288                        {
2289                                switch($recipient_type)
2290                                {
2291                                        case "to":
2292                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
2293                                                break;
2294                                        case "cc":
2295                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
2296                                                break;
2297                                        case "cco":
2298                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
2299                                                break;
2300                                }
2301                        }
2302                }
2303                return true;
2304        }
2305
2306        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
2307        {
2308                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
2309                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
2310                if($encoding == 'base64')
2311                        # The function imap_base64 adds a new line
2312                        # at ASCII text, with CRLF line terminators.
2313                        # So is being exchanged for base64_decode.
2314                        #
2315                        #$fileContent = imap_base64($fileContent);
2316                        $fileContent = base64_decode($fileContent);
2317                else if($encoding == 'quoted-printable')
2318                        $fileContent = quoted_printable_decode($fileContent);
2319                return $fileContent;
2320        }
2321
2322        function del_last_caracter($string)
2323        {
2324                $string = substr($string,0,(strlen($string) - 1));
2325                return $string;
2326        }
2327
2328        function del_last_two_caracters($string)
2329        {
2330                $string = substr($string,0,(strlen($string) - 2));
2331                return $string;
2332        }
2333
2334        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
2335        {
2336                if ($sort_box_type != "SORTFROM" && $search_box_type!= "FLAGGED"){
2337                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
2338                        foreach($imapsort as $iuid)
2339                                $sort[$iuid] = "";
2340                       
2341                        if ($offsetBegin == -1 && $offsetEnd ==-1 )
2342                                $slice_array = false;
2343                        else
2344                                $slice_array = true;
2345                }
2346                else
2347                {
2348                        $sort = array();
2349                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
2350                        $num_msgs = imap_num_msg($this->mbox);
2351                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
2352                        $slice_array = true;
2353
2354                        for ($i=$num_msgs; $i>0; $i--)
2355                        {
2356                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
2357                                        break;
2358                                $iuid = @imap_uid($this->mbox,$i);
2359                                $header = $this->get_header($iuid);
2360                                // List UNSEEN messages.
2361                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
2362                                        continue;
2363                                }
2364                                // List SEEN messages.
2365                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
2366                                        continue;
2367                                }
2368                                // List ANSWERED messages.
2369                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
2370                                        continue;
2371                                }
2372                                // List FLAGGED messages.
2373                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
2374                                        continue;
2375                                }
2376
2377                                if($sort_box_type=='SORTFROM') {
2378                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
2379                                                $from = $header->to;
2380                                        else
2381                                                $from = $header->from;
2382
2383                                        $tmp = imap_mime_header_decode($from[0]->personal);
2384
2385                                        if ($tmp[0]->text != "")
2386                                                $sort[$iuid] = $tmp[0]->text;
2387                                        else
2388                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
2389                                }
2390                                else if($sort_box_type=='SORTSUBJECT') {
2391                                        $sort[$iuid] = $header->subject;
2392                                }
2393                                else if($sort_box_type=='SORTSIZE') {
2394                                        $sort[$iuid] = $header->Size;
2395                                }
2396                                else {
2397                                        $sort[$iuid] = $header->udate;
2398                                }
2399
2400                        }
2401                        natcasesort($sort);
2402
2403                        if ($sort_box_reverse)
2404                                $sort = array_reverse($sort,true);
2405                }
2406
2407                if(!is_array($sort))
2408                        $sort = array();
2409
2410
2411                if ($slice_array)
2412                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
2413
2414
2415                return $sort;
2416
2417        }
2418
2419
2420        function move_search_messages($params){
2421                $params['selected_messages'] = urldecode($params['selected_messages']);
2422                $params['new_folder'] = urldecode($params['new_folder']);
2423                $params['new_folder_name'] = urldecode($params['new_folder_name']);
2424                $sel_msgs = explode(",", $params['selected_messages']);
2425                @reset($sel_msgs);
2426                $sorted_msgs = array();
2427                foreach($sel_msgs as $idx => $sel_msg) {
2428                        $sel_msg = explode(";", $sel_msg);
2429                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
2430                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
2431                         }
2432                         else {
2433                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
2434                         }
2435                }
2436                @ksort($sorted_msgs);
2437                $last_return = false;
2438                foreach($sorted_msgs as $folder => $msgs_number) {
2439                        $params['msgs_number'] = $msgs_number;
2440                        $params['folder'] = $folder;
2441                        if($params['new_folder'] && $folder != $params['new_folder']){
2442                                $last_return = $this -> move_messages($params);
2443                        }
2444                        elseif(!$params['new_folder'] || $params['delete'] ){
2445                                $last_return = $this -> delete_msgs($params);
2446                                $last_return['deleted'] = true;
2447                        }
2448                }
2449                return $last_return;
2450        }
2451
2452        function move_messages($params)
2453        {
2454                $folder = $params['folder'];
2455                $mbox_stream = $this->open_mbox($folder);
2456                $newmailbox = ($params['new_folder']);
2457                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
2458                $new_folder_name = $params['new_folder_name'];
2459                $msgs_number = $params['msgs_number'];
2460                $return = array('msgs_number' => $msgs_number,
2461                                                'folder' => $folder,
2462                                                'new_folder_name' => $new_folder_name,
2463                                                'border_ID' => $params['border_ID'],
2464                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
2465
2466                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
2467        if (substr($folder,0,4) == 'user'){
2468                $acl = $this->getacltouser($folder);
2469                /*
2470                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
2471                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
2472                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
2473                 *   w - write (STORE flags other than SEEN and DELETED)
2474                 *   i - insert (perform APPEND, COPY into mailbox)
2475                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
2476                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
2477                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
2478                 *   a - administer (perform SETACL)
2479                        */
2480                        if (strpos($acl, "d") === false){
2481                                $return['status'] = false;
2482                                return $return;
2483                        }
2484        }
2485        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
2486        if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
2487            if (substr($new_folder_name,0,4) == 'user'){
2488                $this->ldap = new ldap_functions();
2489                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
2490                $return['new_folder_name'] = array_pop($tmp_folder_name);
2491                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
2492                {
2493                    $return['new_folder_name'] = $cn;
2494                }
2495            }
2496        }
2497
2498                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
2499                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
2500                {
2501                        $return['previous_msg'] = $this->get_info_previous_msg($params);
2502                        // Fix problem in unserialize function JS.
2503                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
2504                }
2505
2506                $mbox_stream = $this->open_mbox($folder);
2507                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2508                        imap_expunge($mbox_stream);
2509                        if($mbox_stream)
2510                                imap_close($mbox_stream);
2511                        return $return;
2512                }else {
2513                        if(strstr(imap_last_error(),'Over quota')) {
2514                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
2515                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
2516                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2517                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2518                                $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()))));
2519                                if(!$mbox)
2520                                        return imap_last_error();
2521                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");
2522                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
2523                                        if($mbox_stream)
2524                                                imap_close($mbox_stream);
2525                                        if($mbox)
2526                                                imap_close($mbox);
2527                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
2528                                }
2529                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
2530                                        imap_expunge($mbox_stream);
2531                                        if($mbox_stream)
2532                                                imap_close($mbox_stream);
2533                                        // return to original quota limit.
2534                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2535                                                if($mbox)
2536                                                        imap_close($mbox);
2537                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2538                                        }
2539                                        return $return;
2540                                }
2541                                else {
2542                                        if($mbox_stream)
2543                                                imap_close($mbox_stream);
2544                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
2545                                                if($mbox)
2546                                                        imap_close($mbox);
2547                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
2548                                        }
2549                                        return imap_last_error();
2550                                }
2551
2552                        }
2553                        else {
2554                                if($mbox_stream)
2555                                        imap_close($mbox_stream);
2556                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
2557                        }
2558                }
2559        }
2560
2561        function save_msg($params)
2562        {
2563
2564                include_once("class.phpmailer.php");
2565                $mail = new PHPMailer();
2566                include_once("class.db_functions.inc.php");
2567                $toaddress = $params['input_to'];
2568                $ccaddress = $params['input_cc'];
2569                $ccoaddress = $params['input_cco'];
2570                $subject = $params['input_subject'];
2571                $msg_uid = $params['msg_id'];
2572                $body = $params['body'];
2573                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
2574                $body = preg_replace("/\n/"," ",$body);
2575                $body = preg_replace("/\r/","",$body);
2576                $forwarding_attachments = $params['forwarding_attachments'];
2577                $attachments = $params['FILES'];
2578                $return_files = $params['FILES'];
2579
2580                $folder = $params['folder'];
2581                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
2582                // Fix problem with cyrus delimiter changes.
2583                // Dots in names: enabled/disabled.
2584                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
2585                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
2586                // End Fix.
2587                if(strtoupper($folder) == 'INBOX/DRAFTS')
2588                    {
2589                        $mail->SaveMessageAsDraft = $folder;
2590                    }
2591                $mail->SaveMessageInFolder = $folder;
2592                $mail->SMTPDebug = false;
2593
2594                $mail->IsSMTP();
2595                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2596                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2597                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2598                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2599
2600                $mail->Sender = $mail->From;
2601                $mail->SenderName = $mail->FromName;
2602                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2603                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
2604
2605                $this->add_recipients("to", $toaddress, &$mail);
2606                $this->add_recipients("cc", $ccaddress, &$mail);
2607                $this->add_recipients("cco", $ccoaddress, &$mail);
2608                $mail->Subject = $subject;
2609                $mail->IsHTML(true);
2610                $mail->Body = $body;
2611
2612                $return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
2613
2614        //      Build Forwarding Attachments!!!
2615                if (count($forwarding_attachments) > 0)
2616                {
2617                        foreach($forwarding_attachments as $forwarding_attachment)
2618                        {
2619                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2620                                $tmp = array_values($file_description);
2621                                foreach($file_description as $i => $descriptor){
2622                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2623                                }
2624                                $file_description = $tmp;
2625
2626                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2627                                $fileName = $file_description[2];
2628
2629                                $file_description[5] = strlen($fileContent); //Size of file
2630                                $return_forward[] = $file_description;
2631
2632                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2633                        }
2634                }
2635
2636                if ((count($return_forward) > 0) && (count($return_files) > 0))
2637                        $return_files = array_merge_recursive($return_forward,$return_files);
2638                else
2639                        if (count($return_files) < 1)
2640                                $return_files = $return_forward;
2641
2642                //      Build Uploading Attachments!!!
2643                $sizeof_attachments = count($attachments);
2644                if ($sizeof_attachments)
2645                        foreach ($attachments as $numb => $attach){
2646                                if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
2647                                        list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
2648                                        switch ($image_type)
2649                                        {
2650                                        // Do not corrupt animated gif
2651                                        //case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
2652                                        case 2: $image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
2653                                        case 3: $image_big = imagecreatefrompng($attach['tmp_name']); break;
2654                                        case 6:
2655                                                require_once("gd_functions.php");
2656                                                $image_big = imagecreatefrombmp($attach['tmp_name']); break;
2657                                        default:
2658                                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2659                                                break;
2660                                        }
2661                                        header('Content-type: image/jpeg');
2662                                        $max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
2663                                        $max_resolution = ($max_resolution==""?'65536':$max_resolution);
2664                                        if ($width < $max_resolution && $height < $max_resolution){
2665                                                $new_width = $width;
2666                                                $new_height = $height;
2667                                        }
2668                                        else if ($width > $max_resolution){
2669                                                $new_width = $max_resolution;
2670                                                $new_height = $height*($new_width/$width);
2671                                        }
2672                                        else {
2673                                                $new_height = $max_resolution;
2674                                                $new_width = $width*($new_height/$height);
2675                                        }
2676                                        $image_new = imagecreatetruecolor($new_width, $new_height);
2677                                        imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
2678                                        $tmpDir = ini_get("session.save_path");
2679                                        $_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
2680                                        imagejpeg($image_new,$tmpDir.$_file, 85);
2681                                        $mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
2682                                }
2683                                else
2684                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
2685                                // optional name
2686                                }
2687
2688
2689
2690
2691                if(!empty($mail->AltBody))
2692            $mail->ContentType = "multipart/alternative";
2693
2694                $mail->error_count = 0; // reset errors
2695                $mail->SetMessageType();
2696                $header = $mail->CreateHeader();
2697                $body = $mail->CreateBody();
2698
2699                $mbox_stream = $this->open_mbox($folder);
2700                $new_header = str_replace("\n", "\r\n", $header);
2701                $new_body = str_replace("\n", "\r\n", $body);
2702                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2703                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2704                $return['msg_no'] = $status->uidnext - 1;
2705                $return['folder_id'] = $folder;
2706
2707                if($mbox_stream)
2708                        imap_close($mbox_stream);
2709                if (is_array($return_files))
2710                        foreach ($return_files as $index => $_attachment) {
2711                                if (array_key_exists("name",$_attachment)){
2712                                unset($return_files[$index]);
2713                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2714                        }
2715                        else
2716                        {
2717                                unset($return_files[$index]);
2718                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2719                        }
2720                }
2721
2722                $return['files'] = serialize($return_files);
2723                $return["subject"] = $subject;
2724
2725                if (!$return['append'])
2726                        $return['append'] = imap_last_error();
2727
2728                return $return;
2729        }
2730
2731        function set_messages_flag($params)
2732        {
2733                $folder = $params['folder'];
2734                $msgs_to_set = $params['msgs_to_set'];
2735                $flag = $params['flag'];
2736                $return = array();
2737                $return["msgs_to_set"] = $msgs_to_set;
2738                $return["flag"] = $flag;
2739
2740                if(!$this->mbox && !is_resource($this->mbox))
2741                        $this->mbox = $this->open_mbox($folder);
2742
2743                if ($flag == "unseen")
2744                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2745                elseif ($flag == "seen")
2746                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2747                elseif ($flag == "answered"){
2748                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2749                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2750                }
2751                elseif ($flag == "forwarded")
2752                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2753                elseif ($flag == "flagged")
2754                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2755                elseif ($flag == "unflagged") {
2756                        $flag_importance = false;
2757                        $msgs_number = explode(",",$msgs_to_set);
2758                        $unflagged_msgs = "";
2759                        foreach($msgs_number as $msg_number) {
2760                                preg_match('/importance *: *(.*)\r/i',
2761                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2762                                        ,$importance);
2763                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2764                                        $flag_importance=true;
2765                                }
2766                                else {
2767                                        $unflagged_msgs.=$msg_number.",";
2768                                }
2769                        }
2770
2771                        if($unflagged_msgs!="") {
2772                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2773                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2774                        }
2775                        else {
2776                                $return["msgs_unflageds"] = false;
2777                        }
2778
2779                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2780                                $return["status"] = false;
2781                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2782                        }
2783                        else {
2784                                $return["status"] = true;
2785                        }
2786                }
2787
2788                if($this->mbox && is_resource($this->mbox))
2789                        imap_close($this->mbox);
2790                return $return;
2791        }
2792
2793        function get_file_type($file_name)
2794        {
2795                $file_name = strtolower($file_name);
2796                $strFileType = strrev(substr(strrev($file_name),0,4));
2797                if ($strFileType == ".asf")
2798                        return "video/x-ms-asf";
2799                if ($strFileType == ".avi")
2800                        return "video/avi";
2801                if ($strFileType == ".doc")
2802                        return "application/msword";
2803                if ($strFileType == ".zip")
2804                        return "application/zip";
2805                if ($strFileType == ".xls")
2806                        return "application/vnd.ms-excel";
2807                if ($strFileType == ".gif")
2808                        return "image/gif";
2809                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2810                        return "image/jpeg";
2811                if ($strFileType == ".png")
2812                        return "image/png";
2813                if ($strFileType == ".wav")
2814                        return "audio/wav";
2815                if ($strFileType == ".mp3")
2816                        return "audio/mpeg3";
2817                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2818                        return "video/mpeg";
2819                if ($strFileType == ".rtf")
2820                        return "application/rtf";
2821                if ($strFileType == ".htm" || $strFileType == "html")
2822                        return "text/html";
2823                if ($strFileType == ".xml")
2824                        return "text/xml";
2825                if ($strFileType == ".xsl")
2826                        return "text/xsl";
2827                if ($strFileType == ".css")
2828                        return "text/css";
2829                if ($strFileType == ".php")
2830                        return "text/php";
2831                if ($strFileType == ".asp")
2832                        return "text/asp";
2833                if ($strFileType == ".pdf")
2834                        return "application/pdf";
2835                if ($strFileType == ".txt")
2836                        return "text/plain";
2837                if ($strFileType == ".wmv")
2838                        return "video/x-ms-wmv";
2839                if ($strFileType == ".sxc")
2840                        return "application/vnd.sun.xml.calc";
2841                if ($strFileType == ".stc")
2842                        return "application/vnd.sun.xml.calc.template";
2843                if ($strFileType == ".sxd")
2844                        return "application/vnd.sun.xml.draw";
2845                if ($strFileType == ".std")
2846                        return "application/vnd.sun.xml.draw.template";
2847                if ($strFileType == ".sxi")
2848                        return "application/vnd.sun.xml.impress";
2849                if ($strFileType == ".sti")
2850                        return "application/vnd.sun.xml.impress.template";
2851                if ($strFileType == ".sxm")
2852                        return "application/vnd.sun.xml.math";
2853                if ($strFileType == ".sxw")
2854                        return "application/vnd.sun.xml.writer";
2855                if ($strFileType == ".sxq")
2856                        return "application/vnd.sun.xml.writer.global";
2857                if ($strFileType == ".stw")
2858                        return "application/vnd.sun.xml.writer.template";
2859
2860
2861                return "application/octet-stream";
2862        }
2863
2864        function htmlspecialchars_encode($str)
2865        {
2866                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
2867        }
2868        function htmlspecialchars_decode($str)
2869        {
2870                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
2871        }
2872
2873        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2874        {
2875                if(!$this->mbox || !is_resource($this->mbox))
2876                        $this->mbox = $this->open_mbox($folder);
2877
2878                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2879        }
2880
2881        function get_info_next_msg($params)
2882        {
2883                $msg_number = $params['msg_number'];
2884                $folder = $params['msg_folder'];
2885                $sort_box_type = $params['sort_box_type'];
2886                $sort_box_reverse = $params['sort_box_reverse'];
2887                $reuse_border = $params['reuse_border'];
2888                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2889                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2890
2891                $success = false;
2892                if (is_array($sort_array_msg))
2893                {
2894                        foreach ($sort_array_msg as $i => $value){
2895                                if ($value == $msg_number)
2896                                {
2897                                        $success = true;
2898                                        break;
2899                                }
2900                        }
2901                }
2902
2903                if (! $success || $i >= sizeof($sort_array_msg)-1)
2904                {
2905                        $params['status'] = 'false';
2906                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2907                        return $params;
2908                }
2909
2910                $params = array();
2911                $params['msg_number'] = $sort_array_msg[($i+1)];
2912                $params['msg_folder'] = $folder;
2913
2914                $return = $this->get_info_msg($params);
2915                $return["reuse_border"] = $reuse_border;
2916                return $return;
2917        }
2918
2919        function get_info_previous_msg($params)
2920        {
2921                $msg_number = $params['msgs_number'];
2922                $folder = $params['folder'];
2923                $sort_box_type = $params['sort_box_type'];
2924                $sort_box_reverse = $params['sort_box_reverse'];
2925                $reuse_border = $params['reuse_border'];
2926                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2927                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2928
2929                $success = false;
2930                if (is_array($sort_array_msg))
2931                {
2932                        foreach ($sort_array_msg as $i => $value){
2933                                if ($value == $msg_number)
2934                                {
2935                                        $success = true;
2936                                        break;
2937                                }
2938                        }
2939                }
2940                if (! $success || $i == 0)
2941                {
2942                        $params['status'] = 'false';
2943                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2944                        return $params;
2945                }
2946
2947                $params = array();
2948                $params['msg_number'] = $sort_array_msg[($i-1)];
2949                $params['msg_folder'] = $folder;
2950
2951                $return = $this->get_info_msg($params);
2952                $return["reuse_border"] = $reuse_border;
2953                return $return;
2954        }
2955
2956        // This function updates the values: quota, paging and new messages menu.
2957        function get_menu_values($params){
2958                $return_array = array();
2959                $return_array = $this->get_quota($params);
2960
2961                $mbox_stream = $this->open_mbox($params['folder']);
2962                $return_array['num_msgs'] = imap_num_msg($mbox_stream);
2963                if($mbox_stream)
2964                        imap_close($mbox_stream);
2965
2966                return $return_array;
2967        }
2968
2969        function get_quota($params){
2970                // folder_id = user/{uid} for shared folders
2971                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
2972                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
2973                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];
2974                }
2975                // folder_id = INBOX for inbox folders
2976                else
2977                        $folder_id = "INBOX";
2978
2979                if(!$this->mbox || !is_resource($this->mbox))
2980                        $this->mbox = $this->open_mbox();
2981
2982                $quota = imap_get_quotaroot($this->mbox, $folder_id);
2983                if($this->mbox && is_resource($this->mbox))
2984                        imap_close($this->mbox);
2985
2986                if (!$quota){
2987                        return array(
2988                                'quota_percent' => 0,
2989                                'quota_used' => 0,
2990                                'quota_limit' =>  0
2991                        );
2992                }
2993
2994                if(count($quota) && $quota['limit']) {
2995                        $quota_limit = $quota['limit'];
2996                        $quota_used  = $quota['usage'];
2997                        if($quota_used >= $quota_limit)
2998                        {
2999                                $quotaPercent = 100;
3000                        }
3001                        else
3002                        {
3003                        $quotaPercent = ($quota_used / $quota_limit)*100;
3004                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
3005                        }
3006                        return array(
3007                                'quota_percent' => floor($quotaPercent),
3008                                'quota_used' => $quota_used,
3009                                'quota_limit' =>  $quota_limit
3010                        );
3011                }
3012                else
3013                        return array();
3014        }
3015
3016        function send_notification($params){
3017                include("../header.inc.php");
3018                require_once("class.phpmailer.php");
3019                $mail = new PHPMailer();
3020
3021                $toaddress = $params['notificationto'];
3022
3023                $subject = lang("Read receipt: %1",$params['subject']);
3024                $body = lang("Your message: %1",$params['subject']) . '<br>';
3025                $body .= lang("Received in: %1",$params['date']) . '<br>';
3026                $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"));
3027                $mail->SMTPDebug = false;
3028                $mail->IsSMTP();
3029                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
3030                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
3031                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3032                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
3033                $mail->AddAddress($toaddress);
3034                $mail->Subject = $this->htmlspecialchars_decode($subject);
3035
3036                $mail->IsHTML(true);
3037                $mail->Body = $body;
3038
3039                if(!$mail->Send()){
3040                        return $mail->ErrorInfo;
3041                }
3042                else
3043                        return true;
3044        }
3045
3046        function empty_folder($params)
3047        {
3048                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server'][$params['clean_folder']];
3049                $mbox_stream = $this->open_mbox($folder);
3050                $return = imap_delete($mbox_stream,'1:*');
3051                if($mbox_stream)
3052                        imap_close($mbox_stream, CL_EXPUNGE);
3053                return $return;
3054        }
3055
3056        function search($params)
3057        {
3058                include("class.imap_attachment.inc.php");
3059                $imap_attachment = new imap_attachment();
3060                $criteria = $params['criteria'];
3061                $return = array();
3062                $folders = $this->get_folders_list();
3063
3064                $j = 0;
3065                foreach($folders as $folder)
3066                {
3067                        $mbox_stream = $this->open_mbox($folder);
3068                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
3069
3070                        if ($messages == '')
3071                                continue;
3072
3073                        $i = 0;
3074                        $return[$j] = array();
3075                        $return[$j]['folder_name'] = $folder['name'];
3076
3077                        foreach($messages as $msg_number)
3078                        {
3079                                $header = $this->get_header($msg_number);
3080                                if (!is_object($header))
3081                                        return false;
3082
3083                                $return[$j][$i]['msg_folder']   = $folder['name'];
3084                                $return[$j][$i]['msg_number']   = $msg_number;
3085                                $return[$j][$i]['Recent']               = $header->Recent;
3086                                $return[$j][$i]['Unseen']               = $header->Unseen;
3087                                $return[$j][$i]['Answered']     = $header->Answered;
3088                                $return[$j][$i]['Deleted']              = $header->Deleted;
3089                                $return[$j][$i]['Draft']                = $header->Draft;
3090                                $return[$j][$i]['Flagged']              = $header->Flagged;
3091
3092                                $date_msg = gmdate("d/m/Y",$header->udate);
3093                                if (gmdate("d/m/Y") == $date_msg)
3094                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
3095                                else
3096                                        $return[$j][$i]['udate'] = $date_msg;
3097
3098                                $fromaddress = imap_mime_header_decode($header->fromaddress);
3099                                $return[$j][$i]['fromaddress'] = '';
3100                                foreach ($fromaddress as $tmp)
3101                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
3102
3103                                $from = $header->from;
3104                                $return[$j][$i]['from'] = array();
3105                                $tmp = imap_mime_header_decode($from[0]->personal);
3106                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
3107                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
3108                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
3109
3110                                $to = $header->to;
3111                                $return[$j][$i]['to'] = array();
3112                                $tmp = imap_mime_header_decode($to[0]->personal);
3113                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
3114                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
3115                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
3116
3117                                $subject = imap_mime_header_decode($header->fetchsubject);
3118                                $return[$j][$i]['subject'] = '';
3119                                foreach ($subject as $tmp)
3120                                        $return[$j][$i]['subject'] .= $tmp->text;
3121
3122                                $return[$j][$i]['Size'] = $header->Size;
3123                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
3124
3125                                $return[$j][$i]['attachment'] = array();
3126                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
3127
3128                                $i++;
3129                        }
3130                        $j++;
3131                        if($mbox_stream)
3132                                imap_close($mbox_stream);
3133                }
3134
3135                return $return;
3136        }
3137       
3138       
3139        function mobile_search($params)
3140        {
3141                include("class.imap_attachment.inc.php");
3142                $imap_attachment = new imap_attachment();
3143                $criterias = array ("TO","SUBJECT","FROM","CC");
3144                $return = array();
3145                $folders = $this->get_folders_list();
3146                $num_msgs = 0;
3147                                         
3148                foreach($folders as $id =>$folder)
3149                {
3150                        if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
3151                                foreach($criterias as $criteria_fixed)
3152                    {
3153                        $_filter = $criteria_fixed . ' "'.$params['filter'].'"';
3154                                        $mbox_stream = $this->open_mbox($folder['folder_name']);
3155       
3156                                        $messages = imap_search($mbox_stream, $_filter, SE_UID);
3157                                       
3158                                        if ($messages == ''){
3159                                                if($mbox_stream)
3160                                                        imap_close($mbox_stream);
3161                                                continue;       
3162                                        }
3163                                                                       
3164                                        foreach($messages as $msg_number)
3165                                        {                                       
3166                                                $temp = $this->get_info_head_msg($msg_number);
3167                                                if(!$temp)
3168                                                        return false;
3169               
3170                                                $return[$num_msgs] = $temp;
3171                                                $num_msgs++;
3172                                        }
3173                                        $return['num_msgs'] = $num_msgs;
3174                                       
3175                                        if($mbox_stream)
3176                                                imap_close($mbox_stream);
3177                                }
3178                        }
3179                               
3180                }
3181                return $return;
3182        }
3183
3184        function delete_and_show_previous_message($params)
3185        {
3186                $return = $this->get_info_previous_msg($params);
3187
3188                $params_tmp1 = array();
3189                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
3190                $params_tmp1['folder'] = $params['msg_folder'];
3191                $return_tmp1 = $this->delete_msg($params_tmp1);
3192
3193                $return['msg_number_deleted'] = $return_tmp1;
3194
3195                return $return;
3196        }
3197
3198
3199        function automatic_trash_cleanness($params)
3200        {
3201                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
3202                $criteria =  'BEFORE "'.$before_date.'"';
3203                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
3204                // Free others requests
3205                session_write_close();
3206                $messages = imap_search($mbox_stream, $criteria, SE_UID);
3207                if (is_array($messages)){
3208                        foreach ($messages as $msg_number){
3209                                imap_delete($mbox_stream, $msg_number, FT_UID);
3210                        }
3211                }
3212                if($mbox_stream)
3213                        imap_close($mbox_stream, CL_EXPUNGE);
3214                return $messages;
3215        }
3216//      Fix the search problem with special characters!!!!
3217        function remove_accents($string) {
3218                return strtr($string,
3219                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
3220                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
3221        }
3222
3223        function make_search_date($date){
3224
3225            $months = array(
3226                1   => 'jan',
3227                2   => 'feb',
3228                3   => 'mar',
3229                4   => 'apr',
3230                5   => 'may',
3231                6   => 'jun',
3232                7   => 'jul',
3233                8   => 'aug',
3234                9   => 'sep',
3235                10  => 'oct',
3236                11  => 'nov',
3237                12  => 'dec'
3238            );
3239
3240            //TODO: Adaptar a data de acordo com o locale do sistema.
3241            list($day,$month,$year) = explode("/", $date);
3242            $search_date = $day."-".$months[intval($month)]."-".$year;
3243            return $search_date;
3244
3245        }
3246
3247        function search_msg($params = ''){
3248            $mbox_stream = "";
3249            if(strpos($params['condition'],"#")===false) { //local messages? It shouldn't be necessary, should it? FIXME
3250                    $search=false;
3251            }
3252            else {
3253                    $search = explode(",",$params['condition']);
3254            }
3255            $params['page'] = $params['page']*1;
3256
3257            if(is_array($search)){
3258                $search = array_unique($search); // Remove duplicated folders
3259                $search_criteria = '';
3260                $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
3261                foreach($search as $tmp)
3262                {
3263                    $tmp1 = explode("##",$tmp);
3264                    $sum = 0;
3265                    $name_box = $tmp1[0];
3266                    unset($filter);
3267                    foreach($tmp1 as $index => $criteria)
3268                    {
3269                        if ($index != 0 && strlen($criteria) != 0)
3270                        {
3271                            $filter_array = explode("<=>",rawurldecode($criteria));
3272                            $filter .= " ".$filter_array[0];
3273                            if (strlen($filter_array[1]) != 0){
3274                                if (trim($filter_array[0]) != 'BEFORE' &&
3275                                    trim($filter_array[0]) != 'SINCE' &&
3276                                    trim($filter_array[0]) != 'ON')
3277                                {
3278                                    $filter .= '"'.$filter_array[1].'"';
3279                                }
3280                                else
3281                                    {
3282                                        $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
3283                                    }
3284                            }
3285                        }
3286                    }
3287                    $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3288                    $filter = $this->remove_accents($filter);
3289                    //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
3290                    if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
3291                    {
3292                        $folder_name = explode($this->imap_delimiter,$name_box);
3293                        $this->ldap = new ldap_functions();
3294                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
3295                        {
3296                            $folder_name[1] = $cn;
3297                        }
3298                        $folder_name = implode($this->imap_delimiter,$folder_name);
3299                    }
3300                    else
3301                    {
3302                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
3303                    }
3304
3305                    if(!is_resource($mbox_stream))
3306                    {
3307                        $mbox_stream = $this->open_mbox($name_box);
3308                    }
3309                    else
3310                        {
3311                            imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
3312                        }
3313
3314                    if (preg_match("/^.?\bALL\b/", $filter))
3315                    { // Quick Search, note: this ALL isn't the same ALL from imap_search
3316
3317                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
3318                        foreach($all_criterias as $criteria_fixed)
3319                        {
3320                            $_filter = $criteria_fixed . substr($filter,4);
3321
3322                            $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
3323
3324                            if(is_array($search_criteria))
3325                            {
3326                                foreach($search_criteria as $new_search)
3327                                {
3328                                    $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3329                                    $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
3330                                    $elem['uid'] = $new_search;
3331                                    $retorno[] = $elem;
3332                                }
3333                            }
3334                        }
3335                    }
3336                    else {
3337                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
3338                        if( is_array( $search_criteria) )
3339                        {
3340                            foreach($search_criteria as $new_search)
3341                            {
3342                                    $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
3343                                    $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
3344                                    $elem['uid'] = $new_search;
3345                                    $retorno[] = $elem;
3346                            }
3347                        }
3348                    }
3349                }
3350            }
3351            if($mbox_stream)
3352            {
3353                imap_close($mbox_stream);
3354            }
3355            $num_msgs = count($retorno);
3356
3357            /* Comparison functions, descendent is ascendent with parms inverted */
3358            function SORTDATE($a, $b) { return ($a['udate'] < $b['udate']); }
3359            function SORTDATE_REVERSE($b, $a) { return SORTDATE($a,$b); }
3360
3361            function SORTWHO($a, $b) { return (strtoupper($a['from']) > strtoupper($b['from'])); }
3362            function SORTWHO_REVERSE($b, $a) { return SORTWHO($a,$b); }
3363
3364            function SORTSUBJECT($a, $b) { return (strtoupper($a['subject']) > strtoupper($b['subject'])); }
3365            function SORTSUBJECT_REVERSE($b, $a) { return SORTSUBJECT($a,$b); }
3366
3367            function SORTBOX($a, $b) { return ($a['boxname'] > $b['boxname']); }
3368            function SORTBOX_REVERSE($b, $a) { return SORTBOX($a,$b); }
3369
3370            function SORTSIZE($a, $b) { return ($a['size'] > $b['size']); }
3371            function SORTSIZE_REVERSE($b, $a) { return SORTSIZE($a,$b); }
3372
3373            usort($retorno, $params['sort_type']);
3374            $pageret = array_slice($retorno, $params['page'] * $this->prefs['max_email_per_page'], $this->prefs['max_email_per_page']);
3375            $arrayRetorno['num_msgs'] =  $num_msgs;
3376            $arrayRetorno['data'] =  $pageret;
3377
3378            if ($pageret)
3379            {
3380                return $arrayRetorno;
3381            }
3382            else
3383            {
3384                return 'none';
3385            }
3386        }
3387
3388        function get_msg_detail($uid_msg,$name_box, $mbox_stream )
3389        {
3390                $header = $this->get_header($uid_msg);
3391                require_once("class.imap_attachment.inc.php");
3392                $imap_attachment = new imap_attachment();
3393                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
3394                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
3395                $flag = $header->Unseen
3396                        .$header->Recent
3397                        .$header->Flagged
3398                        .$header->Draft
3399                        .$header->Answered
3400                        .$header->Deleted
3401                        .$attachments;
3402
3403
3404                $subject = $this->decode_string($header->fetchsubject);
3405                $from = $header->from[0]->mailbox;
3406                if($header->from[0]->personal != "")
3407                        $from = $header->from[0]->personal;
3408                $ret_msg['from'] = $this->decode_string($from);
3409                $ret_msg['subject'] = $subject;
3410                $ret_msg['udate'] = $header ->udate;
3411                $ret_msg['size'] = $header->Size;
3412                $ret_msg['flag'] = $flag;
3413                return $ret_msg;
3414        }
3415        function ob_array($the_object)
3416        {
3417           $the_array=array();
3418           if(!is_scalar($the_object))
3419           {
3420               foreach($the_object as $id => $object)
3421               {
3422                   if(is_scalar($object))
3423                   {
3424                       $the_array[$id]=$object;
3425                   }
3426                   else
3427                   {
3428                       $the_array[$id]=$this->ob_array($object);
3429                   }
3430               }
3431               return $the_array;
3432           }
3433           else
3434           {
3435               return $the_object;
3436           }
3437        }
3438
3439        function getacl()
3440        {
3441                $this->ldap = new ldap_functions();
3442
3443                $return = array();
3444                $mbox_stream = $this->open_mbox();
3445                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3446
3447                $i = 0;
3448                foreach ($mbox_acl as $user => $acl)
3449                {
3450                        if ($user != $this->username)
3451                        {
3452                                $return[$i]['uid'] = $user;
3453                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
3454                        }
3455                        $i++;
3456                }
3457                return $return;
3458        }
3459
3460        function setacl($params)
3461        {
3462                $old_users = $this->getacl();
3463                if (!count($old_users))
3464                        $old_users = array();
3465
3466                $tmp_array = array();
3467                foreach ($old_users as $index => $user_info)
3468                {
3469                        $tmp_array[$index] = $user_info['uid'];
3470                }
3471                $old_users = $tmp_array;
3472
3473                $users = unserialize($params['users']);
3474                if (!count($users))
3475                        $users = array();
3476
3477                //$add_share = array_diff($users, $old_users);
3478                $remove_share = array_diff($old_users, $users);
3479
3480                $mbox_stream = $this->open_mbox();
3481
3482                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3483                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3484
3485                /*if (count($add_share))
3486                {
3487                        foreach ($add_share as $index=>$uid)
3488                        {
3489                        if (is_array($mailboxes_list))
3490                        {
3491                        foreach ($mailboxes_list as $key => $val)
3492                        {
3493                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3494                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
3495                        }
3496                        }
3497                        }
3498                }*/
3499
3500                if (count($remove_share))
3501                {
3502                        foreach ($remove_share as $index=>$uid)
3503                        {
3504                        if (is_array($mailboxes_list))
3505                        {
3506                        foreach ($mailboxes_list as $key => $val)
3507                        {
3508                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
3509                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
3510                        }
3511                        }
3512                        }
3513                }
3514
3515                return true;
3516        }
3517
3518        function getaclfromuser($params)
3519        {
3520                $useracl = $params['user'];
3521
3522                $return = array();
3523                $return[$useracl] = 'false';
3524                $mbox_stream = $this->open_mbox();
3525                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
3526
3527                foreach ($mbox_acl as $user => $acl)
3528                {
3529                        if (($user != $this->username) && ($user == $useracl))
3530                        {
3531                                $return[$user] = $acl;
3532                        }
3533                }
3534                return $return;
3535        }
3536
3537        function getacltouser($user)
3538        {
3539                $return = array();
3540                $mbox_stream = $this->open_mbox();
3541                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3542                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
3543                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
3544                if(substr($user,0,4) != 'user')
3545                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
3546                else
3547                  $mbox_acl = imap_getacl($mbox_stream, $user);
3548                return $mbox_acl[$this->username];
3549        }
3550
3551
3552        function setaclfromuser($params)
3553        {
3554                $user = $params['user'];
3555                $acl = $params['acl'];
3556
3557                $mbox_stream = $this->open_mbox();
3558
3559                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
3560                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
3561
3562                if (is_array($mailboxes_list))
3563                {
3564                        foreach ($mailboxes_list as $key => $val)
3565                        {
3566                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
3567                                $folder = str_replace("&-", "&", $folder);
3568                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
3569                                {
3570                                        $return = imap_last_error();
3571                                }
3572                        }
3573                }
3574                if (isset($return))
3575                        return $return;
3576                else
3577                        return true;
3578        }
3579
3580        function download_attachment($msg,$msgno)
3581        {
3582                $array_parts_attachments = array();
3583                $array_parts_attachments['names'] = '';
3584                include_once("class.imap_attachment.inc.php");
3585                $imap_attachment = new imap_attachment();
3586
3587                if (count($msg->fname[$msgno]) > 0)
3588                {
3589                        $i = 0;
3590                        foreach ($msg->fname[$msgno] as $index=>$fname)
3591                        {
3592                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
3593                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($this->decode_string($fname));
3594                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
3595                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
3596                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
3597                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
3598                                $i++;
3599                        }
3600                }
3601                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
3602                return $array_parts_attachments;
3603        }
3604
3605        function spam($params)
3606        {
3607                $is_spam = $params['spam'];
3608                $folder = $params['folder'];
3609                $mbox_stream = $this->open_mbox($folder);
3610                $msgs_number = explode(',',$params['msgs_number']);
3611
3612                foreach($msgs_number as $msg_number) {
3613                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
3614                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
3615                        $body = imap_body($mbox_stream, $imap_msg_number);
3616                        $msg = $header . $body;
3617                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
3618                        $username = $this->username;
3619                        strtok($email, '@');
3620                        $domain = strtok('@');
3621
3622                        //Encontrar a assinatura do dspam no cabecalho
3623                        $v = explode("\r\n", $header);
3624                        foreach ($v as $linha){
3625                                if (eregi("^Message-ID", $linha)) {
3626                                        $args = explode(" ", $linha);
3627                                        $msg_id = "'$args[1]'";
3628                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
3629                                        $args = explode(" ",$linha);
3630                                        $signature = $args[1];
3631                                }
3632                        }
3633
3634                        // Seleciona qual comando a ser executado
3635                        switch($is_spam){
3636                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
3637                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
3638                        }
3639
3640                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
3641                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
3642                        system($cmd);
3643                }
3644                imap_close($mbox_stream);
3645                return false;
3646        }
3647        function get_header($msg_number){
3648                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
3649                if (!is_object($header))
3650                        return false;
3651                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
3652                $pdate = date_parse($header->MailDate);
3653                $header->udate +=  $pdate['zone']*(-60);
3654
3655                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
3656                        $flag = preg_match('/importance *: *(.*)\r/i',
3657                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
3658                                                ,$importance);
3659                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
3660                }
3661
3662                return $header;
3663        }
3664
3665//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
3666///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.
3667
3668    function insert_email($source,$folder,$timestamp){
3669        $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
3670        $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
3671        $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
3672        $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
3673        $imap_options = '/notls/novalidate-cert';
3674        $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
3675        if(imap_last_error())
3676        {
3677            imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
3678       }
3679        if($timestamp){
3680            $tempDir = ini_get("session.save_path");
3681            $file = $tempDir."imap_".$_SESSION[ 'phpgw_session' ][ 'session_id' ];
3682                $f = fopen($file,"w");
3683                fputs($f,base64_encode($source));
3684            fclose($f);
3685            $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);
3686            $return['command']=exec(escapeshellcmd($command));
3687        }else{
3688            $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
3689        }
3690        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
3691        $return['msg_no'] = $status->uidnext - 1;
3692                $return['error'] = imap_last_error();
3693        if($mbox_stream)
3694                        imap_close($mbox_stream);
3695        return $return;
3696
3697    }
3698
3699    function show_decript($params){
3700        $source = $params['source'];
3701        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
3702        $source = str_replace(" ", "+", $source,$i);
3703
3704        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
3705            if(!$source = base64_decode($source,true))
3706                return "error ".$source."Espaços ".$i;
3707
3708        }
3709        else {
3710            if(!$source = base64_decode($source))
3711                return "error ".$source."Espaços ".$i;
3712        }
3713
3714        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3715
3716                $get['msg_number'] = $insert['msg_no'];
3717                $get['msg_folder'] = 'INBOX'.$this->imap_delimiter.'decifradas';
3718                $return = $this->get_info_msg($get);
3719                $get['msg_number'] = $params['ID'];
3720                $get['msg_folder'] = $params['folder'];
3721                $tmp = $this->get_info_msg($get);
3722                if(!$tmp['status_get_msg_info'])
3723                {
3724                        $return['msg_day']=$tmp['msg_day'];
3725                        $return['msg_hour']=$tmp['msg_hour'];
3726                        $return['fulldate']=$tmp['fulldate'];
3727                        $return['smalldate']=$tmp['smalldate'];
3728                }
3729                else
3730                {
3731                        $return['msg_day']='';
3732                        $return['msg_hour']='';
3733                        $return['fulldate']='';
3734                        $return['smalldate']='';
3735                }
3736        $return['msg_no'] =$insert['msg_no'];
3737        $return['error'] = $insert['error'];
3738        $return['folder'] = $params['folder'];
3739        //$return['acls'] = $insert['acls'];
3740        $return['original_ID'] =  $params['ID'];
3741
3742        return $return;
3743
3744    }
3745
3746//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
3747//Base64 os "+" são substituidos por " " no envio e essa função arruma esse efeito.
3748
3749    function treat_base64_from_post($source){
3750            $offset = 0;
3751            do
3752            {
3753                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
3754                    {
3755                            $inicio = strpos($source, "\n\r", $inicio);
3756                            $fim = strpos($source, '--', $inicio);
3757                            if(!$fim)
3758                                    $fim = strpos($source,"\n\r", $inicio);
3759                            $length = $fim-$inicio;
3760                            $parte = substr( $source,$inicio,$length-1);
3761                            $parte = str_replace(" ", "+", $parte);
3762                            $source = substr_replace($source, $parte, $inicio, $length-1);
3763                    }
3764                    if($offset > $inicio)
3765                    $offset=FALSE;
3766                    else
3767                    $offset = $inicio;
3768            }
3769            while($offset);
3770            return $source;
3771    }
3772
3773//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.
3774
3775    function unarchive_mail($params)
3776    {
3777        $dest_folder = $params['folder'];
3778        $sources = explode("#@#@#@",$params['source']);
3779        $timestamps = explode("#@#@#@",$params['timestamp']);
3780        foreach($sources as $index=>$src) {
3781                        if($src!=""){
3782                                $source = $this->treat_base64_from_post($src);
3783                                $insert = $this->insert_email($source,$dest_folder,$timestamps[$index]);
3784                        }
3785                }
3786        return $insert;
3787    }
3788
3789    function download_all_local_attachments($params)
3790    {
3791        $source = $params['source'];
3792        $source = $this->treat_base64_from_post($source);
3793        $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
3794        $exporteml = new ExportEml();
3795        $params['num_msg']=$insert['msg_no'];
3796        $params['folder']='INBOX'.$this->imap_delimiter.'decifradas';
3797        return $exporteml->download_all_attachments($params);
3798    }
3799    function get_quota_folders(){
3800
3801            // Additional Imap Class for not-implemented functions into PHP-IMAP extension.
3802            include_once("class.imapfp.inc.php");           
3803            $imapfp = new imapfp();
3804
3805            if(!$imapfp->open($this->imap_server,$this->imap_port))
3806                    return $imapfp->get_error();             
3807            if (!$imapfp->login( $this->username,$this->password ))
3808                    return $imapfp->get_error();
3809
3810            $response_array = $imapfp->get_mailboxes_size();
3811            if ($imapfp->error)
3812                    return $imapfp->get_error();
3813
3814            $data = array();
3815            $quota_root = $this->get_quota(array('folder_id' => "INBOX"));
3816            $data["quota_root"] = $quota_root;
3817
3818            foreach ($response_array as $idx=>$line) {
3819                    $line2 = str_replace('"', "", $line);
3820                    $line2 = str_replace(" /vendor/cmu/cyrus-imapd/size (value.shared ",";",str_replace("* ANNOTATION ","",$line2));
3821                    list($folder,$size) = explode(";",$line2);
3822                    $size = str_replace(")","",$size);
3823                    $quotaPercent = (($size / 1048576) / $data["quota_root"]["quota_limit"])*100;
3824                    if ($size < 1048576 && $size > 1024)
3825                            $quota_used = round($size / 1024, 0).' Kb';
3826                    else if($size > 1024)
3827                            $quota_used = round($size / (1024*1024), 1).' Mb';
3828                    else
3829                            $quota_used = $size." b";
3830                    $folder = mb_convert_encoding($folder, "ISO_8859-1", "UTF7-IMAP");
3831                    if(!preg_match('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i',$folder)){
3832                            $folder = $this->functions->getLang("Inbox");
3833                    }
3834                    else
3835                            $folder = preg_replace('/user\\'.$this->imap_delimiter.$this->username.'\\'.$this->imap_delimiter.'/i','', $folder);
3836
3837                    $data[$folder] = array("quota_percent" => sprintf("%.1f",round($quotaPercent,1)), "quota_used" => $quota_used);
3838            }
3839            $imapfp->close();
3840            return $data;
3841    } 
3842}
3843?>
Note: See TracBrowser for help on using the repository browser.