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

Revision 320, 79.8 KB checked in by niltonneto, 16 years ago (diff)

Versionamento 1.222
Ver changelog de alterações no Trac.

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