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

Revision 659, 96.5 KB checked in by eduardoalex, 15 years ago (diff)

Correções de defeitos apontados por Nilton no envio de mensagens importantes.

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