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

Revision 3294, 138.5 KB checked in by brunocosta, 14 years ago (diff)

Ticket #1323 - função replace_special_characters - retirada do caracter x00 do body

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