source: trunk/expressoMail1_2/inc/class.imap_functions.inc.php @ 970

Revision 970, 98.7 KB checked in by amuller, 15 years ago (diff)

Ticket #545 - Correção de problema, utilizando imap_sort

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2include_once("class.functions.inc.php");
3include_once("class.ldap_functions.inc.php");
4include_once("class.exporteml.inc.php");
5
6class imap_functions
7{
8        var $public_functions = array
9        (       
10                'get_range_msgs'                                => True,
11                'get_info_msg'                                  => True,
12                'get_info_msgs'                                 => True,
13                'get_folders_list'                              => True,
14                'import_msgs'                                   => True
15        );
16
17        var $ldap;
18        var $mbox;
19        var $imap_port;
20        var $has_cid;
21        var $imap_options = '';
22        var $functions;
23        var $foldersLimit;
24
25        function imap_functions (){
26                $this->foldersLimit = 200; //Limit of folders (mailboxes) user can see
27                $this->username           = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
28                $this->password           = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
29                $this->imap_server        = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
30                $this->imap_port          = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
31                $this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
32                $this->functions          = new functions();           
33                $this->has_cid = false;
34               
35                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
36                {
37                        $this->imap_options = '/tls/novalidate-cert';
38                }
39                else
40                {
41                        $this->imap_options = '/notls/novalidate-cert';
42                }
43        }
44        // BEGIN of functions.
45        function open_mbox($folder = False)
46        {
47                if (is_resource($this->mbox))
48                        return $this->mbox;
49                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
50                $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()))));
51                return $this->mbox;
52         }
53
54        function parse_error($error){
55                // This error is returned from Imap.
56                if(strstr($error,'Connection refused')) {
57                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
58                }
59                // This error is returned from Postfix.
60                elseif(strstr($error,'message file too big')) {
61                        return str_replace("%1", ini_get('upload_max_filesize'),$this->functions->getLang('The size of this message has exceeded  the limit (%1B).'));                 
62                }
63                elseif(strstr($error,'virus')) {
64                        return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
65                }
66                // This condition verifies if SESSION is expired.
67                elseif(!count($_SESSION))                       
68                        return "nosession";
69
70                return $error;
71        }
72       
73        function get_range_msgs2($params)
74        {
75                $folder = $params['folder'];
76                $msg_range_begin = $params['msg_range_begin'];
77                $msg_range_end = $params['msg_range_end'];
78                $sort_box_type = $params['sort_box_type'];             
79                $sort_box_reverse = $params['sort_box_reverse'];
80                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
81                $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
82               
83                $return = array();
84                $i = 0;
85                $num_msgs = imap_num_msg($this->mbox);
86                if(is_array($sort_array_msg)){
87                        foreach($sort_array_msg as $msg_number => $value)
88                        {
89                                $temp = $this->get_info_head_msg($msg_number);
90                                if(!$temp)
91                                        return false;
92
93                                $return[$i] = $temp;
94                                $i++;
95                        }
96                }
97                $return['num_msgs'] = $num_msgs;
98
99                return $return;
100        }
101
102        function get_info_head_msg($msg_number) {
103                $head_array = array();
104                include_once("class.imap_attachment.inc.php");
105                $imap_attachment = new imap_attachment();
106
107
108
109                /*Como eu preciso do atributo Importance para saber se o email é
110                 * importante ou não, uso abaixo a função imap_fetchheader e busco
111                 * o atributo importance nela. Isso faz com que eu acesse o cabeçalho
112                 * duas vezes e de duas formas diferentes, mas em contrapartida, eu
113                 * não preciso reimplementar o método utilizando o fetchheader.
114                 * Como as mensagens são renderizadas em um número pequeno por vez,
115                 * não parece ter perda considerável de performance.
116                 */
117                $flag = preg_match('/importance *: *(.*)\r/i',
118                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number)),
119                        $importance);
120                $head_array['Importance'] = $flag==0?"Normal":$importance[1];
121
122
123                $header = $this->get_header($msg_number);
124                if (!is_object($header))
125                        return false;
126                $head_array['Recent'] = $header->Recent;
127                $head_array['Unseen'] = $header->Unseen;
128                if($header->Answered =='A' && $header->Draft == 'X'){
129                        $head_array['Forwarded'] = 'F';
130                }
131                else {
132                        $head_array['Answered'] = $header->Answered;
133                        $head_array['Draft']    = $header->Draft;
134                }
135                $head_array['Deleted'] = $header->Deleted;
136                $head_array['Flagged'] = $header->Flagged;
137
138                $head_array['msg_number'] = $msg_number;
139                //$head_array['msg_folder'] = $folder;
140
141                $date_msg = gmdate("d/m/Y",$header->udate);
142                if ( date("d/m/Y") == $date_msg)
143                        $head_array['udate'] = gmdate("H:i",$header->udate);
144                else
145                {
146                        $head_array['udate'] = $date_msg;
147                        if ( date("d/m/Y", time() - 86400) == gmdate("d/m/Y",$header->udate) )
148                                $head_array['udate'] = $this -> functions -> getLang( 'Yesterday' );
149                        if ( date("d/m/Y", time() - 172800) == gmdate("d/m/Y",$header->udate) )
150                                $head_array['udate'] = $this -> functions -> getLang( gmdate("l",$header->udate) );
151                        if ( date("d/m/Y", time() - 259200) == gmdate("d/m/Y",$header->udate) )
152                                $head_array['udate'] = $this -> functions -> getLang( gmdate("l",$header->udate) );
153                }
154
155                $head_array['aux_date'] = $date_msg; //Auxiliar apenas para mensagens locais.
156
157                $from = $header->from;
158                $head_array['from'] = array();
159                $tmp = imap_mime_header_decode($from[0]->personal);
160                $head_array['from']['name'] = $this->decode_string($tmp[0]->text);
161                $head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
162                if(!$head_array['from']['name'])
163                        $head_array['from']['name'] = $head_array['from']['email'];
164                $to = $header->to;
165                $head_array['to'] = array();
166                $tmp = imap_mime_header_decode($to[0]->personal);
167                $head_array['to']['name'] = $this->decode_string($this->decode_string($tmp[0]->text));
168                $head_array['to']['email'] = $this->decode_string($to[0]->mailbox) . "@" . $to[0]->host;
169                if(!$head_array['to']['name'])
170                        $head_array['to']['name'] = $head_array['to']['email'];
171                $head_array['subject'] = $this->decode_string($header->fetchsubject);
172
173                $head_array['Size'] = $header->Size;
174
175                $head_array['attachment'] = array();
176                $head_array['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
177
178                return $head_array;
179        }
180
181        function decode_string($string)
182        {       
183                if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
184                {
185                        $tmp = imap_mime_header_decode($string);
186                        foreach ($tmp as $tmp1)
187                                $return .= $this->htmlspecialchars_encode($tmp1->text);
188                        return $return;
189                }
190                else if (strpos(strtolower($string), '=?utf-8') !== false)
191                {
192                        $elements = imap_mime_header_decode($string);
193                        for($i = 0;$i < count($elements);$i++) {
194                                $charset = $elements[$i]->charset;
195                                $text =$elements[$i]->text;
196                                if(!strcasecmp($charset, "utf-8") ||
197                                !strcasecmp($charset, "utf-7")) {
198                                $text = iconv($charset, "ISO-8859-1", $text);
199                        }
200                                $decoded .= $this->htmlspecialchars_encode($text);
201                        }
202                        return $decoded;
203                }
204                else
205                        return $this->htmlspecialchars_encode($string);
206        }
207        /**
208        * Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
209        * com .emls gerados pelo expresso, e o arquivo pode ser um zip contendo vários emls ou um .eml.
210        */
211        function import_msgs($params) {
212                if(!$this->mbox)               
213                        $this->mbox = $this->open_mbox();
214                $errors = array();
215                $invalid_format = false;
216                $filename = $params['FILES'][0]['name'];
217                $quota = imap_get_quotaroot($this->mbox, $params["folder"]);
218                if((($quota['limit'] - $quota['usage'])*1024) <= $params['FILES'][0]['size']){
219                        return array( 'error' => $this->functions->getLang("fail in import:").
220                                                        " ".$this->functions->getLang("Over quota"));           
221                }
222                if(substr($filename,strlen($filename)-4)==".zip") {
223                        $zip = zip_open($params['FILES'][0]['tmp_name']);
224
225                        if ($zip) {
226                                while ($zip_entry = zip_read($zip)) {
227                                       
228                                        if (zip_entry_open($zip, $zip_entry, "r")) {
229                                                $email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
230                                                $status = @imap_append($this->mbox,
231                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
232                                                                        $email
233                                                                        );
234                                                if(!$status)
235                                                        array_push($errors,zip_entry_name($zip_entry));
236                                                zip_entry_close($zip_entry);
237                                        }
238                                }
239                                zip_close($zip);
240                        }
241                        }
242                else if(substr($filename,strlen($filename)-4)==".eml") {
243                        $email = implode("",file($params['FILES'][0]['tmp_name']));
244                        $status = @imap_append($this->mbox,
245                                                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
246                                                                        $email
247                                                                        );
248                        if(!$status){
249                                array_push($errors,zip_entry_name($zip_entry));
250                                zip_entry_close($zip_entry);
251                        }
252                }
253                else
254                {
255                        return array("error" => $this->functions->getLang("wrong file format"));
256                        $invalid_format = true;
257                }
258               
259                if(!$invalid_format) {
260                        if(count($errors)>0) {
261                                $message = $this->functions->getLang("fail in import:")."\n";
262                                foreach($errors as $arquivo) {
263                                        $message.=$arquivo."\n";
264                                }
265                                return array("error" => $message);
266                        }
267                        else
268                                return $this->functions->getLang("The import was executed successfully.");                     
269                }
270        }       
271        /*
272                Remove os anexos de uma mensagem. A estratégia para isso é criar uma mensagem nova sem os anexos, mantendo apenas
273                a primeira parte do e-mail, que é o texto, sem anexos.
274                O método considera que o email é multpart.
275        */
276        function remove_attachments($params) {
277                include_once("class.message_components.inc.php");
278                if(!$this->mbox || !is_resource($this->mbox))
279                        $this->mbox = $this->open_mbox($params["folder"]);
280                $return["status"] = true;
281                $return["msg_num"] = $params["msg_num"];
282                $header = "";
283               
284                $headertemp = explode("\n",imap_fetchheader($this->mbox, imap_msgno($this->mbox, $params["msg_num"])));
285                foreach($headertemp as $head) {//Se eu colocar todo o header do email dá pau no append, então procuro apenas o que interessa.
286                        $head1 = explode(":",$head);
287                        if ( (strtoupper($head1[0]) == strtoupper("to")) ||
288                                        (strtoupper($head1[0]) == strtoupper("from")) ||
289                                        (strtoupper($head1[0]) == strtoupper("subject")) ||
290                                        (strtoupper($head1[0]) == strtoupper("date")) )
291                                $header .= $head."\r\n";
292                }
293                               
294                $msg = &new message_components($this->mbox);
295                $msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
296                                                             Então uso essa classe para verificar a codificação e o charset,
297                                                             para que o método decodeBody do expresso possa trazer tudo certinho*/
298               
299                $status = @imap_append($this->mbox,
300                                "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
301                                        $header.
302                                        "\r\n".
303                                        str_replace("\n","\r\n",$this->decodeBody(
304                                                        imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),"1"),
305                                                        $msg->encoding[$params["msg_num"]][0], $msg->charset[$params["msg_num"]][0]
306                                                        )                                       
307                                        )); //Append do novo email, só com header e conteúdo sem anexos.
308               
309                if(!$status) {
310                        $return["status"] = false;
311                        $return["msg"] = lang("error appending mail on delete attachments");
312                }
313       
314                @imap_delete($this->mbox, imap_msgno($this->mbox, $params["msg_num"])); //Insere o novo e-mail sem anexos.
315                @imap_expunge($this->mbox); //Deleta o e-mail com anexos
316               
317                return $return;
318               
319        }
320
321/**
322         *
323         * @return
324         * @param $params Object
325         */
326        function get_info_msgs($params) {
327                include_once("class.exporteml.inc.php");
328                $return = array();
329                $new_params = array();
330                $attach_params = array();
331                $new_params["msg_folder"]=$params["folder"];
332                $attach_params["folder"] = $params["folder"];
333                $msgs = explode(",",$params["msgs_number"]);
334                $exporteml = new ExportEml();
335                foreach($msgs as $msg_number) {
336                        $new_params["msg_number"] = $msg_number;
337                        //ini_set("display_errors","1");
338                        $msg_info = $this->get_info_msg($new_params);
339
340                        $this->mbox = $this->open_mbox($params['folder']); //Não sei porque, mas se não abrir de novo a caixa dá erro.
341                        $msg_info['header'] = $this->get_info_head_msg($msg_number);
342
343                        $attach_params["num_msg"] = $msg_number;
344                        $msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
345                        $msg_info['url_export_file'] = $exporteml->export_to_archive($msg_number,$params["folder"]);
346                        imap_close($this->mbox);
347                        $this->mbox=false;
348                        array_push($return,serialize($msg_info));
349                }
350                return $return;
351        }
352
353        function get_info_msg($params)
354        {
355                $return = array();
356                $msg_number = $params['msg_number'];
357                $msg_folder = $params['msg_folder'];
358               
359                if(!$this->mbox || !is_resource($this->mbox))
360                        $this->mbox = $this->open_mbox($msg_folder);           
361               
362                $header = $this->get_header($msg_number);
363                if (!$header) {
364                        $return['status_get_msg_info'] = "false";                       
365                        return $return;
366                }
367               
368                $header_ = imap_fetchheader($this->mbox, $msg_number, FT_UID);
369
370                $return_get_body = $this->get_body_msg($msg_number, $msg_folder);
371               
372                //Substituição de links em email para abrir no próprio expresso
373                $body = ereg_replace("<a[^>]*href=[\'\"]mailto:([^\"\']+)[\'\"]>([^<]+)</a>","<a href=\"javascript:new_message_to('\\1')\">\\2</a>",$return_get_body['body']);
374
375                $return['body']                 = $body;
376                $return['attachments']  = $return_get_body['attachments'];
377                $return['thumbs']               = $return_get_body['thumbs'];
378                $return['signature']    = $return_get_body['signature'];
379
380                $pattern = '/^[ \t]*Disposition-Notification-To(^:)*:(.+)*@(.+)*$/isUm';
381                if (preg_match($pattern, $header_, $fields))
382                {
383                        preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches);
384                        $return['DispositionNotificationTo'] = "<".$matches[0].">";
385                }
386
387                $return['Recent']       = $header->Recent;
388                $return['Unseen']       = $header->Unseen;
389                $return['Deleted']      = $header->Deleted;             
390                $return['Flagged']      = $header->Flagged;
391
392                if($header->Answered =='A' && $header->Draft == 'X'){
393                        $return['Forwarded'] = 'F';
394                }
395 
396                else {
397                        $return['Answered']     = $header->Answered;
398                        $return['Draft']        = $header->Draft;       
399                }
400
401                $return['msg_number'] = $msg_number;
402                $return['msg_folder'] = $msg_folder;
403       
404                $date_msg = gmdate("d/m/Y",$header->udate);
405                if (date("d/m/Y") == $date_msg)
406                        $return['udate'] = gmdate("H:i",$header->udate);
407                else
408                        $return['udate'] = $date_msg;
409               
410                $return['msg_day'] = $date_msg;
411                $return['msg_hour'] = gmdate("H:i",$header->udate);
412               
413                if (date("d/m/Y") == $date_msg) //no dia
414                {
415                        $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
416                        $return['smalldate'] = gmdate("H:i",$header->udate);
417
418                        $timestamp_now = strtotime("now");                     
419                        $timestamp_msg_time = $header->udate;
420                        // $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ.
421                        // The variable $timestamp_diff is calculated without MailDate TZ.
422                        $pdate = date_parse($header->MailDate);
423                        $timestamp_diff = $timestamp_now - $timestamp_msg_time  + ($pdate['zone']*(-60));
424                       
425                        if (gmdate("H",$timestamp_diff) > 0)
426                        {
427                                $return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
428                        }
429                        else
430                        {
431                                if (gmdate("i",$timestamp_diff) == 0){
432                                        $return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
433                                }
434                                elseif (gmdate("i",$timestamp_diff) == 1){
435                                        $return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
436                                }
437                                else{
438                                        $return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
439                                }
440                        }
441                }
442                else{
443                        $return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
444                        $return['smalldate'] = gmdate("d/m/Y",$header->udate);
445                }
446               
447                $from = $header->from;
448                $return['from'] = array();
449                $tmp = imap_mime_header_decode($from[0]->personal);
450                $return['from']['name'] = $this->decode_string($tmp[0]->text);
451                $return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
452                if ($return['from']['name'])
453                {
454                        if (substr($return['from']['name'], 0, 1) == '"')
455                                $return['from']['full'] = $return['from']['name'] . ' ' . '&lt;' . $return['from']['email'] . '&gt;';
456                        else
457                                $return['from']['full'] = '"' . $return['from']['name'] . '" ' . '&lt;' . $return['from']['email'] . '&gt;';
458                }
459                else
460                        $return['from']['full'] = $return['from']['email'];
461               
462                // Sender attribute
463                $sender = $header->sender;
464                $return['sender'] = array();
465                $tmp = imap_mime_header_decode($sender[0]->personal);
466                $return['sender']['name'] = $this->decode_string($tmp[0]->text);
467                $return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
468                if ($return['sender']['name'])
469                {
470                        if (substr($return['sender']['name'], 0, 1) == '"')
471                                $return['sender']['full'] = $return['sender']['name'] . ' ' . '&lt;' . $return['sender']['email'] . '&gt;';
472                        else
473                                $return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '&lt;' . $return['sender']['email'] . '&gt;';
474                }
475                else
476                        $return['sender']['full'] = $return['sender']['email'];
477
478                if($return['from']['full'] == $return['sender']['full'])
479                        $return['sender'] = null;
480                $to = $header->to;
481                $return['toaddress2'] = "";
482                if (!empty($to))
483                {
484                        foreach ($to as $tmp)
485                        {
486                                if (!empty($tmp->personal))
487                                {
488                                        $personal_tmp = imap_mime_header_decode($tmp->personal);
489                                        $return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
490                                        $return['toaddress2'] .= " ";
491                                        $return['toaddress2'] .= "&lt;";
492                                        if ($tmp->host != 'unspecified-domain')
493                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
494                                        else
495                                                $return['toaddress2'] .= $tmp->mailbox;
496                                        $return['toaddress2'] .= "&gt;";
497                                        $return['toaddress2'] .= ", ";
498                                }
499                                else
500                                {
501                                        if ($tmp->host != 'unspecified-domain')
502                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
503                                        else
504                                                $return['toaddress2'] .= $tmp->mailbox;
505                                        $return['toaddress2'] .= ", ";
506                                }
507                        }
508                        $return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
509                }
510                else
511                {
512                        $return['toaddress2'] = "&lt;Empty&gt;";
513                }       
514               
515                $cc = $header->cc;
516                $return['cc'] = "";
517                if (!empty($cc))
518                {
519                        foreach ($cc as $tmp_cc)
520                        {
521                                if (!empty($tmp_cc->personal))
522                                {
523                                        $personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
524                                        $return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
525                                        $return['cc'] .= " ";
526                                        $return['cc'] .= "&lt;";
527                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
528                                        $return['cc'] .= "&gt;";
529                                        $return['cc'] .= ", ";
530                                }
531                                else
532                                {
533                                        $return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
534                                        $return['cc'] .= ", ";
535                                }
536                        }
537                        $return['cc'] = $this->del_last_two_caracters($return['cc']);
538                }
539                else
540                {
541                        $return['cc'] = "";
542                }       
543
544                ##
545                # @AUTHOR Rodrigo Souza dos Santos
546                # @DATE 2008/09/12
547                # @BRIEF Adding the BCC field.
548                ##
549                $bcc = $header->bcc;
550                $return['bcc'] = "";
551                if (!empty($bcc))
552                {
553                        foreach ($bcc as $tmp_bcc)
554                        {
555                                if (!empty($tmp_bcc->personal))
556                                {
557                                        $personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
558                                        $return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
559                                        $return['bcc'] .= " ";
560                                        $return['bcc'] .= "&lt;";
561                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
562                                        $return['bcc'] .= "&gt;";
563                                        $return['bcc'] .= ", ";
564                                }
565                                else
566                                {
567                                        $return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
568                                        $return['bcc'] .= ", ";
569                                }
570                        }
571                        $return['bcc'] = $this->del_last_two_caracters($return['bcc']);
572                }
573                else
574                {
575                        $return['bcc'] = "";
576                }       
577
578                $reply_to = $header->reply_to;
579                $return['reply_to'] = "";
580                if (is_object($reply_to[0]))
581                {
582                        if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
583                        {
584                                if (!empty($reply_to[0]->personal))
585                                {
586                                        $personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
587                                        if(!empty($personal_reply_to[0]->text)) {
588                                                $return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
589                                                $return['reply_to'] .= " ";
590                                                $return['reply_to'] .= "&lt;";
591                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
592                                                $return['reply_to'] .= "&gt;";
593                                        }
594                                        else {
595                                                $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
596                                        }
597                                }
598                                else
599                                {
600                                        $return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
601                                }
602                        }
603                }
604                $return['reply_to'] = $this->decode_string($return['reply_to']);
605                $return['subject'] = $this->decode_string($header->fetchsubject);
606                $return['Size'] = $header->Size;
607                $return['reply_toaddress'] = $header->reply_toaddress;
608
609                //All this is to help in local messages
610                $return['timestamp'] = $header->udate;
611                $return['login'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];//$GLOBALS['phpgw_info']['user']['account_id'];
612                $return['reply_toaddress'] = $header->reply_toaddress;
613
614                return $return;
615        }
616       
617        function get_body_msg($msg_number, $msg_folder)
618        {
619                include_once("class.message_components.inc.php");
620                $msg = &new message_components($this->mbox);
621                $msg->fetch_structure($msg_number);
622                $return = array();
623                $return['attachments'] = $this-> download_attachment($msg,$msg_number);         
624                if(!$this->has_cid)
625                {
626                        $return['thumbs']  = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
627                        $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
628                }                       
629               
630                if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
631                {
632                        $attachment = array(); //No attachments
633                       
634                        $content = '';
635                        if (strtolower($msg->structure[$msg_number]->subtype) == "plain")
636                        {
637                                $content .= nl2br($this->decodeBody((imap_body($this->mbox, $msg_number, FT_UID)), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]));
638                        }
639                        else if (strtolower($msg->structure[$msg_number]->subtype) == "html")
640                        {
641                                $content .= $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
642                        }
643                }
644                else
645                { //Complicated message, multiple parts
646                        $html_body = '';
647                        $content = '';
648                        $has_multipart = true;
649                        $this->has_cid = false;
650                       
651                        if (strtolower($msg->structure[$msg_number]->subtype) == "related")
652                                $this->has_cid = true;
653                       
654                        if (strtolower($msg->structure[$msg_number]->subtype) == "alternative") {
655                                $show_only_html = false;
656                                foreach($msg->pid[$msg_number] as $values => $msg_part) {
657                                        $file_type = strtolower($msg->file_type[$msg_number][$values]);
658                                        if($file_type == "text/html")
659                                                $show_only_html = true;                 
660                                }
661                        }
662                        else
663                                $show_only_html = false;
664
665                        foreach($msg->pid[$msg_number] as $values => $msg_part)
666                        {
667                               
668                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
669                                if($file_type == "message/rfc822")
670                                        $has_multipart = false;
671       
672                                if($file_type == "multipart/alternative")
673                                        $has_multipart = false;
674       
675                                if(($file_type == "text/plain"
676                                        || $file_type == "text/html")
677                                        && $file_type != 'attachment')
678                                {
679                                        if($file_type == "text/plain" && !$show_only_html && $has_multipart)
680                                        {
681                                                // if TXT file size > 100kb, then it will not expand.
682                                                if(!($file_type == "text/plain" && $msg->fsize[$msg_number][$values] > 102400)) {
683                                                        $content .= nl2br(htmlentities($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values])));                                                     
684                                                }
685                                        }
686                                        // if HTML attachment file size > 300kb, then it will not expand.
687                                        else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < 307200)
688                                        {
689                                                $content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
690                                                $show_only_html = true;
691                                        }
692                                }
693                                else if($file_type == "message/delivery-status"){
694                                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
695                                        $content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));                                           
696
697                                }
698                                else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
699                                       
700                                        include_once("class.imap_attachment.inc.php");
701                                        $att = new imap_attachment();
702                                        $attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
703                                        if($attachments['number_attachments'] > 0) {                                                                                           
704                                                foreach($attachments ['attachment'] as $index => $attachment){
705                                                        if(strtolower($attachment['type']) == "delivery-status" ||
706                                                                strtolower($attachment['type']) == "rfc822" ||                                                         
707                                                                strtolower($attachment['type']) == "rfc822-headers" ||
708                                                                strtolower($attachment['type']) == "plain"
709                                                        ){
710                                                                $obj = imap_rfc822_parse_headers(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values]);                                   
711                                                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";                                   
712                                                                $content .= "<br><table  style='margin:2px;border:1px solid black;background:#EAEAEA'>";
713                                                                $content .= "<tr><td><b>".$this->functions->getLang("Subject").":</b></td><td>".$this->decode_string($obj->subject)."</td></tr>";
714                                                                $content .= "<tr><td><b>".$this->functions->getLang("From").":</b></td><td>".$this->decode_string($obj->from[0]->mailbox."@".$obj->from[0]->host)."</td></tr>";
715                                                                $content .= "<tr><td><b>".$this->functions->getLang("Date").":</b></td><td>".$obj->date."</td></tr>";
716                                                                $content .= "<tr><td><b>".$this->functions->getLang("TO").":</b></td><td>".$this->decode_string($obj->to[0]->mailbox."@".$obj->to[0]->host)."</td></tr>";
717                                                                $content .= !$obj->cc ? "</table><br>" :"<tr><td><b>".$this->functions->getLang("CC").":</b></td><td>".$this->decode_string($obj->cc[0]->mailbox."@".$obj->cc[0]->host)."</td></tr></table><br>";                                                               
718                                                                $ix_part =      strtolower($attachment['type']) == "delivery-status" ? 1 : 0;
719                                                                $content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, ($attachment['part_in_msg']+$ix_part).".1", FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));                                                         
720                                                                break;                 
721                                                        }
722                                                }
723                                        }
724                                }
725                        }
726                        if($file_type == "text/plain" && ($show_only_html &&  $msg_part == 1) ||  (!$show_only_html &&  $msg_part == 3)){
727                                if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" &&  $msg_part == 1)
728                                        $content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
729                                else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
730                                        $content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));                         
731                        }
732                }
733                // Force message with flag Seen (imap_fetchbody not works correctly)
734                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");                               
735                $this->set_messages_flag($params);
736                $content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
737                $content = $this->replace_special_characters($content);
738                $return['body'] = $content;
739                return $return;
740        }
741       
742        function htmlfilter($body)
743        {
744                require_once('htmlfilter.inc');
745               
746                $tag_list = Array(
747                                false,
748                                'blink',
749                                'object',
750                                'meta',
751                                'html',
752                                'link',
753                                'frame',
754                                'iframe',
755                                'layer',
756                                'ilayer',
757                                'plaintext'
758                );
759
760                /**
761                * A very exclusive set:
762                */
763                // $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
764                $rm_tags_with_content = Array(
765                                'script',
766                                'style',
767                                'applet',
768                                'embed',
769                                'head',
770                                'frameset',
771                                'xml',
772                                'xmp'
773                );
774
775                $self_closing_tags =  Array(
776                                'img',
777                                'br',
778                                'hr',
779                                'input'
780                );
781
782                $force_tag_closing = true;
783
784                $rm_attnames = Array(
785                        '/.*/' =>
786                                Array(
787                                        '/target/i',
788                                        //'/^on.*/i', -> onClick, dos compromissos da agenda.
789                                        '/^dynsrc/i',
790                                        '/^datasrc/i',
791                                        '/^data.*/i',
792                                        '/^lowsrc/i'
793                                )
794                );
795
796                /**
797                 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
798                 * some idea of what's going on here. :)
799                 */
800
801                $bad_attvals = Array(
802                '/.*/' =>
803                Array(
804                      '/.*/' =>
805                              Array(
806                                Array(
807                                  '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
808                                          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
809                                          '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
810                                          '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
811                                      ),
812                            Array(
813                                              '\\1oddjob:\\2\\1',
814                                          //'\\1uucp:\\2\\1', -> doclinks notes
815                                      '\\1amaretto:\\2\\1',
816                                          '\\1round:\\2\\1'
817                                        )
818                                    ),     
819         
820                          '/^style/i' =>
821                              Array(
822                                        Array(
823                                          '/expression/i',
824                                              '/behaviou*r/i',
825                                          '/binding/i',
826                                              '/include-source/i',
827                                          '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
828                                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
829                                         ),
830                                        Array(
831                                          'idiocy',
832                                              'idiocy',
833                                          'idiocy',
834                                              'idiocy',
835                                          'url(\\1http://securityfocus.com/\\1)',
836                                          'url(\\1http://securityfocus.com/\\1)'
837                                         )
838                                )
839                          )
840                    );
841
842                $add_attr_to_tag = Array(
843                                '/^a$/i' => Array('target' => '"_new"')
844                );
845       
846       
847                $trusted_body = sanitize($body,
848                                $tag_list,
849                                $rm_tags_with_content,
850                                $self_closing_tags,
851                                $force_tag_closing,
852                                $rm_attnames,
853                                $bad_attvals,
854                                $add_attr_to_tag
855                );
856       
857            return $trusted_body;
858        }
859       
860        function decodeBody($body, $encoding, $charset=null)
861        {
862                /**
863                * replace e-mail by anchor.
864                */
865                // HTML Filter
866                //$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);
867        //$body = str_replace("\r\n", "\n", $body);
868                if ($encoding == 'quoted-printable')
869                {
870                        /*
871                       
872                        for($i=0;$i<256;$i++) {
873                                $c1=dechex($i);
874                                if(strlen($c1)==1){$c1="0".$c1;}
875                                $c1="=".$c1;
876                                $myqprinta[]=$c1;
877                                $myqprintb[]=chr($i);
878                        }               
879                         */
880                        $body = str_replace($myqprinta,$myqprintb,($body));
881                        $body = quoted_printable_decode($body);
882                while (ereg("=\n", $body))
883                {
884                        $body = ereg_replace ("=\n", '', $body);
885                }
886        }
887        else if ($encoding == 'base64')
888        {
889                $body = base64_decode($body);
890        }
891        else if ($encoding == '7bit')
892        {
893                $body = quoted_printable_decode($body);                                         
894        }
895                // All other encodings are returned raw.
896                if (strtolower($charset) == "utf-8")
897                        return utf8_decode($body);
898        else
899                        return $body;
900        }
901       
902        function process_embedded_images($msg, $msgno, $body, $msg_folder)
903        {
904                if (count($msg->inline_id[$msgno]) > 0)
905                {
906                        foreach ($msg->inline_id[$msgno] as $index => $cid)
907                        {
908                                $cid = eregi_replace("<", "", $cid);
909                                $cid = eregi_replace(">", "", $cid);
910                                $msg_part = $msg->pid[$msgno][$index];
911                                //$body = eregi_replace("alt=\"\"", "", $body);
912                                $body = eregi_replace("<br/>", "", $body);
913                                $body = str_replace("src=\"cid:".$cid."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
914                                $body = str_replace("src='cid:".$cid."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
915                                $body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
916                        }
917                }
918               
919                return $body;
920        }
921       
922        function replace_special_characters($body)
923        {
924                // Suspected TAGS!
925                /*$tag_list = Array(   
926                        'blink','object','meta',
927                        'html','link','frame',
928                        'iframe','layer','ilayer',
929                        'plaintext','script','style','img',
930                        'applet','embed','head',
931                        'frameset','xml','xmp');
932                */
933
934                // Layout problem: Change html elements
935                // with absolute position to relate position, CASE INSENSITIVE.
936                $body = @eregi_replace("POSITION: ABSOLUTE;","",$body);
937
938                $tag_list = Array('head','blink','object','frame',
939                        'iframe','layer','ilayer','plaintext','script',
940                        'applet','embed','frameset','xml','xmp','style');
941
942                $body = $this-> replace_links($body);
943                $blocked_tags = array();               
944                foreach($tag_list as $index => $tag) {
945                        $new_body = eregi_replace("<$tag", "<!--$tag", $body);
946                        if($body != $new_body) {
947                                $blocked_tags[] = $tag;
948                        }
949                        $body = eregi_replace("</$tag>", "</$tag-->", $new_body);
950                }
951                // Malicious Code Remove
952                $dirtyCodePattern = "/(<([\w]+)([^>]*)on(mouse(move|over|down|up)|load|blur|change|click|dblclick|focus|key(down|up|press)|select)=[\"'][^>\"']*[\"']([^>]*)>)(.*)(<\/\\2>)?/isU";
953                preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
954                foreach($rest[0] as $i => $val)
955                        if (!(preg_match("/window\.open/i",$rest[1][$i]) && strtoupper($rest[4][$i]) == "CLICK" )) //Calendar events
956                                $body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
957
958                return  "<span>".$body;
959        }
960
961        function replace_links($body) {                                 
962                $matches = array();
963                // Verify exception.
964                @preg_match("/<a href=\"notes:\/\/\//",$body,$matches);
965                // It no has exception,then open the link in new window.
966                if(count($matches))
967                        return $body;
968       
969                $pattern = '/(?<=[\s|(<br>)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[:\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\:\/\w.\-~&=?%;@+]*))/i';
970                $replacement = '<a href="http$3://$4$5" target="_blank">$1</a>';
971                return preg_replace($pattern, $replacement, $body);
972               
973                // Original
974                //return preg_replace('/(?<=[\s|(<br>)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\/\w.\-~&=?%;@+]*))/i', '<a href="http$3://$4$5" target="_blank">http$3://$4$5</a>', $body);
975        }
976
977        function get_signature($msg, $msg_number, $msg_folder)
978        {
979                foreach ($msg->file_type[$msg_number] as $index => $file_type)
980                {
981                        $file_type = strtolower($file_type);
982                        if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
983                        {
984                                if ($file_type == 'application/x-pkcs7-signature' || $file_type == 'application/pkcs7-signature')
985                                {
986                                        $export_mail = new ExportEml();
987                                        $params['folder'] = $msg_folder;
988                                        $params['msgs_to_export'] = $msg_number;
989                                    $tempDir = ini_get("session.save_path");
990                                        $cert_file = $tempDir."/certificate_".base_convert(microtime(), 10, 36).".crt";                                 
991                                        $result = openssl_pkcs7_verify($export_mail->export_msg($params),PKCS7_NOVERIFY,$cert_file);
992                                        if (file_exists($cert_file))
993                                        {
994                                                $handle = fopen ($cert_file,"r");
995                                                $pemout = fread($handle,filesize($cert_file));
996                                                fclose($handle);
997                                                $cert=openssl_x509_parse($pemout);
998                                                $temp = "\\nSigned by: ".$cert[subject][CN];
999                                                $temp .= "\\nEmail Address: ".$cert[subject][emailAddress];
1000                                                $temp .= "\\nCertificate issued by: ".$cert[issuer][CN]."\\n";
1001                                        }
1002                                    /* Message verified */
1003                                    if ($result === true)
1004                                            $sign = $temp;
1005                                     else
1006                                            $sign = "void";
1007                                }
1008                        }
1009                }
1010                return $sign;   
1011        }
1012
1013        function get_thumbs($msg, $msg_number, $msg_folder)
1014        {
1015                $thumbs_array = array();
1016                $i = 0;
1017        foreach ($msg->file_type[$msg_number] as $index => $file_type)
1018        {
1019                $file_type = strtolower($file_type);
1020                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
1021                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
1022                                $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].">";
1023                                $href = "<a onMouseDown='save_image(event,this)' 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>";
1024                                        $thumbs_array[] = $href;
1025                        }
1026                        $i++;
1027                }
1028        }
1029        return $thumbs_array;
1030        }
1031               
1032        /*function delete_msg($params)
1033        {
1034                $folder = $params['folder'];
1035                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
1036               
1037                $mbox_stream = $this->open_mbox($folder);
1038               
1039                foreach ($msgs_to_delete as $msg_number){
1040                        imap_delete($mbox_stream, $msg_number, FT_UID);
1041                }
1042                imap_close($mbox_stream, CL_EXPUNGE);
1043                return $params['msgs_to_delete'];
1044        }*/
1045
1046        // Novo
1047        function delete_msgs($params)
1048        {
1049               
1050                $folder = $params['folder'];
1051                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
1052                $msgs_number = explode(",",$params['msgs_number']);
1053                $border_ID = $params['border_ID'];
1054               
1055                $return = array();
1056               
1057                if ($params['get_previous_msg']){
1058                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1059                        // Fix problem in unserialize function JS.
1060                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1061                }
1062
1063                //$mbox_stream = $this->open_mbox($folder);             
1064                $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()))));
1065               
1066                foreach ($msgs_number as $msg_number)
1067                {
1068                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
1069                                $return['msgs_number'][] = $msg_number;
1070                }
1071               
1072                $return['folder'] = $folder;
1073                $return['border_ID'] = $border_ID;
1074               
1075                if($mbox_stream)
1076                        imap_close($mbox_stream, CL_EXPUNGE);
1077                return $return;
1078        }
1079
1080               
1081        function refresh($params)
1082        {
1083                include_once("class.imap_attachment.inc.php");
1084                $imap_attachment = new imap_attachment();               
1085                $folder = $params['folder'];
1086                $msg_range_begin = $params['msg_range_begin'];
1087                $msg_range_end = $params['msg_range_end'];
1088                $msgs_existent = $params['msgs_existent'];
1089                $sort_box_type = $params['sort_box_type'];             
1090                $sort_box_reverse = $params['sort_box_reverse'];
1091                $msgs_in_the_server = array();
1092                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1093                $msgs_in_the_server = $this->get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$msg_range_end);
1094                $msgs_in_the_server = array_keys($msgs_in_the_server);
1095                if(!count($msgs_in_the_server))
1096                        return array();
1097                       
1098                $num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
1099                $msgs_in_the_client = explode(",", $msgs_existent);     
1100
1101                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
1102                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
1103               
1104                $msgs_to_exec = array();
1105                if ((count($msg_to_insert)) && ($msgs_existent))
1106                {
1107                        foreach($msg_to_insert as $index => $msg_number)
1108                        {
1109                                if ($msgs_in_the_server[$index+1])
1110                                {
1111                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
1112                                        $msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
1113                                }
1114                                else
1115                                {
1116                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
1117                                        $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1118                                }
1119                        }
1120                        ksort($msgs_to_exec);
1121                }
1122                elseif(!$msgs_existent)
1123                {
1124                        foreach($msgs_in_the_server as $index => $msg_number)
1125                        {
1126                                $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
1127                        }
1128                }
1129               
1130                $return = array();
1131                $i = 0;
1132                foreach($msgs_to_exec as $msg_number => $command)
1133                {
1134                        /*A função imap_headerinfo não traz o cabeçalho completo, e sim alguns
1135                        * atributos do cabeçalho. Como eu preciso do atributo Importance
1136                        * para saber se o email é importante ou não, uso abaixo a função
1137                        * imap_fetchheader e busco o atributo importance nela para passar
1138                        * para as funções ajax. Isso faz com que eu acesse o cabeçalho
1139                        * duas vezes e de duas formas diferentes, mas em contrapartida, eu
1140                        * não preciso reimplementar o método utilizando o fetchheader.
1141                        * Como na atualização são poucas as mensagens que devem ser renderizadas,
1142                        * a perda em performance é insignificante.
1143                        */
1144                        $flag = preg_match('/importance *: *(.*)\r/i',
1145                                        @imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
1146                                        ,$importance);         
1147                        $return[$i]['Importance'] = $flag==0?"Normal":$importance[1];
1148                       
1149                        $header = $this->get_header($msg_number);
1150                        if (!is_object($header))
1151                                continue;
1152
1153                        $return[$i]['msg_number']       = $msg_number;
1154                        $return[$i]['command']          = $command;
1155                       
1156                        $return[$i]['msg_folder']       = $folder;
1157                        $return[$i]['Recent']           = $header->Recent;
1158                        $return[$i]['Unseen']           = $header->Unseen;
1159                        $return[$i]['Answered']         = $header->Answered;
1160                        $return[$i]['Deleted']          = $header->Deleted;
1161                        $return[$i]['Draft']            = $header->Draft;
1162                        $return[$i]['Flagged']          = $header->Flagged;
1163
1164                        $date_msg = gmdate("d/m/Y",$header->udate);
1165                        if (gmdate("d/m/Y") == $date_msg)
1166                                $return[$i]['udate'] = gmdate("H:i",$header->udate);
1167                        else
1168                                $return[$i]['udate'] = $date_msg;
1169                       
1170                        $from = $header->from;
1171                        $return[$i]['from'] = array();
1172                        $tmp = imap_mime_header_decode($from[0]->personal);
1173                        $return[$i]['from']['name'] = $tmp[0]->text;
1174                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
1175                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
1176                        if(!$return[$i]['from']['name'])
1177                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
1178                       
1179                        /*$toaddress = imap_mime_header_decode($header->toaddress);
1180                        $return[$i]['toaddress'] = '';
1181                        foreach ($toaddress as $tmp)
1182                                $return[$i]['toaddress'] .= $tmp->text;*/
1183                        $to = $header->to;
1184                        $return[$i]['to'] = array();
1185                        $tmp = imap_mime_header_decode($to[0]->personal);
1186                        $return[$i]['to']['name'] = $tmp[0]->text;
1187                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
1188                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
1189                       
1190                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
1191
1192                        $return[$i]['Size'] = $header->Size;
1193                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
1194                       
1195                        $return[$i]['attachment'] = array();
1196                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
1197                        $i++;
1198                }
1199                $return['new_msgs'] = imap_num_recent($this->mbox);
1200                $return['msgs_to_delete'] = $msg_to_delete;
1201                if($this->mbox && is_resource($this->mbox))
1202                        imap_close($this->mbox);
1203
1204                return $return;
1205        }
1206
1207        function get_folders_list($params = null)
1208        {
1209                $mbox_stream = $this->open_mbox();             
1210                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
1211                $folders_list = imap_getmailboxes($mbox_stream, $serverString, "*");
1212                $folders_list = array_slice($folders_list,0,$this->foldersLimit);
1213
1214                $tmp = array();
1215                $result = array();
1216               
1217                if (is_array($folders_list)) {
1218                        reset($folders_list);
1219                       
1220                        $i = 0;
1221                        while (list($key, $val) = each($folders_list)) {
1222                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
1223                                $result[$i]['folder_unseen'] = $status->unseen;
1224                       
1225                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
1226                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
1227                                $folder_id = $tmp_folder_id[1];
1228                                $result[$i]['folder_id'] = $folder_id;
1229                               
1230                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1231                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
1232                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
1233                                if (is_numeric($result[$i]['folder_name']))     {
1234                                        $this->ldap = new ldap_functions();
1235                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])){
1236                                                $result[$i]['folder_name'] = $cn;
1237                                        }
1238                                }
1239                               
1240                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1241                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
1242                                       
1243                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
1244                                        $result[$i]['folder_hasChildren'] = 1;
1245                                else
1246                                        $result[$i]['folder_hasChildren'] = 0;
1247
1248                                $i++;                           
1249                        }
1250                }
1251               
1252                foreach ($result as $folder_info)
1253                {
1254                        $array_tmp[] = $folder_info['folder_id'];
1255                }
1256               
1257                natcasesort($array_tmp);
1258               
1259                foreach ($array_tmp as $key => $folder_id)
1260                {
1261                        $result2[] = $result[$key];
1262                }
1263               
1264                $current_folder = "INBOX";
1265                if($params && $params['folder'])
1266                        $current_folder = $params['folder'];
1267                return array_merge($result2, $this->get_quota(array(folder_id => $current_folder)));
1268        }
1269       
1270        function create_mailbox($arr)
1271        {
1272                $namebox        = $arr['newp'];
1273                $mbox_stream = $this->open_mbox();
1274                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1275                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
1276               
1277                $result = "Ok";
1278                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
1279                {
1280                        $result = implode("<br />\n", imap_errors());
1281                }       
1282               
1283                if($mbox_stream)
1284                        imap_close($mbox_stream);
1285                                       
1286                return $result;
1287               
1288        }
1289       
1290        function create_extra_mailbox($arr)
1291        {
1292                $nameboxs = explode(";",$arr['nw_folders']);
1293                $result = "";
1294                $mbox_stream = $this->open_mbox();
1295                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1296                foreach($nameboxs as $key=>$tmp){                       
1297                        if($tmp != ""){
1298                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1299                                        $result = implode("<br />\n", imap_errors());
1300                                        if($mbox_stream)
1301                                                imap_close($mbox_stream);                                       
1302                                        return $result;
1303                                }
1304                        }
1305                }
1306                if($mbox_stream)
1307                        imap_close($mbox_stream);
1308                return true;
1309        }
1310       
1311        function delete_mailbox($arr)
1312        {
1313                $namebox = $arr['del_past'];
1314                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1315                $mbox_stream = $this->open_mbox();
1316                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
1317               
1318                $result = "Ok";
1319                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1320                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1321                {
1322                        $result = implode("<br />\n", imap_errors());
1323                }
1324                if($mbox_stream)
1325                        imap_close($mbox_stream);
1326                return $result;
1327        }
1328       
1329        function ren_mailbox($arr)
1330        {
1331                $namebox = $arr['current'];
1332                $new_box = $arr['rename'];
1333                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1334                $mbox_stream = $this->open_mbox();
1335                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
1336               
1337                $result = "Ok";
1338                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1339                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
1340               
1341                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1342                {
1343                        $result = imap_errors();                       
1344                }
1345                if($mbox_stream)
1346                        imap_close($mbox_stream);
1347                return $result;
1348               
1349        }
1350       
1351        function get_num_msgs($params)
1352        {
1353                $folder = $params['folder'];
1354                if(!$this->mbox || !is_resource($this->mbox)) {
1355                        $this->mbox = $this->open_mbox($folder);
1356                        if(!$this->mbox || !is_resource($this->mbox))
1357                        return imap_last_error();
1358                }               
1359                $num_msgs = imap_num_msg($this->mbox);
1360                if($this->mbox && is_resource($this->mbox))
1361                        imap_close($this->mbox);
1362               
1363                return $num_msgs;
1364        }
1365       
1366        function send_mail($params)
1367        {
1368                include_once("class.phpmailer.php");
1369                $mail = new PHPMailer();
1370                include_once("class.db_functions.inc.php");
1371                $db = new db_functions();
1372                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
1373                ##
1374                # @AUTHOR Rodrigo Souza dos Santos
1375                # @DATE 2008/09/17
1376                # @BRIEF Checks if the user has permission to send an email with the email address used.
1377                ##
1378                if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
1379                {
1380                        $deny = true;
1381                        foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
1382                                if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
1383                                        $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
1384
1385                        if ( $deny )
1386                                return "The server denied your request to send a mail, you cannot use this mail address.";
1387                }
1388
1389                //new_message_to backs to mailto: pattern
1390                $params['body'] = eregi_replace("<a href=\"javascript:new_message_to\('([^>]+)'\)\">[^>]+</a>","<a href='mailto:\\1'>\\1</a>",$params['body']);
1391
1392                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1393                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1394                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1395                $subject = $params['input_subject'];
1396                $msg_uid = $params['msg_id'];
1397                $return_receipt = $params['input_return_receipt'];
1398                $is_important = $params['input_important_message'];
1399                $body = $params['body'];
1400                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
1401                $attachments = $params['FILES'];
1402                $forwarding_attachments = $params['forwarding_attachments'];
1403                $local_attachments = $params['local_attachments'];
1404                 
1405                $folder =$params['folder'];
1406                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
1407                $folder_name = $params['folder_name'];         
1408                // Fix problem with cyrus delimiter changes.
1409                // Dots in names: enabled/disabled.                             
1410                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1411                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1412                // End Fix.
1413                if ($folder != 'null'){                 
1414                        $mail->SaveMessageInFolder = $folder;
1415                }
1416////////////////////////////////////////////////////////////////////////////////////////////////////
1417                $mail->SMTPDebug = false;
1418                               
1419                $mail->IsSMTP();
1420                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1421                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1422                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1423                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1424                if($fromaddress){
1425                        $mail->Sender = $mail->From;
1426                        $mail->SenderName = $mail->FromName;
1427                        $mail->FromName = $fromaddress[0];
1428                        $mail->From = $fromaddress[1];
1429                }
1430                               
1431                $this->add_recipients("to", $toaddress, &$mail);
1432                $this->add_recipients("cc", $ccaddress, &$mail);
1433                $this->add_recipients("cco", $ccoaddress, &$mail);
1434                $mail->Subject = $subject;
1435                $mail->IsHTML(true);
1436                $mail->Body = $params['body'];
1437
1438////////////////////////////////////////////////////////////////////////////////////////////////////
1439                //      Build CID for embedded Images!!!
1440                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
1441                $cid_imgs = '';
1442                $name_cid_files = array();
1443                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1444                $cid_array = array();
1445                foreach($cid_imgs[6] as $j => $val){
1446                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
1447                        {
1448                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
1449                        }
1450                        $cid = $cid_array[$cid_imgs[4][$j].$val];
1451                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
1452                       
1453                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
1454                                {
1455                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
1456                                        $fileName = "image_".($j).".jpg";
1457                                        $fileCode = "base64";
1458                                        $fileType = "image/jpg";
1459                                }
1460                                else
1461                                {
1462                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
1463                                        $file_description = unserialize(rawurldecode($attach_img));
1464
1465                                        foreach($file_description as $i => $descriptor){                               
1466                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
1467                                        }
1468                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
1469                                        $fileName = $file_description[2];
1470                                        $fileCode = $file_description[4];
1471                                        $fileType = $this->get_file_type($file_description[2]);
1472                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
1473                                }
1474                                $tempDir = ini_get("session.save_path");
1475                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
1476                                $f = fopen($tempDir.'/'.$file,"w");
1477                                fputs($f,$fileContent);
1478                                fclose($f);
1479                                if ($fileContent)
1480                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
1481                                //else
1482                                //      return "Error loading image attachment content";                                               
1483
1484                }
1485////////////////////////////////////////////////////////////////////////////////////////////////////
1486                //      Build Uploading Attachments!!!
1487                if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
1488                {
1489                        $total_uploaded_size = 0;
1490                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
1491                        foreach ($attachments as $attach)
1492                        {
1493                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
1494                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
1495                        }
1496                        if( $total_uploaded_size > $upload_max_filesize)
1497                                return $this->parse_error("message file too big");                     
1498                }
1499                else if(($params['is_local_forward']=="1") && (count($local_attachments))) { //Caso seja forward de mensagens locais
1500
1501                        $total_uploaded_size = 0;
1502                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;                       
1503                        foreach($local_attachments as $local_attachment) {
1504                                $file_description = unserialize(rawurldecode($local_attachment));
1505                                $tmp = array_values($file_description);
1506                                foreach($file_description as $i => $descriptor){                               
1507                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1508                                }
1509                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
1510                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
1511                        }
1512                        if( $total_uploaded_size > $upload_max_filesize)
1513                                return 'false';
1514                }
1515////////////////////////////////////////////////////////////////////////////////////////////////////
1516                //      Build Forwarding Attachments!!!
1517                if (count($forwarding_attachments) > 0)
1518                {
1519                        // Bug fixed for array_search function
1520                        if(count($name_cid_files) > 0) {
1521                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
1522                                $name_cid_files[0] = null;
1523                        }                       
1524                       
1525                        foreach($forwarding_attachments as $forwarding_attachment)
1526                        {
1527                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
1528                                        $tmp = array_values($file_description);
1529                                        foreach($file_description as $i => $descriptor){                               
1530                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1531                                        }
1532                                        $file_description = $tmp;                                       
1533                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
1534                                        $fileName = $file_description[2];
1535                                        if(!array_search(trim($fileName),$name_cid_files)) {
1536                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
1537                                }
1538                        }
1539                }
1540
1541////////////////////////////////////////////////////////////////////////////////////////////////////
1542                // Important message
1543                if($is_important)
1544                        $mail->isImportant();
1545
1546////////////////////////////////////////////////////////////////////////////////////////////////////
1547                // Disposition-Notification-To
1548                if ($return_receipt)
1549                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1550////////////////////////////////////////////////////////////////////////////////////////////////////
1551
1552                $sent = $mail->Send();
1553               
1554                if(!$sent)
1555                {
1556                        return $this->parse_error($mail->ErrorInfo);
1557                }
1558                else
1559                {
1560                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
1561                        {
1562                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
1563                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
1564                                $now = date("d/m/y H:i:s");
1565                                $addrs = $toaddress.$ccaddress.$ccoaddress;
1566                                $sent = trim($sent);                                                                                           
1567                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
1568                        }
1569                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
1570                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
1571                                $contacts = new dynamic_contacts();
1572                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
1573                                return array("success" => true, "new_contacts" => $new_contacts);
1574                        }
1575                        return array("success" => true);
1576                }
1577        }
1578
1579        function add_recipients($recipient_type, $full_address, $mail)
1580        {
1581                $parse_address = imap_rfc822_parse_adrlist($full_address, "");         
1582                foreach ($parse_address as $val)
1583                {
1584                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
1585                        if ($val->mailbox == "INVALID_ADDRESS")
1586                                continue;
1587                       
1588                        if (empty($val->personal))
1589                        {
1590                                switch($recipient_type)
1591                                {
1592                                        case "to":
1593                                                $mail->AddAddress($val->mailbox."@".$val->host);
1594                                                break;
1595                                        case "cc":
1596                                                $mail->AddCC($val->mailbox."@".$val->host);
1597                                                break;
1598                                        case "cco":
1599                                                $mail->AddBCC($val->mailbox."@".$val->host);
1600                                                break;
1601                                }
1602                        }
1603                        else
1604                        {
1605                                switch($recipient_type)
1606                                {
1607                                        case "to":
1608                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
1609                                                break;
1610                                        case "cc":
1611                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
1612                                                break;
1613                                        case "cco":
1614                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
1615                                                break;
1616                                }
1617                        }
1618                }
1619                return true;
1620        }
1621       
1622        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
1623        {
1624                $mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
1625                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);           
1626                if($encoding == 'base64')
1627                        # The function imap_base64 adds a new line
1628                        # at ASCII text, with CRLF line terminators.
1629                        # So is being exchanged for base64_decode.
1630                        #
1631                        #$fileContent = imap_base64($fileContent);
1632                        $fileContent = base64_decode($fileContent);
1633                else if($encoding == 'quoted-printable')
1634                        $fileContent = quoted_printable_decode($fileContent);                           
1635                return $fileContent;
1636        }
1637       
1638        function del_last_caracter($string)
1639        {
1640                $string = substr($string,0,(strlen($string) - 1));
1641                return $string;
1642        }
1643       
1644        function del_last_two_caracters($string)
1645        {
1646                $string = substr($string,0,(strlen($string) - 2));
1647                return $string;
1648        }
1649       
1650        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd)
1651        {
1652                if ($search_box_type == "" || $search_box_type == "ALL"){
1653                        $imapsort = imap_sort($this->mbox,constant($sort_box_type),$sort_box_reverse,SE_UID,$search_box_type);
1654                        foreach($imapsort as $iuid)
1655                                $sort[$iuid] = "";
1656                        $slice_array = true;
1657                }
1658                else
1659                {
1660                        $sort = array();
1661                        if ($offsetBegin > $offsetEnd) {$temp=$offsetEnd; $offsetEnd=$offsetBegin; $offsetBegin=$temp;}
1662                        $num_msgs = imap_num_msg($this->mbox);
1663                        if ($offsetEnd >  $num_msgs) {$offsetEnd = $num_msgs;}
1664                        if ($sort_box_type == "SORTARRIVAL")
1665                        {
1666                                // If I'm looking for arrival order we doesn't need to see all imap box
1667                                if ($sort_box_reverse)
1668                                {
1669                                        $numBegin = $num_msgs - $offsetEnd;
1670                                        if ($numBegin < 0) $numBegin=0;
1671                                        $numEnd = $num_msgs - ($offsetBegin-1);
1672                                }
1673                                else
1674                                {
1675                                        $numBegin = ($offsetBegin-1);
1676                                        $numEnd = $offsetEnd;
1677                                }
1678                                $slice_array = false;
1679                        }
1680                        else
1681                        {
1682                                // If I'm looking for a specific type of email I have to see entire imap box
1683                                $numBegin = 0;
1684                                $numEnd = $num_msgs;
1685                                $slice_array = true;
1686                        }
1687                        for ($i=$numBegin+1; $i<=$numEnd; $i++)
1688                        {
1689                                $iuid = @imap_uid($this->mbox,$i);
1690                                $header = $this->get_header($iuid);
1691                                // List UNSEEN messages.
1692                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
1693                                        continue;
1694                                }
1695                                // List SEEN messages.
1696                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
1697                                        continue;
1698                                }
1699                                // List ANSWERED messages.
1700                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
1701                                        continue;
1702                                }
1703                                // List FLAGGED messages.
1704                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
1705                                        continue;
1706                                }
1707
1708                                if($sort_box_type=='SORTFROM') {
1709                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
1710                                                $from = $header->to;
1711                                        else
1712                                                $from = $header->from;
1713
1714                                        $tmp = imap_mime_header_decode($from[0]->personal);
1715
1716                                        if ($tmp[0]->text != "")
1717                                                $sort[$iuid] = $tmp[0]->text;
1718                                        else
1719                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
1720                                }
1721                                else if($sort_box_type=='SORTSUBJECT') {
1722                                        $sort[$iuid] = $header->subject;
1723                                }
1724                                else if($sort_box_type=='SORTSIZE') {
1725                                        $sort[$iuid] = $header->Size;
1726                                }
1727                                else {
1728                                        $sort[$iuid] = $header->udate;
1729                                }
1730
1731                        }
1732                        natcasesort($sort);
1733
1734                        if ($sort_box_reverse)
1735                                $sort = array_reverse($sort,true);
1736                }
1737
1738                if ($slice_array)
1739                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
1740
1741                return $sort;
1742
1743        }
1744
1745
1746        function move_search_messages($params){         
1747                $params['selected_messages'] = urldecode($params['selected_messages']);
1748                $params['new_folder'] = urldecode($params['new_folder']);
1749                $params['new_folder_name'] = urldecode($params['new_folder_name']);
1750                $sel_msgs = explode(",", $params['selected_messages']);
1751                @reset($sel_msgs);     
1752                $sorted_msgs = array();
1753                foreach($sel_msgs as $idx => $sel_msg) {
1754                        $sel_msg = explode(";", $sel_msg);
1755                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
1756                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
1757                         }     
1758                         else {
1759                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
1760                         }
1761                }
1762                @ksort($sorted_msgs);
1763                $last_return = false;           
1764                foreach($sorted_msgs as $folder => $msgs_number) {                     
1765                        $params['msgs_number'] = $msgs_number;
1766                        $params['folder'] = $folder;   
1767                        if($params['new_folder'] && $folder != $params['new_folder']){
1768                                $last_return = $this -> move_messages($params);                         
1769                        }
1770                        elseif(!$params['new_folder'] || $params['delete'] ){
1771                                $last_return = $this -> delete_msgs($params);
1772                                $last_return['deleted'] = true;
1773                        }
1774                }
1775                return $last_return;
1776        }
1777       
1778        function move_messages($params)
1779        {
1780                $folder = $params['folder'];           
1781                $mbox_stream = $this->open_mbox($folder);               
1782                $newmailbox = ($params['new_folder']);
1783                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
1784                $new_folder_name = $params['new_folder_name'];
1785                $msgs_number = $params['msgs_number'];
1786                $return = array('msgs_number' => $msgs_number,
1787                                                'folder' => $folder,
1788                                                'new_folder_name' => $new_folder_name,
1789                                                'border_ID' => $params['border_ID'],
1790                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
1791               
1792                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
1793        if (substr($folder,0,4) == 'user'){
1794                $acl = $this->getacltouser($folder);
1795                /*
1796                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
1797                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
1798                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
1799                 *   w - write (STORE flags other than SEEN and DELETED)
1800                 *   i - insert (perform APPEND, COPY into mailbox)
1801                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
1802                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
1803                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
1804                 *   a - administer (perform SETACL)
1805                        */
1806                        if (strpos($acl, "d") === false){
1807                                $return['status'] = false;
1808                                return $return;
1809                        }
1810        }
1811        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
1812        if (substr($new_folder_name,0,4) == 'user'){
1813                $this->ldap = new ldap_functions();
1814                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
1815                        $return['new_folder_name'] = array_pop($tmp_folder_name);
1816                        if (is_numeric($return['new_folder_name']))
1817                                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
1818                                        $return['new_folder_name'] = $cn;
1819        }
1820               
1821                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.         
1822                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
1823                {
1824                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1825                        // Fix problem in unserialize function JS.
1826                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1827                }
1828               
1829                $mbox_stream = $this->open_mbox($folder);       
1830                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1831                        imap_expunge($mbox_stream);
1832                        if($mbox_stream)
1833                                imap_close($mbox_stream);
1834                        return $return;
1835                }else {
1836                        if(strstr(imap_last_error(),'Over quota')) {                           
1837                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
1838                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];                                                                       
1839                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];                                                           
1840                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1841                                $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()))));
1842                                if(!$mbox)
1843                                        return imap_last_error();
1844                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");                           
1845                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
1846                                        if($mbox_stream)
1847                                                imap_close($mbox_stream);
1848                                        if($mbox)                                                                       
1849                                                imap_close($mbox);
1850                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";                                                               
1851                                }
1852                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1853                                        imap_expunge($mbox_stream);
1854                                        if($mbox_stream)
1855                                                imap_close($mbox_stream);
1856                                        // return to original quota limit.
1857                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
1858                                                if($mbox)
1859                                                        imap_close($mbox);
1860                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
1861                                        }
1862                                        return $return;                                                                                                 
1863                                }
1864                                else {
1865                                        if($mbox_stream)
1866                                                imap_close($mbox_stream);
1867                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
1868                                                if($mbox)
1869                                                        imap_close($mbox);
1870                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
1871                                        }
1872                                        return imap_last_error();                               
1873                                }
1874                               
1875                        }
1876                        else {
1877                                if($mbox_stream)
1878                                        imap_close($mbox_stream);
1879                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
1880                        }
1881                }               
1882        }
1883       
1884        function save_msg($params)
1885        {
1886               
1887                include_once("class.phpmailer.php");
1888                $mail = new PHPMailer();
1889                include_once("class.db_functions.inc.php");
1890                $toaddress = $params['input_to'];
1891                $ccaddress = $params['input_cc'];
1892                $subject = $params['input_subject'];
1893                $msg_uid = $params['msg_id'];
1894                $body = $params['body'];
1895                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
1896                $body = preg_replace("/\n/"," ",$body);
1897                $body = preg_replace("/\r/","",$body);
1898                $forwarding_attachments = $params['forwarding_attachments'];
1899                $attachments = $params['FILES'];
1900                $return_files = $params['FILES'];
1901                 
1902                $folder = $params['folder'];
1903                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
1904                // Fix problem with cyrus delimiter changes.
1905                // Dots in names: enabled/disabled.                             
1906                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1907                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1908                // End Fix.
1909                                       
1910                $mail->SaveMessageInFolder = $folder;
1911                $mail->SMTPDebug = false;
1912                                               
1913                $mail->IsSMTP();
1914                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1915                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1916                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1917                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1918               
1919                $mail->Sender = $mail->From;
1920                $mail->SenderName = $mail->FromName;
1921                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1922                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
1923                               
1924                $this->add_recipients("to", $toaddress, &$mail);
1925                $this->add_recipients("cc", $ccaddress, &$mail);
1926                $mail->Subject = $subject;
1927                $mail->IsHTML(true);
1928                $mail->Body = $body;
1929               
1930                //      Build CID for embedded Images!!!
1931                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
1932                $cid_imgs = '';
1933                $name_cid_files = array();
1934                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1935                $cid_array = array();
1936                foreach($cid_imgs[6] as $j => $val){
1937                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
1938                        {
1939                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
1940                        }
1941                        $cid = $cid_array[$cid_imgs[4][$j].$val];
1942                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
1943                       
1944                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
1945                                {
1946                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
1947                                        //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
1948                                        $fileName = "image_".($j).".jpg";
1949                                        $fileCode = "base64";
1950                                        $fileType = "image/jpg";
1951                                        $file_attached[0] = $cid_imgs[2][$j];
1952                                        $file_attached[1] = $cid_imgs[4][$j];
1953                                        $file_attached[2] = $fileName;
1954                                        $file_attached[3] = $cid_imgs[6][$j];
1955                                        $file_attached[4] = 'base64';
1956                                        $file_attached[5] = strlen($fileContent); //Size of file
1957                                        $return_forward[] = $file_attached;
1958                                }
1959                                else
1960                                {
1961                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
1962                                        $file_description = unserialize(rawurldecode($attach_img));
1963                                        foreach($file_description as $i => $descriptor){                               
1964                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
1965                                        }
1966                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
1967                                        $fileName = $file_description[2];
1968                                        $fileCode = $file_description[4];
1969                                        $fileType = $this->get_file_type($file_description[2]);
1970                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
1971                                        if (!empty($file_description))
1972                                        {
1973                                                $file_description[5] = strlen($fileContent); //Size of file
1974                                                $return_forward[] = $file_description;
1975                                        }
1976                                }
1977                                $tempDir = ini_get("session.save_path");
1978                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
1979                                $f = fopen($tempDir.'/'.$file,"w");
1980                                fputs($f,$fileContent);
1981                                fclose($f);
1982                                if ($fileContent)
1983                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
1984                                //else
1985                                //      return "Error loading image attachment content";                                               
1986
1987                }
1988       
1989        //      Build Forwarding Attachments!!!         
1990                if (count($forwarding_attachments) > 0)
1991                {
1992                        foreach($forwarding_attachments as $forwarding_attachment)
1993                        {
1994                                $file_description = unserialize(rawurldecode($forwarding_attachment));
1995                                $tmp = array_values($file_description);
1996                                foreach($file_description as $i => $descriptor){                               
1997                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1998                                }
1999                                $file_description = $tmp;
2000                               
2001                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2002                                $fileName = $file_description[2];
2003                               
2004                                $file_description[5] = strlen($fileContent); //Size of file
2005                                $return_forward[] = $file_description;
2006                       
2007                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2008                        }
2009                }
2010               
2011                if ((count($return_forward) > 0) && (count($return_files) > 0))
2012                        $return_files = array_merge_recursive($return_forward,$return_files);
2013                else
2014                        if (count($return_files) < 1)
2015                                $return_files = $return_forward;
2016       
2017                //      Build Uploading Attachments!!!
2018                if (count($attachments))
2019                        foreach ($attachments as $attach)
2020                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name                 
2021       
2022       
2023               
2024                if(!empty($mail->AltBody))
2025            $mail->ContentType = "multipart/alternative";
2026
2027                $mail->error_count = 0; // reset errors
2028                $mail->SetMessageType();
2029                $header = $mail->CreateHeader();
2030                $body = $mail->CreateBody();
2031
2032                $mbox_stream = $this->open_mbox($folder);       
2033                $new_header = str_replace("\n", "\r\n", $header);
2034                $new_body = str_replace("\n", "\r\n", $body);
2035                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2036                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2037                $return['msg_no'] = $status->uidnext - 1;
2038                $return['folder_id'] = $folder;
2039
2040                if($mbox_stream)
2041                        imap_close($mbox_stream);
2042                if (is_array($return_files))             
2043                        foreach ($return_files as $index => $_attachment) {
2044                                if (array_key_exists("name",$_attachment)){
2045                                unset($return_files[$index]);
2046                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2047                        }
2048                        else
2049                        {
2050                                unset($return_files[$index]);
2051                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2052                        }
2053                }
2054               
2055                $return['files'] = serialize($return_files);
2056                $return["subject"] = $subject;
2057                               
2058                if (!$return['append'])
2059                        $return['append'] = imap_last_error();
2060               
2061                return $return;
2062        }
2063       
2064        function set_messages_flag($params)
2065        {
2066                $folder = $params['folder'];
2067                $msgs_to_set = $params['msgs_to_set'];
2068                $flag = $params['flag'];
2069                $return = array();
2070                $return["msgs_to_set"] = $msgs_to_set;
2071                $return["flag"] = $flag;
2072               
2073                if(!$this->mbox && !is_resource($this->mbox))
2074                        $this->mbox = $this->open_mbox($folder);
2075               
2076                if ($flag == "unseen")
2077                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2078                elseif ($flag == "seen")
2079                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2080                elseif ($flag == "answered"){
2081                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2082                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2083                }
2084                elseif ($flag == "forwarded")
2085                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2086                elseif ($flag == "flagged")
2087                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2088                elseif ($flag == "unflagged") {
2089                        $flag_importance = false;
2090                        $msgs_number = explode(",",$msgs_to_set);
2091                        $unflagged_msgs = "";
2092                        foreach($msgs_number as $msg_number) {
2093                                preg_match('/importance *: *(.*)\r/i',
2094                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2095                                        ,$importance);         
2096                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2097                                        $flag_importance=true;
2098                                }
2099                                else {
2100                                        $unflagged_msgs.=$msg_number.",";
2101                                }                               
2102                        }
2103
2104                        if($unflagged_msgs!="") {
2105                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2106                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2107                        }
2108                        else {
2109                                $return["msgs_unflageds"] = false;
2110                        }
2111
2112                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2113                                $return["status"] = false;
2114                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2115                        }
2116                        else {
2117                                $return["status"] = true;
2118                        }
2119                }
2120               
2121                if($this->mbox && is_resource($this->mbox))
2122                        imap_close($this->mbox);
2123                return $return;
2124        }
2125       
2126        function get_file_type($file_name)
2127        {
2128                $file_name = strtolower($file_name);
2129                $strFileType = strrev(substr(strrev($file_name),0,4));
2130                if ($strFileType == ".asf")
2131                        return "video/x-ms-asf";
2132                if ($strFileType == ".avi")
2133                        return "video/avi";
2134                if ($strFileType == ".doc")
2135                        return "application/msword";
2136                if ($strFileType == ".zip")
2137                        return "application/zip";
2138                if ($strFileType == ".xls")
2139                        return "application/vnd.ms-excel";
2140                if ($strFileType == ".gif")
2141                        return "image/gif";
2142                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2143                        return "image/jpeg";
2144                if ($strFileType == ".png")
2145                        return "image/png";
2146                if ($strFileType == ".wav")
2147                        return "audio/wav";
2148                if ($strFileType == ".mp3")
2149                        return "audio/mpeg3";
2150                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2151                        return "video/mpeg";
2152                if ($strFileType == ".rtf")
2153                        return "application/rtf";
2154                if ($strFileType == ".htm" || $strFileType == "html")
2155                        return "text/html";
2156                if ($strFileType == ".xml")
2157                        return "text/xml";
2158                if ($strFileType == ".xsl")
2159                        return "text/xsl";
2160                if ($strFileType == ".css")
2161                        return "text/css";
2162                if ($strFileType == ".php")
2163                        return "text/php";
2164                if ($strFileType == ".asp")
2165                        return "text/asp";
2166                if ($strFileType == ".pdf")
2167                        return "application/pdf";
2168                if ($strFileType == ".txt")
2169                        return "text/plain";
2170                if ($strFileType == ".wmv")
2171                        return "video/x-ms-wmv";
2172                if ($strFileType == ".sxc")
2173                        return "application/vnd.sun.xml.calc";
2174                if ($strFileType == ".stc")
2175                        return "application/vnd.sun.xml.calc.template";
2176                if ($strFileType == ".sxd")
2177                        return "application/vnd.sun.xml.draw";
2178                if ($strFileType == ".std")
2179                        return "application/vnd.sun.xml.draw.template";
2180                if ($strFileType == ".sxi")
2181                        return "application/vnd.sun.xml.impress";
2182                if ($strFileType == ".sti")
2183                        return "application/vnd.sun.xml.impress.template";
2184                if ($strFileType == ".sxm")
2185                        return "application/vnd.sun.xml.math";
2186                if ($strFileType == ".sxw")
2187                        return "application/vnd.sun.xml.writer";
2188                if ($strFileType == ".sxq")
2189                        return "application/vnd.sun.xml.writer.global";
2190                if ($strFileType == ".stw")
2191                        return "application/vnd.sun.xml.writer.template";
2192               
2193               
2194                return "application/octet-stream";             
2195        }
2196       
2197        function htmlspecialchars_encode($str)
2198        {
2199                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
2200        }
2201        function htmlspecialchars_decode($str)
2202        {
2203                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
2204        }
2205       
2206        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2207        {
2208                if(!$this->mbox || !is_resource($this->mbox))
2209                        $this->mbox = $this->open_mbox($folder);
2210
2211                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2212        }
2213       
2214        function get_info_next_msg($params)
2215        {
2216                $msg_number = $params['msg_number'];
2217                $folder = $params['msg_folder'];
2218                $sort_box_type = $params['sort_box_type'];
2219                $sort_box_reverse = $params['sort_box_reverse'];
2220                $reuse_border = $params['reuse_border'];
2221                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2222                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);                             
2223               
2224                $success = false;
2225                if (is_array($sort_array_msg))
2226                {
2227                        foreach ($sort_array_msg as $i => $value){
2228                                if ($value == $msg_number)
2229                                {
2230                                        $success = true;
2231                                        break;
2232                                }
2233                        }
2234                }
2235
2236                if (! $success || $i >= sizeof($sort_array_msg)-1)
2237                {
2238                        $params['status'] = 'false';
2239                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2240                        return $params;
2241                }
2242               
2243                $params = array();
2244                $params['msg_number'] = $sort_array_msg[($i+1)];
2245                $params['msg_folder'] = $folder;
2246               
2247                $return = $this->get_info_msg($params);         
2248                $return["reuse_border"] = $reuse_border;
2249                return $return;
2250        }
2251
2252        function get_info_previous_msg($params)
2253        {
2254                $msg_number = $params['msgs_number'];
2255                $folder = $params['folder'];
2256                $sort_box_type = $params['sort_box_type'];
2257                $sort_box_reverse = $params['sort_box_reverse'];
2258                $reuse_border = $params['reuse_border'];
2259                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2260                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2261               
2262                $success = false;
2263                if (is_array($sort_array_msg))
2264                {
2265                        foreach ($sort_array_msg as $i => $value){
2266                                if ($value == $msg_number)
2267                                {
2268                                        $success = true;
2269                                        break;
2270                                }
2271                        }
2272                }
2273                if (! $success || $i == 0)
2274                {
2275                        $params['status'] = 'false';
2276                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2277                        return $params;
2278                }
2279               
2280                $params = array();
2281                $params['msg_number'] = $sort_array_msg[($i-1)];
2282                $params['msg_folder'] = $folder;
2283               
2284                $return = $this->get_info_msg($params);
2285                $return["reuse_border"] = $reuse_border;
2286                return $return;
2287        }
2288       
2289        // This function updates the values: quota, paging and new messages menu.
2290        function get_menu_values($params){
2291                $return_array = array();
2292                $return_array = $this->get_quota($params);
2293               
2294                $mbox_stream = $this->open_mbox($params['folder']);
2295                $return_array['num_msgs'] = imap_num_msg($mbox_stream);         
2296                if($mbox_stream)
2297                        imap_close($mbox_stream);
2298                               
2299                return $return_array;
2300        }
2301       
2302        function get_quota($params){
2303                // folder_id = user/{uid} for shared folders
2304                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
2305                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
2306                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];             
2307                }
2308                // folder_id = INBOX for inbox folders
2309                else
2310                        $folder_id = "INBOX";
2311               
2312                if(!$this->mbox)
2313                        $this->mbox = $this->open_mbox();
2314
2315                $quota = imap_get_quotaroot($this->mbox, $folder_id);
2316                if($this->mbox && is_resource($this->mbox))
2317                        imap_close($this->mbox);
2318                       
2319                if (!$quota){
2320                        return array(
2321                                'quota_percent' => 0,
2322                                'quota_used' => 0,
2323                                'quota_limit' =>  0
2324                        );
2325                }
2326               
2327                if(count($quota) && $quota['limit']) {
2328                        $quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
2329                        $quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
2330                        if($quota_used >= $quota_limit)
2331                        {
2332                                $quotaPercent = 100;
2333                        }
2334                        else
2335                        {
2336                        $quotaPercent = ($quota_used / $quota_limit)*100;
2337                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
2338                        }
2339                        return array(
2340                                'quota_percent' => floor($quotaPercent),
2341                                'quota_used' => floor($quota_used),
2342                                'quota_limit' =>  floor($quota_limit)
2343                        );
2344                }
2345                else
2346                        return array();
2347        }
2348       
2349        function send_notification($params){
2350                require_once("class.phpmailer.php");
2351                $mail = new PHPMailer();
2352                 
2353                $toaddress = $params['notificationto'];
2354               
2355                $subject = 'Confirmação de leitura: ' . $params['subject'];
2356                $body = 'Sua mensagem: ' . $params['subject'] . '<br>';
2357                $body .= 'foi lida por: ' . $_SESSION['phpgw_info']['expressomail']['user']['fullname'] . ' &lt;' . $_SESSION['phpgw_info']['expressomail']['user']['email'] . '&gt; em ' . date("d/m/Y H:i");
2358                $mail->SMTPDebug = false;
2359                $mail->IsSMTP();
2360                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2361                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2362                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2363                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2364                $mail->AddAddress($toaddress);
2365                $mail->Subject = $this->htmlspecialchars_decode($subject);
2366
2367                $mail->IsHTML(true);
2368                $mail->Body = $body;
2369               
2370                if(!$mail->Send()){
2371                        return $mail->ErrorInfo;
2372                }
2373                else
2374                        return true;
2375        }
2376       
2377        function empty_trash()
2378        {
2379                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
2380                $mbox_stream = $this->open_mbox($folder);
2381                $return = imap_delete($mbox_stream,'1:*');
2382                if($mbox_stream)
2383                        imap_close($mbox_stream, CL_EXPUNGE);
2384                return $return;
2385        }
2386       
2387        function search($params)
2388        {
2389                include("class.imap_attachment.inc.php");
2390                $imap_attachment = new imap_attachment();                               
2391                $criteria = $params['criteria'];
2392                $return = array();
2393                $folders = $this->get_folders_list();
2394               
2395                $j = 0;
2396                foreach($folders as $folder)
2397                {
2398                        $mbox_stream = $this->open_mbox($folder);
2399                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
2400                       
2401                        if ($messages == '')
2402                                continue;
2403               
2404                        $i = 0;
2405                        $return[$j] = array();
2406                        $return[$j]['folder_name'] = $folder['name'];
2407                       
2408                        foreach($messages as $msg_number)
2409                        {
2410                                $header = $this->get_header($msg_number);
2411                                if (!is_object($header))
2412                                        return false;
2413                               
2414                                $return[$j][$i]['msg_folder']   = $folder['name'];
2415                                $return[$j][$i]['msg_number']   = $msg_number;
2416                                $return[$j][$i]['Recent']               = $header->Recent;
2417                                $return[$j][$i]['Unseen']               = $header->Unseen;
2418                                $return[$j][$i]['Answered']     = $header->Answered;
2419                                $return[$j][$i]['Deleted']              = $header->Deleted;
2420                                $return[$j][$i]['Draft']                = $header->Draft;
2421                                $return[$j][$i]['Flagged']              = $header->Flagged;
2422       
2423                                $date_msg = gmdate("d/m/Y",$header->udate);
2424                                if (gmdate("d/m/Y") == $date_msg)
2425                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
2426                                else
2427                                        $return[$j][$i]['udate'] = $date_msg;
2428                       
2429                                $fromaddress = imap_mime_header_decode($header->fromaddress);
2430                                $return[$j][$i]['fromaddress'] = '';
2431                                foreach ($fromaddress as $tmp)
2432                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
2433                       
2434                                $from = $header->from;
2435                                $return[$j][$i]['from'] = array();
2436                                $tmp = imap_mime_header_decode($from[0]->personal);
2437                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
2438                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
2439                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
2440
2441                                $to = $header->to;
2442                                $return[$j][$i]['to'] = array();
2443                                $tmp = imap_mime_header_decode($to[0]->personal);
2444                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
2445                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
2446                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
2447
2448                                $subject = imap_mime_header_decode($header->fetchsubject);
2449                                $return[$j][$i]['subject'] = '';
2450                                foreach ($subject as $tmp)
2451                                        $return[$j][$i]['subject'] .= $tmp->text;
2452
2453                                $return[$j][$i]['Size'] = $header->Size;
2454                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
2455                       
2456                                $return[$j][$i]['attachment'] = array();
2457                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
2458                                               
2459                                $i++;
2460                        }
2461                        $j++;
2462                        if($mbox_stream)
2463                                imap_close($mbox_stream);
2464                }
2465       
2466                return $return;
2467        }
2468       
2469        function delete_and_show_previous_message($params)
2470        {
2471                $return = $this->get_info_previous_msg($params);
2472               
2473                $params_tmp1 = array();
2474                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
2475                $params_tmp1['folder'] = $params['msg_folder'];
2476                $return_tmp1 = $this->delete_msg($params_tmp1);
2477               
2478                $return['msg_number_deleted'] = $return_tmp1;
2479               
2480                return $return;
2481        }
2482               
2483       
2484        function automatic_trash_cleanness($params)
2485        {
2486                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
2487                $criteria =  'BEFORE "'.$before_date.'"';
2488                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
2489                $messages = imap_search($mbox_stream, $criteria, SE_UID);
2490                if (is_array($messages)){
2491                        foreach ($messages as $msg_number){
2492                                imap_delete($mbox_stream, $msg_number, FT_UID);
2493                        }
2494                }
2495                if($mbox_stream)
2496                        imap_close($mbox_stream, CL_EXPUNGE);
2497                return $messages;
2498        }
2499//      Fix the search problem with special characters!!!!
2500        function remove_accents($string) {
2501                return strtr($string,
2502                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
2503                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
2504        }
2505
2506        function search_msg($params = ''){             
2507                $retorno = "";
2508                $mbox_stream = "";
2509                if(strpos($params['condition'],"#")===false) { //local messages
2510                        $search=false;
2511                }
2512                else {
2513                        $search = explode(",",$params['condition']);                   
2514                }
2515
2516                if($search){
2517                        $search_criteria = '';
2518                        foreach($search as $tmp)
2519                        {
2520                                $tmp1 = explode("##",$tmp);
2521                                $name_box = $tmp1[0];
2522                                unset($filter);
2523                                foreach($tmp1 as $index => $criteria)
2524                                {
2525                                        if ($index != 0 && strlen($criteria) != 0)
2526                                        {
2527                                                $filter_array = explode("<=>",rawurldecode($criteria));
2528                                                $filter .= " ".$filter_array[0];
2529                                                $filter .= '"'.$filter_array[1].'"';
2530                                        }
2531                                }               
2532                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
2533                                $filter = $this->remove_accents($filter);
2534                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
2535                                $folder_name = explode($this->imap_delimiter,$name_box);
2536                                if (is_numeric($folder_name[1])) {
2537                                        $this->ldap = new ldap_functions();
2538                                        if ($cn = $this->ldap->uid2cn($folder_name[1])) {
2539                                                $folder_name[1] = $cn;
2540                                        }
2541                                }
2542                                $folder_name = implode($this->imap_delimiter,$folder_name);
2543                               
2544                                if(!is_resource($mbox_stream))
2545                                        $mbox_stream = $this->open_mbox($name_box);
2546                                else
2547                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
2548                       
2549                                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search   
2550                               
2551                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
2552                                        foreach($all_criterias as $criteria_fixed)
2553                                        {
2554                                                $_filter = $criteria_fixed . substr($filter,4);
2555                                       
2556                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
2557                                               
2558                                                if($search_criteria && count($search_criteria) < 50)
2559                                                {
2560                                                        foreach($search_criteria as $new_search){
2561                                                                $m_token = trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--".$new_search."##"."\n");
2562                                                                if(!@strstr($retorno,$m_token))
2563                                                                        $retorno .= $m_token;
2564                                                        }
2565                                                }                                               
2566                                                else if(count($search_criteria) >= 50)                                                 
2567                                                        return "many results";                                         
2568                                        }
2569                                }
2570                                else {
2571                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
2572                                        if( is_array( $search_criteria) )
2573                                        {
2574                                                foreach($search_criteria as $new_search)
2575                                                        $retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
2576                                        }
2577                                }
2578                        }
2579                }
2580                if($mbox_stream)
2581                        imap_close($mbox_stream);               
2582                                               
2583                return $retorno ? $retorno : "none";
2584        }
2585       
2586        function get_msg($uid_msg,$name_box, $mbox_stream )
2587        {
2588                $header = $this->get_header($uid_msg);
2589                include_once("class.imap_attachment.inc.php");
2590                $imap_attachment = new imap_attachment();
2591                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
2592                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
2593                $flag = $header->Unseen
2594                        .$header->Recent
2595                        .$header->Flagged
2596                        .$header->Draft
2597                        .$header->Answered
2598                        .$header->Deleted
2599                        .$attachments;
2600
2601
2602                $subject = $this->decode_string($header->fetchsubject);
2603                $from = $header->from[0]->mailbox;
2604                if($header->from[0]->personal != "")
2605                        $from = $header->from[0]->personal;
2606                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size) ."--". $flag;
2607                return $ret_msg;                   
2608        }       
2609
2610        function size_msg($size){
2611                $var = floor($size/1024);
2612                if($var >= 1){
2613                        return $var." kb";     
2614                }else{
2615                        return $size ." b";     
2616                }
2617        }
2618
2619        function ob_array($the_object)
2620        {
2621           $the_array=array();
2622           if(!is_scalar($the_object))
2623           {
2624               foreach($the_object as $id => $object)
2625               {
2626                   if(is_scalar($object))
2627                   {
2628                       $the_array[$id]=$object;
2629                   }
2630                   else
2631                   {
2632                       $the_array[$id]=$this->ob_array($object);
2633                   }
2634               }
2635               return $the_array;
2636           }
2637           else
2638           {
2639               return $the_object;
2640           }
2641        }
2642       
2643        function getacl()
2644        {
2645                $this->ldap = new ldap_functions();
2646               
2647                $return = array();
2648                $mbox_stream = $this->open_mbox();     
2649                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
2650               
2651                $i = 0;
2652                foreach ($mbox_acl as $user => $acl)
2653                {
2654                        if ($user != $this->username)
2655                        {
2656                                $return[$i]['uid'] = $user;
2657                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
2658                        }
2659                        $i++;
2660                }
2661                return $return;
2662        }
2663       
2664        function setacl($params)
2665        {
2666                $old_users = $this->getacl();
2667                if (!count($old_users))
2668                        $old_users = array();
2669               
2670                $tmp_array = array();
2671                foreach ($old_users as $index => $user_info)
2672                {
2673                        $tmp_array[$index] = $user_info['uid'];
2674                }
2675                $old_users = $tmp_array;
2676               
2677                $users = unserialize($params['users']);
2678                if (!count($users))
2679                        $users = array();
2680               
2681                //$add_share = array_diff($users, $old_users);
2682                $remove_share = array_diff($old_users, $users);
2683
2684                $mbox_stream = $this->open_mbox();
2685
2686                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2687                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
2688
2689                /*if (count($add_share))
2690                {
2691                        foreach ($add_share as $index=>$uid)
2692                        {
2693                        if (is_array($mailboxes_list))
2694                        {
2695                        foreach ($mailboxes_list as $key => $val)
2696                        {
2697                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
2698                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
2699                        }
2700                        }
2701                        }
2702                }*/
2703               
2704                if (count($remove_share))
2705                {
2706                        foreach ($remove_share as $index=>$uid)
2707                        {
2708                        if (is_array($mailboxes_list))
2709                        {
2710                        foreach ($mailboxes_list as $key => $val)
2711                        {
2712                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
2713                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
2714                        }
2715                        }
2716                        }       
2717                }
2718               
2719                return true;
2720        }
2721       
2722        function getaclfromuser($params)
2723        {
2724                $useracl = $params['user'];
2725               
2726                $return = array();
2727                $return[$useracl] = 'false';
2728                $mbox_stream = $this->open_mbox();     
2729                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
2730               
2731                foreach ($mbox_acl as $user => $acl)
2732                {
2733                        if (($user != $this->username) && ($user == $useracl))
2734                        {
2735                                $return[$user] = $acl;
2736                        }
2737                }
2738                return $return;
2739        }
2740
2741        function getacltouser($user)
2742        {
2743                $return = array();
2744                $mbox_stream = $this->open_mbox();
2745                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
2746                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
2747                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
2748                if(substr($user,0,4) != 'user')
2749                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
2750                else
2751                  $mbox_acl = imap_getacl($mbox_stream, $user);
2752                return $mbox_acl[$this->username];
2753        }
2754       
2755
2756        function setaclfromuser($params)
2757        {
2758                $user = $params['user'];
2759                $acl = $params['acl'];
2760               
2761                $mbox_stream = $this->open_mbox();
2762
2763                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2764                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
2765
2766                if (is_array($mailboxes_list))
2767                {
2768                        foreach ($mailboxes_list as $key => $val)
2769                        {
2770                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
2771                                $folder = str_replace("&-", "&", $folder);
2772                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
2773                                {
2774                                        $return = imap_last_error();
2775                                }
2776                        }
2777                }
2778                if (isset($return))
2779                        return $return;
2780                else
2781                        return true;
2782        }
2783       
2784        function download_attachment($msg,$msgno)
2785        {
2786                $array_parts_attachments = array();             
2787                $array_parts_attachments['names'] = '';
2788                include_once("class.imap_attachment.inc.php");
2789                $imap_attachment = new imap_attachment();               
2790               
2791                if (count($msg->fname[$msgno]) > 0)
2792                {
2793                        $i = 0;
2794                        foreach ($msg->fname[$msgno] as $index=>$fname)
2795                        {
2796                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
2797                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($fname);
2798                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
2799                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
2800                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
2801                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
2802                                $i++;
2803                        }
2804                }
2805                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
2806                return $array_parts_attachments;
2807        }       
2808
2809        function spam($params)
2810        {
2811                $is_spam = $params['spam'];
2812                $folder = $params['folder'];
2813                $mbox_stream = $this->open_mbox($folder);
2814                $msgs_number = explode(',',$params['msgs_number']);
2815
2816                foreach($msgs_number as $msg_number) {
2817                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
2818                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
2819                        $body = imap_body($mbox_stream, $imap_msg_number);
2820                        $msg = $header . $body;
2821                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2822                        $username = $this->username;
2823                        strtok($email, '@');
2824                        $domain = strtok('@');
2825
2826                        //Encontrar a assinatura do dspam no cabecalho
2827                        $v = explode("\r\n", $header);
2828                        foreach ($v as $linha){
2829                                if (eregi("^Message-ID", $linha)) {
2830                                        $args = explode(" ", $linha);
2831                                        $msg_id = "'$args[1]'";
2832                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
2833                                        $args = explode(" ",$linha);
2834                                        $signature = $args[1];
2835                                }
2836                        }
2837
2838                        // Seleciona qual comando a ser executado
2839                        switch($is_spam){
2840                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
2841                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
2842                        }
2843
2844                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
2845                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
2846                        system($cmd);
2847                }
2848                imap_close($mbox_stream);
2849                return false;
2850        }
2851        function get_header($msg_number){
2852                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
2853                if (!is_object($header))
2854                        return false;
2855                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
2856                $pdate = date_parse($header->MailDate);
2857                $header->udate +=  $pdate['zone']*(-60);
2858               
2859                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2860                        $flag = preg_match('/importance *: *(.*)\r/i',
2861                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2862                                                ,$importance);         
2863                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
2864                }
2865               
2866                return $header;
2867        }
2868}
2869?>
Note: See TracBrowser for help on using the repository browser.