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

Revision 615, 93.1 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #402

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