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

Revision 628, 93.4 KB checked in by niltonneto, 15 years ago (diff)

Resolve #412

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