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

Revision 614, 91.3 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #401

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