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

Revision 990, 98.3 KB checked in by amuller, 15 years ago (diff)

Ticket #545 - Refazendo código da revisão número [658]

  • 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 ($sort_box_type != "SORTFROM"){
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                        $slice_array = true;
1665
1666                        for ($i=$num_msgs; $i>0; $i--)
1667                        {
1668                                if ($sort_box_type == "SORTARRIVAL" && $sort_box_reverse && count($sort) >= $offsetEnd)
1669                                        break;
1670                                $iuid = @imap_uid($this->mbox,$i);
1671                                $header = $this->get_header($iuid);
1672                                // List UNSEEN messages.
1673                                if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
1674                                        continue;
1675                                }
1676                                // List SEEN messages.
1677                                elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
1678                                        continue;
1679                                }
1680                                // List ANSWERED messages.
1681                                elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
1682                                        continue;
1683                                }
1684                                // List FLAGGED messages.
1685                                elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
1686                                        continue;
1687                                }
1688
1689                                if($sort_box_type=='SORTFROM') {
1690                                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
1691                                                $from = $header->to;
1692                                        else
1693                                                $from = $header->from;
1694
1695                                        $tmp = imap_mime_header_decode($from[0]->personal);
1696
1697                                        if ($tmp[0]->text != "")
1698                                                $sort[$iuid] = $tmp[0]->text;
1699                                        else
1700                                                $sort[$iuid] = $from[0]->mailbox . "@" . $from[0]->host;
1701                                }
1702                                else if($sort_box_type=='SORTSUBJECT') {
1703                                        $sort[$iuid] = $header->subject;
1704                                }
1705                                else if($sort_box_type=='SORTSIZE') {
1706                                        $sort[$iuid] = $header->Size;
1707                                }
1708                                else {
1709                                        $sort[$iuid] = $header->udate;
1710                                }
1711
1712                        }
1713                        natcasesort($sort);
1714
1715                        if ($sort_box_reverse)
1716                                $sort = array_reverse($sort,true);
1717                }
1718
1719                if(!is_array($sort))
1720                        $sort = array();
1721                       
1722                if ($slice_array)
1723                        $sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
1724                       
1725
1726                return $sort;
1727
1728        }
1729
1730
1731        function move_search_messages($params){         
1732                $params['selected_messages'] = urldecode($params['selected_messages']);
1733                $params['new_folder'] = urldecode($params['new_folder']);
1734                $params['new_folder_name'] = urldecode($params['new_folder_name']);
1735                $sel_msgs = explode(",", $params['selected_messages']);
1736                @reset($sel_msgs);     
1737                $sorted_msgs = array();
1738                foreach($sel_msgs as $idx => $sel_msg) {
1739                        $sel_msg = explode(";", $sel_msg);
1740                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
1741                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
1742                         }     
1743                         else {
1744                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
1745                         }
1746                }
1747                @ksort($sorted_msgs);
1748                $last_return = false;           
1749                foreach($sorted_msgs as $folder => $msgs_number) {                     
1750                        $params['msgs_number'] = $msgs_number;
1751                        $params['folder'] = $folder;   
1752                        if($params['new_folder'] && $folder != $params['new_folder']){
1753                                $last_return = $this -> move_messages($params);                         
1754                        }
1755                        elseif(!$params['new_folder'] || $params['delete'] ){
1756                                $last_return = $this -> delete_msgs($params);
1757                                $last_return['deleted'] = true;
1758                        }
1759                }
1760                return $last_return;
1761        }
1762       
1763        function move_messages($params)
1764        {
1765                $folder = $params['folder'];           
1766                $mbox_stream = $this->open_mbox($folder);               
1767                $newmailbox = ($params['new_folder']);
1768                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
1769                $new_folder_name = $params['new_folder_name'];
1770                $msgs_number = $params['msgs_number'];
1771                $return = array('msgs_number' => $msgs_number,
1772                                                'folder' => $folder,
1773                                                'new_folder_name' => $new_folder_name,
1774                                                'border_ID' => $params['border_ID'],
1775                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
1776               
1777                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
1778        if (substr($folder,0,4) == 'user'){
1779                $acl = $this->getacltouser($folder);
1780                /*
1781                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
1782                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
1783                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
1784                 *   w - write (STORE flags other than SEEN and DELETED)
1785                 *   i - insert (perform APPEND, COPY into mailbox)
1786                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
1787                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
1788                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
1789                 *   a - administer (perform SETACL)
1790                        */
1791                        if (strpos($acl, "d") === false){
1792                                $return['status'] = false;
1793                                return $return;
1794                        }
1795        }
1796        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
1797        if (substr($new_folder_name,0,4) == 'user'){
1798                $this->ldap = new ldap_functions();
1799                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
1800                        $return['new_folder_name'] = array_pop($tmp_folder_name);
1801                        if (is_numeric($return['new_folder_name']))
1802                                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
1803                                        $return['new_folder_name'] = $cn;
1804        }
1805               
1806                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.         
1807                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
1808                {
1809                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1810                        // Fix problem in unserialize function JS.
1811                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1812                }
1813               
1814                $mbox_stream = $this->open_mbox($folder);       
1815                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1816                        imap_expunge($mbox_stream);
1817                        if($mbox_stream)
1818                                imap_close($mbox_stream);
1819                        return $return;
1820                }else {
1821                        if(strstr(imap_last_error(),'Over quota')) {                           
1822                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
1823                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];                                                                       
1824                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];                                                           
1825                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1826                                $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()))));
1827                                if(!$mbox)
1828                                        return imap_last_error();
1829                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");                           
1830                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
1831                                        if($mbox_stream)
1832                                                imap_close($mbox_stream);
1833                                        if($mbox)                                                                       
1834                                                imap_close($mbox);
1835                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";                                                               
1836                                }
1837                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1838                                        imap_expunge($mbox_stream);
1839                                        if($mbox_stream)
1840                                                imap_close($mbox_stream);
1841                                        // return to original quota limit.
1842                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
1843                                                if($mbox)
1844                                                        imap_close($mbox);
1845                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
1846                                        }
1847                                        return $return;                                                                                                 
1848                                }
1849                                else {
1850                                        if($mbox_stream)
1851                                                imap_close($mbox_stream);
1852                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
1853                                                if($mbox)
1854                                                        imap_close($mbox);
1855                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
1856                                        }
1857                                        return imap_last_error();                               
1858                                }
1859                               
1860                        }
1861                        else {
1862                                if($mbox_stream)
1863                                        imap_close($mbox_stream);
1864                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
1865                        }
1866                }               
1867        }
1868       
1869        function save_msg($params)
1870        {
1871               
1872                include_once("class.phpmailer.php");
1873                $mail = new PHPMailer();
1874                include_once("class.db_functions.inc.php");
1875                $toaddress = $params['input_to'];
1876                $ccaddress = $params['input_cc'];
1877                $subject = $params['input_subject'];
1878                $msg_uid = $params['msg_id'];
1879                $body = $params['body'];
1880                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
1881                $body = preg_replace("/\n/"," ",$body);
1882                $body = preg_replace("/\r/","",$body);
1883                $forwarding_attachments = $params['forwarding_attachments'];
1884                $attachments = $params['FILES'];
1885                $return_files = $params['FILES'];
1886                 
1887                $folder = $params['folder'];
1888                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
1889                // Fix problem with cyrus delimiter changes.
1890                // Dots in names: enabled/disabled.                             
1891                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1892                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1893                // End Fix.
1894                                       
1895                $mail->SaveMessageInFolder = $folder;
1896                $mail->SMTPDebug = false;
1897                                               
1898                $mail->IsSMTP();
1899                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1900                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1901                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1902                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1903               
1904                $mail->Sender = $mail->From;
1905                $mail->SenderName = $mail->FromName;
1906                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1907                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
1908                               
1909                $this->add_recipients("to", $toaddress, &$mail);
1910                $this->add_recipients("cc", $ccaddress, &$mail);
1911                $mail->Subject = $subject;
1912                $mail->IsHTML(true);
1913                $mail->Body = $body;
1914               
1915                //      Build CID for embedded Images!!!
1916                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
1917                $cid_imgs = '';
1918                $name_cid_files = array();
1919                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1920                $cid_array = array();
1921                foreach($cid_imgs[6] as $j => $val){
1922                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
1923                        {
1924                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
1925                        }
1926                        $cid = $cid_array[$cid_imgs[4][$j].$val];
1927                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
1928                       
1929                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
1930                                {
1931                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
1932                                        //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
1933                                        $fileName = "image_".($j).".jpg";
1934                                        $fileCode = "base64";
1935                                        $fileType = "image/jpg";
1936                                        $file_attached[0] = $cid_imgs[2][$j];
1937                                        $file_attached[1] = $cid_imgs[4][$j];
1938                                        $file_attached[2] = $fileName;
1939                                        $file_attached[3] = $cid_imgs[6][$j];
1940                                        $file_attached[4] = 'base64';
1941                                        $file_attached[5] = strlen($fileContent); //Size of file
1942                                        $return_forward[] = $file_attached;
1943                                }
1944                                else
1945                                {
1946                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
1947                                        $file_description = unserialize(rawurldecode($attach_img));
1948                                        foreach($file_description as $i => $descriptor){                               
1949                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
1950                                        }
1951                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
1952                                        $fileName = $file_description[2];
1953                                        $fileCode = $file_description[4];
1954                                        $fileType = $this->get_file_type($file_description[2]);
1955                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
1956                                        if (!empty($file_description))
1957                                        {
1958                                                $file_description[5] = strlen($fileContent); //Size of file
1959                                                $return_forward[] = $file_description;
1960                                        }
1961                                }
1962                                $tempDir = ini_get("session.save_path");
1963                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
1964                                $f = fopen($tempDir.'/'.$file,"w");
1965                                fputs($f,$fileContent);
1966                                fclose($f);
1967                                if ($fileContent)
1968                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
1969                                //else
1970                                //      return "Error loading image attachment content";                                               
1971
1972                }
1973       
1974        //      Build Forwarding Attachments!!!         
1975                if (count($forwarding_attachments) > 0)
1976                {
1977                        foreach($forwarding_attachments as $forwarding_attachment)
1978                        {
1979                                $file_description = unserialize(rawurldecode($forwarding_attachment));
1980                                $tmp = array_values($file_description);
1981                                foreach($file_description as $i => $descriptor){                               
1982                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1983                                }
1984                                $file_description = $tmp;
1985                               
1986                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
1987                                $fileName = $file_description[2];
1988                               
1989                                $file_description[5] = strlen($fileContent); //Size of file
1990                                $return_forward[] = $file_description;
1991                       
1992                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
1993                        }
1994                }
1995               
1996                if ((count($return_forward) > 0) && (count($return_files) > 0))
1997                        $return_files = array_merge_recursive($return_forward,$return_files);
1998                else
1999                        if (count($return_files) < 1)
2000                                $return_files = $return_forward;
2001       
2002                //      Build Uploading Attachments!!!
2003                if (count($attachments))
2004                        foreach ($attachments as $attach)
2005                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name                 
2006       
2007       
2008               
2009                if(!empty($mail->AltBody))
2010            $mail->ContentType = "multipart/alternative";
2011
2012                $mail->error_count = 0; // reset errors
2013                $mail->SetMessageType();
2014                $header = $mail->CreateHeader();
2015                $body = $mail->CreateBody();
2016
2017                $mbox_stream = $this->open_mbox($folder);       
2018                $new_header = str_replace("\n", "\r\n", $header);
2019                $new_body = str_replace("\n", "\r\n", $body);
2020                $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2021                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2022                $return['msg_no'] = $status->uidnext - 1;
2023                $return['folder_id'] = $folder;
2024
2025                if($mbox_stream)
2026                        imap_close($mbox_stream);
2027                if (is_array($return_files))             
2028                        foreach ($return_files as $index => $_attachment) {
2029                                if (array_key_exists("name",$_attachment)){
2030                                unset($return_files[$index]);
2031                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2032                        }
2033                        else
2034                        {
2035                                unset($return_files[$index]);
2036                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2037                        }
2038                }
2039               
2040                $return['files'] = serialize($return_files);
2041                $return["subject"] = $subject;
2042                               
2043                if (!$return['append'])
2044                        $return['append'] = imap_last_error();
2045               
2046                return $return;
2047        }
2048       
2049        function set_messages_flag($params)
2050        {
2051                $folder = $params['folder'];
2052                $msgs_to_set = $params['msgs_to_set'];
2053                $flag = $params['flag'];
2054                $return = array();
2055                $return["msgs_to_set"] = $msgs_to_set;
2056                $return["flag"] = $flag;
2057               
2058                if(!$this->mbox && !is_resource($this->mbox))
2059                        $this->mbox = $this->open_mbox($folder);
2060               
2061                if ($flag == "unseen")
2062                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2063                elseif ($flag == "seen")
2064                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2065                elseif ($flag == "answered"){
2066                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2067                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2068                }
2069                elseif ($flag == "forwarded")
2070                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2071                elseif ($flag == "flagged")
2072                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2073                elseif ($flag == "unflagged") {
2074                        $flag_importance = false;
2075                        $msgs_number = explode(",",$msgs_to_set);
2076                        $unflagged_msgs = "";
2077                        foreach($msgs_number as $msg_number) {
2078                                preg_match('/importance *: *(.*)\r/i',
2079                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2080                                        ,$importance);         
2081                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2082                                        $flag_importance=true;
2083                                }
2084                                else {
2085                                        $unflagged_msgs.=$msg_number.",";
2086                                }                               
2087                        }
2088
2089                        if($unflagged_msgs!="") {
2090                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2091                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2092                        }
2093                        else {
2094                                $return["msgs_unflageds"] = false;
2095                        }
2096
2097                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2098                                $return["status"] = false;
2099                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2100                        }
2101                        else {
2102                                $return["status"] = true;
2103                        }
2104                }
2105               
2106                if($this->mbox && is_resource($this->mbox))
2107                        imap_close($this->mbox);
2108                return $return;
2109        }
2110       
2111        function get_file_type($file_name)
2112        {
2113                $file_name = strtolower($file_name);
2114                $strFileType = strrev(substr(strrev($file_name),0,4));
2115                if ($strFileType == ".asf")
2116                        return "video/x-ms-asf";
2117                if ($strFileType == ".avi")
2118                        return "video/avi";
2119                if ($strFileType == ".doc")
2120                        return "application/msword";
2121                if ($strFileType == ".zip")
2122                        return "application/zip";
2123                if ($strFileType == ".xls")
2124                        return "application/vnd.ms-excel";
2125                if ($strFileType == ".gif")
2126                        return "image/gif";
2127                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2128                        return "image/jpeg";
2129                if ($strFileType == ".png")
2130                        return "image/png";
2131                if ($strFileType == ".wav")
2132                        return "audio/wav";
2133                if ($strFileType == ".mp3")
2134                        return "audio/mpeg3";
2135                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2136                        return "video/mpeg";
2137                if ($strFileType == ".rtf")
2138                        return "application/rtf";
2139                if ($strFileType == ".htm" || $strFileType == "html")
2140                        return "text/html";
2141                if ($strFileType == ".xml")
2142                        return "text/xml";
2143                if ($strFileType == ".xsl")
2144                        return "text/xsl";
2145                if ($strFileType == ".css")
2146                        return "text/css";
2147                if ($strFileType == ".php")
2148                        return "text/php";
2149                if ($strFileType == ".asp")
2150                        return "text/asp";
2151                if ($strFileType == ".pdf")
2152                        return "application/pdf";
2153                if ($strFileType == ".txt")
2154                        return "text/plain";
2155                if ($strFileType == ".wmv")
2156                        return "video/x-ms-wmv";
2157                if ($strFileType == ".sxc")
2158                        return "application/vnd.sun.xml.calc";
2159                if ($strFileType == ".stc")
2160                        return "application/vnd.sun.xml.calc.template";
2161                if ($strFileType == ".sxd")
2162                        return "application/vnd.sun.xml.draw";
2163                if ($strFileType == ".std")
2164                        return "application/vnd.sun.xml.draw.template";
2165                if ($strFileType == ".sxi")
2166                        return "application/vnd.sun.xml.impress";
2167                if ($strFileType == ".sti")
2168                        return "application/vnd.sun.xml.impress.template";
2169                if ($strFileType == ".sxm")
2170                        return "application/vnd.sun.xml.math";
2171                if ($strFileType == ".sxw")
2172                        return "application/vnd.sun.xml.writer";
2173                if ($strFileType == ".sxq")
2174                        return "application/vnd.sun.xml.writer.global";
2175                if ($strFileType == ".stw")
2176                        return "application/vnd.sun.xml.writer.template";
2177               
2178               
2179                return "application/octet-stream";             
2180        }
2181       
2182        function htmlspecialchars_encode($str)
2183        {
2184                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
2185        }
2186        function htmlspecialchars_decode($str)
2187        {
2188                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
2189        }
2190       
2191        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$offsetBegin = 0,$offsetEnd = 0)
2192        {
2193                if(!$this->mbox || !is_resource($this->mbox))
2194                        $this->mbox = $this->open_mbox($folder);
2195
2196                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type,$offsetBegin,$offsetEnd);
2197        }
2198       
2199        function get_info_next_msg($params)
2200        {
2201                $msg_number = $params['msg_number'];
2202                $folder = $params['msg_folder'];
2203                $sort_box_type = $params['sort_box_type'];
2204                $sort_box_reverse = $params['sort_box_reverse'];
2205                $reuse_border = $params['reuse_border'];
2206                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2207                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);                             
2208               
2209                $success = false;
2210                if (is_array($sort_array_msg))
2211                {
2212                        foreach ($sort_array_msg as $i => $value){
2213                                if ($value == $msg_number)
2214                                {
2215                                        $success = true;
2216                                        break;
2217                                }
2218                        }
2219                }
2220
2221                if (! $success || $i >= sizeof($sort_array_msg)-1)
2222                {
2223                        $params['status'] = 'false';
2224                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2225                        return $params;
2226                }
2227               
2228                $params = array();
2229                $params['msg_number'] = $sort_array_msg[($i+1)];
2230                $params['msg_folder'] = $folder;
2231               
2232                $return = $this->get_info_msg($params);         
2233                $return["reuse_border"] = $reuse_border;
2234                return $return;
2235        }
2236
2237        function get_info_previous_msg($params)
2238        {
2239                $msg_number = $params['msgs_number'];
2240                $folder = $params['folder'];
2241                $sort_box_type = $params['sort_box_type'];
2242                $sort_box_reverse = $params['sort_box_reverse'];
2243                $reuse_border = $params['reuse_border'];
2244                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2245                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2246               
2247                $success = false;
2248                if (is_array($sort_array_msg))
2249                {
2250                        foreach ($sort_array_msg as $i => $value){
2251                                if ($value == $msg_number)
2252                                {
2253                                        $success = true;
2254                                        break;
2255                                }
2256                        }
2257                }
2258                if (! $success || $i == 0)
2259                {
2260                        $params['status'] = 'false';
2261                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2262                        return $params;
2263                }
2264               
2265                $params = array();
2266                $params['msg_number'] = $sort_array_msg[($i-1)];
2267                $params['msg_folder'] = $folder;
2268               
2269                $return = $this->get_info_msg($params);
2270                $return["reuse_border"] = $reuse_border;
2271                return $return;
2272        }
2273       
2274        // This function updates the values: quota, paging and new messages menu.
2275        function get_menu_values($params){
2276                $return_array = array();
2277                $return_array = $this->get_quota($params);
2278               
2279                $mbox_stream = $this->open_mbox($params['folder']);
2280                $return_array['num_msgs'] = imap_num_msg($mbox_stream);         
2281                if($mbox_stream)
2282                        imap_close($mbox_stream);
2283                               
2284                return $return_array;
2285        }
2286       
2287        function get_quota($params){
2288                // folder_id = user/{uid} for shared folders
2289                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
2290                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
2291                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];             
2292                }
2293                // folder_id = INBOX for inbox folders
2294                else
2295                        $folder_id = "INBOX";
2296               
2297                if(!$this->mbox)
2298                        $this->mbox = $this->open_mbox();
2299
2300                $quota = imap_get_quotaroot($this->mbox, $folder_id);
2301                if($this->mbox && is_resource($this->mbox))
2302                        imap_close($this->mbox);
2303                       
2304                if (!$quota){
2305                        return array(
2306                                'quota_percent' => 0,
2307                                'quota_used' => 0,
2308                                'quota_limit' =>  0
2309                        );
2310                }
2311               
2312                if(count($quota) && $quota['limit']) {
2313                        $quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
2314                        $quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
2315                        if($quota_used >= $quota_limit)
2316                        {
2317                                $quotaPercent = 100;
2318                        }
2319                        else
2320                        {
2321                        $quotaPercent = ($quota_used / $quota_limit)*100;
2322                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
2323                        }
2324                        return array(
2325                                'quota_percent' => floor($quotaPercent),
2326                                'quota_used' => floor($quota_used),
2327                                'quota_limit' =>  floor($quota_limit)
2328                        );
2329                }
2330                else
2331                        return array();
2332        }
2333       
2334        function send_notification($params){
2335                require_once("class.phpmailer.php");
2336                $mail = new PHPMailer();
2337                 
2338                $toaddress = $params['notificationto'];
2339               
2340                $subject = 'Confirmação de leitura: ' . $params['subject'];
2341                $body = 'Sua mensagem: ' . $params['subject'] . '<br>';
2342                $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");
2343                $mail->SMTPDebug = false;
2344                $mail->IsSMTP();
2345                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2346                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2347                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2348                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2349                $mail->AddAddress($toaddress);
2350                $mail->Subject = $this->htmlspecialchars_decode($subject);
2351
2352                $mail->IsHTML(true);
2353                $mail->Body = $body;
2354               
2355                if(!$mail->Send()){
2356                        return $mail->ErrorInfo;
2357                }
2358                else
2359                        return true;
2360        }
2361       
2362        function empty_trash()
2363        {
2364                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
2365                $mbox_stream = $this->open_mbox($folder);
2366                $return = imap_delete($mbox_stream,'1:*');
2367                if($mbox_stream)
2368                        imap_close($mbox_stream, CL_EXPUNGE);
2369                return $return;
2370        }
2371       
2372        function search($params)
2373        {
2374                include("class.imap_attachment.inc.php");
2375                $imap_attachment = new imap_attachment();                               
2376                $criteria = $params['criteria'];
2377                $return = array();
2378                $folders = $this->get_folders_list();
2379               
2380                $j = 0;
2381                foreach($folders as $folder)
2382                {
2383                        $mbox_stream = $this->open_mbox($folder);
2384                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
2385                       
2386                        if ($messages == '')
2387                                continue;
2388               
2389                        $i = 0;
2390                        $return[$j] = array();
2391                        $return[$j]['folder_name'] = $folder['name'];
2392                       
2393                        foreach($messages as $msg_number)
2394                        {
2395                                $header = $this->get_header($msg_number);
2396                                if (!is_object($header))
2397                                        return false;
2398                               
2399                                $return[$j][$i]['msg_folder']   = $folder['name'];
2400                                $return[$j][$i]['msg_number']   = $msg_number;
2401                                $return[$j][$i]['Recent']               = $header->Recent;
2402                                $return[$j][$i]['Unseen']               = $header->Unseen;
2403                                $return[$j][$i]['Answered']     = $header->Answered;
2404                                $return[$j][$i]['Deleted']              = $header->Deleted;
2405                                $return[$j][$i]['Draft']                = $header->Draft;
2406                                $return[$j][$i]['Flagged']              = $header->Flagged;
2407       
2408                                $date_msg = gmdate("d/m/Y",$header->udate);
2409                                if (gmdate("d/m/Y") == $date_msg)
2410                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
2411                                else
2412                                        $return[$j][$i]['udate'] = $date_msg;
2413                       
2414                                $fromaddress = imap_mime_header_decode($header->fromaddress);
2415                                $return[$j][$i]['fromaddress'] = '';
2416                                foreach ($fromaddress as $tmp)
2417                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
2418                       
2419                                $from = $header->from;
2420                                $return[$j][$i]['from'] = array();
2421                                $tmp = imap_mime_header_decode($from[0]->personal);
2422                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
2423                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
2424                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
2425
2426                                $to = $header->to;
2427                                $return[$j][$i]['to'] = array();
2428                                $tmp = imap_mime_header_decode($to[0]->personal);
2429                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
2430                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
2431                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
2432
2433                                $subject = imap_mime_header_decode($header->fetchsubject);
2434                                $return[$j][$i]['subject'] = '';
2435                                foreach ($subject as $tmp)
2436                                        $return[$j][$i]['subject'] .= $tmp->text;
2437
2438                                $return[$j][$i]['Size'] = $header->Size;
2439                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
2440                       
2441                                $return[$j][$i]['attachment'] = array();
2442                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
2443                                               
2444                                $i++;
2445                        }
2446                        $j++;
2447                        if($mbox_stream)
2448                                imap_close($mbox_stream);
2449                }
2450       
2451                return $return;
2452        }
2453       
2454        function delete_and_show_previous_message($params)
2455        {
2456                $return = $this->get_info_previous_msg($params);
2457               
2458                $params_tmp1 = array();
2459                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
2460                $params_tmp1['folder'] = $params['msg_folder'];
2461                $return_tmp1 = $this->delete_msg($params_tmp1);
2462               
2463                $return['msg_number_deleted'] = $return_tmp1;
2464               
2465                return $return;
2466        }
2467               
2468       
2469        function automatic_trash_cleanness($params)
2470        {
2471                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
2472                $criteria =  'BEFORE "'.$before_date.'"';
2473                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
2474                $messages = imap_search($mbox_stream, $criteria, SE_UID);
2475                if (is_array($messages)){
2476                        foreach ($messages as $msg_number){
2477                                imap_delete($mbox_stream, $msg_number, FT_UID);
2478                        }
2479                }
2480                if($mbox_stream)
2481                        imap_close($mbox_stream, CL_EXPUNGE);
2482                return $messages;
2483        }
2484//      Fix the search problem with special characters!!!!
2485        function remove_accents($string) {
2486                return strtr($string,
2487                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
2488                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
2489        }
2490
2491        function search_msg($params = ''){             
2492                $retorno = "";
2493                $mbox_stream = "";
2494                if(strpos($params['condition'],"#")===false) { //local messages
2495                        $search=false;
2496                }
2497                else {
2498                        $search = explode(",",$params['condition']);                   
2499                }
2500
2501                if($search){
2502                        $search_criteria = '';
2503                        foreach($search as $tmp)
2504                        {
2505                                $tmp1 = explode("##",$tmp);
2506                                $name_box = $tmp1[0];
2507                                unset($filter);
2508                                foreach($tmp1 as $index => $criteria)
2509                                {
2510                                        if ($index != 0 && strlen($criteria) != 0)
2511                                        {
2512                                                $filter_array = explode("<=>",rawurldecode($criteria));
2513                                                $filter .= " ".$filter_array[0];
2514                                                $filter .= '"'.$filter_array[1].'"';
2515                                        }
2516                                }               
2517                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
2518                                $filter = $this->remove_accents($filter);
2519                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
2520                                $folder_name = explode($this->imap_delimiter,$name_box);
2521                                if (is_numeric($folder_name[1])) {
2522                                        $this->ldap = new ldap_functions();
2523                                        if ($cn = $this->ldap->uid2cn($folder_name[1])) {
2524                                                $folder_name[1] = $cn;
2525                                        }
2526                                }
2527                                $folder_name = implode($this->imap_delimiter,$folder_name);
2528                               
2529                                if(!is_resource($mbox_stream))
2530                                        $mbox_stream = $this->open_mbox($name_box);
2531                                else
2532                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
2533                       
2534                                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search   
2535                               
2536                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
2537                                        foreach($all_criterias as $criteria_fixed)
2538                                        {
2539                                                $_filter = $criteria_fixed . substr($filter,4);
2540                                       
2541                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
2542                                               
2543                                                if($search_criteria && count($search_criteria) < 50)
2544                                                {
2545                                                        foreach($search_criteria as $new_search){
2546                                                                $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");
2547                                                                if(!@strstr($retorno,$m_token))
2548                                                                        $retorno .= $m_token;
2549                                                        }
2550                                                }                                               
2551                                                else if(count($search_criteria) >= 50)                                                 
2552                                                        return "many results";                                         
2553                                        }
2554                                }
2555                                else {
2556                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
2557                                        if( is_array( $search_criteria) )
2558                                        {
2559                                                foreach($search_criteria as $new_search)
2560                                                        $retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
2561                                        }
2562                                }
2563                        }
2564                }
2565                if($mbox_stream)
2566                        imap_close($mbox_stream);               
2567                                               
2568                return $retorno ? $retorno : "none";
2569        }
2570       
2571        function get_msg($uid_msg,$name_box, $mbox_stream )
2572        {
2573                $header = $this->get_header($uid_msg);
2574                include_once("class.imap_attachment.inc.php");
2575                $imap_attachment = new imap_attachment();
2576                $attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
2577                $attachments = $attachments['number_attachments'] > 0?"T".$attachments['number_attachments']:"";
2578                $flag = $header->Unseen
2579                        .$header->Recent
2580                        .$header->Flagged
2581                        .$header->Draft
2582                        .$header->Answered
2583                        .$header->Deleted
2584                        .$attachments;
2585
2586
2587                $subject = $this->decode_string($header->fetchsubject);
2588                $from = $header->from[0]->mailbox;
2589                if($header->from[0]->personal != "")
2590                        $from = $header->from[0]->personal;
2591                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size) ."--". $flag;
2592                return $ret_msg;                   
2593        }       
2594
2595        function size_msg($size){
2596                $var = floor($size/1024);
2597                if($var >= 1){
2598                        return $var." kb";     
2599                }else{
2600                        return $size ." b";     
2601                }
2602        }
2603
2604        function ob_array($the_object)
2605        {
2606           $the_array=array();
2607           if(!is_scalar($the_object))
2608           {
2609               foreach($the_object as $id => $object)
2610               {
2611                   if(is_scalar($object))
2612                   {
2613                       $the_array[$id]=$object;
2614                   }
2615                   else
2616                   {
2617                       $the_array[$id]=$this->ob_array($object);
2618                   }
2619               }
2620               return $the_array;
2621           }
2622           else
2623           {
2624               return $the_object;
2625           }
2626        }
2627       
2628        function getacl()
2629        {
2630                $this->ldap = new ldap_functions();
2631               
2632                $return = array();
2633                $mbox_stream = $this->open_mbox();     
2634                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
2635               
2636                $i = 0;
2637                foreach ($mbox_acl as $user => $acl)
2638                {
2639                        if ($user != $this->username)
2640                        {
2641                                $return[$i]['uid'] = $user;
2642                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
2643                        }
2644                        $i++;
2645                }
2646                return $return;
2647        }
2648       
2649        function setacl($params)
2650        {
2651                $old_users = $this->getacl();
2652                if (!count($old_users))
2653                        $old_users = array();
2654               
2655                $tmp_array = array();
2656                foreach ($old_users as $index => $user_info)
2657                {
2658                        $tmp_array[$index] = $user_info['uid'];
2659                }
2660                $old_users = $tmp_array;
2661               
2662                $users = unserialize($params['users']);
2663                if (!count($users))
2664                        $users = array();
2665               
2666                //$add_share = array_diff($users, $old_users);
2667                $remove_share = array_diff($old_users, $users);
2668
2669                $mbox_stream = $this->open_mbox();
2670
2671                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2672                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
2673
2674                /*if (count($add_share))
2675                {
2676                        foreach ($add_share as $index=>$uid)
2677                        {
2678                        if (is_array($mailboxes_list))
2679                        {
2680                        foreach ($mailboxes_list as $key => $val)
2681                        {
2682                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
2683                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
2684                        }
2685                        }
2686                        }
2687                }*/
2688               
2689                if (count($remove_share))
2690                {
2691                        foreach ($remove_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", "");
2699                        }
2700                        }
2701                        }       
2702                }
2703               
2704                return true;
2705        }
2706       
2707        function getaclfromuser($params)
2708        {
2709                $useracl = $params['user'];
2710               
2711                $return = array();
2712                $return[$useracl] = 'false';
2713                $mbox_stream = $this->open_mbox();     
2714                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
2715               
2716                foreach ($mbox_acl as $user => $acl)
2717                {
2718                        if (($user != $this->username) && ($user == $useracl))
2719                        {
2720                                $return[$user] = $acl;
2721                        }
2722                }
2723                return $return;
2724        }
2725
2726        function getacltouser($user)
2727        {
2728                $return = array();
2729                $mbox_stream = $this->open_mbox();
2730                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
2731                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
2732                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
2733                if(substr($user,0,4) != 'user')
2734                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
2735                else
2736                  $mbox_acl = imap_getacl($mbox_stream, $user);
2737                return $mbox_acl[$this->username];
2738        }
2739       
2740
2741        function setaclfromuser($params)
2742        {
2743                $user = $params['user'];
2744                $acl = $params['acl'];
2745               
2746                $mbox_stream = $this->open_mbox();
2747
2748                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2749                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
2750
2751                if (is_array($mailboxes_list))
2752                {
2753                        foreach ($mailboxes_list as $key => $val)
2754                        {
2755                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
2756                                $folder = str_replace("&-", "&", $folder);
2757                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
2758                                {
2759                                        $return = imap_last_error();
2760                                }
2761                        }
2762                }
2763                if (isset($return))
2764                        return $return;
2765                else
2766                        return true;
2767        }
2768       
2769        function download_attachment($msg,$msgno)
2770        {
2771                $array_parts_attachments = array();             
2772                $array_parts_attachments['names'] = '';
2773                include_once("class.imap_attachment.inc.php");
2774                $imap_attachment = new imap_attachment();               
2775               
2776                if (count($msg->fname[$msgno]) > 0)
2777                {
2778                        $i = 0;
2779                        foreach ($msg->fname[$msgno] as $index=>$fname)
2780                        {
2781                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
2782                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($fname);
2783                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
2784                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
2785                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
2786                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
2787                                $i++;
2788                        }
2789                }
2790                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
2791                return $array_parts_attachments;
2792        }       
2793
2794        function spam($params)
2795        {
2796                $is_spam = $params['spam'];
2797                $folder = $params['folder'];
2798                $mbox_stream = $this->open_mbox($folder);
2799                $msgs_number = explode(',',$params['msgs_number']);
2800
2801                foreach($msgs_number as $msg_number) {
2802                        $imap_msg_number = imap_msgno($mbox_stream, $msg_number);
2803                        $header = imap_fetchheader($mbox_stream, $imap_msg_number);
2804                        $body = imap_body($mbox_stream, $imap_msg_number);
2805                        $msg = $header . $body;
2806                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2807                        $username = $this->username;
2808                        strtok($email, '@');
2809                        $domain = strtok('@');
2810
2811                        //Encontrar a assinatura do dspam no cabecalho
2812                        $v = explode("\r\n", $header);
2813                        foreach ($v as $linha){
2814                                if (eregi("^Message-ID", $linha)) {
2815                                        $args = explode(" ", $linha);
2816                                        $msg_id = "'$args[1]'";
2817                                } elseif (eregi("^X-DSPAM-Signature", $linha)) {
2818                                        $args = explode(" ",$linha);
2819                                        $signature = $args[1];
2820                                }
2821                        }
2822
2823                        // Seleciona qual comando a ser executado
2824                        switch($is_spam){
2825                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
2826                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
2827                        }
2828
2829                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
2830                        $cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
2831                        system($cmd);
2832                }
2833                imap_close($mbox_stream);
2834                return false;
2835        }
2836        function get_header($msg_number){
2837                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
2838                if (!is_object($header))
2839                        return false;
2840                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
2841                $pdate = date_parse($header->MailDate);
2842                $header->udate +=  $pdate['zone']*(-60);
2843               
2844                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2845                        $flag = preg_match('/importance *: *(.*)\r/i',
2846                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2847                                                ,$importance);         
2848                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
2849                }
2850               
2851                return $header;
2852        }
2853}
2854?>
Note: See TracBrowser for help on using the repository browser.