source: companies/celepar/expressoMail1_2/inc/class.imap_functions.inc.php @ 841

Revision 841, 98.6 KB checked in by niltonneto, 15 years ago (diff)

Equalização do código do Trunk com Companies/Celepar?.

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