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

Revision 3560, 143.8 KB checked in by wmerlotto, 13 years ago (diff)

Ticket #1389 - Os espaços e tabs são removidos do assundo do e-mail.

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