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

Revision 828, 98.4 KB checked in by niltonneto, 15 years ago (diff)

Ticket 432 - Otimização do tempo de resposta na leitura de caixas grandes.

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