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

Revision 3057, 137.3 KB checked in by amuller, 14 years ago (diff)

Ticket #974 - Colocando no alt e title do td a data completa

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