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

Revision 830, 97.8 KB checked in by niltonneto, 15 years ago (diff)

ticket #484 - Correção de código que estava em hardcoded.

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