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

Revision 413, 82.3 KB checked in by rafaelraymundo, 16 years ago (diff)

Melhoria implementada, relativo a ocorrencia #314 da comunidade.
Contatos dinamicos no envio de emails de forma configuravel.

  • 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 || !is_resource($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                $matches = array();
695                // Verify exception.
696                @preg_match("/<a href=\"notes:\/\/\//",$body,$matches);
697                // It no has exception,then open the link in new window.
698                if(count($matches))
699                        return $body;
700                return preg_replace('/(?<=[\s|(<br>)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\/\w.\-~&=?%;@+]*))/i', '<a href="http$3://$4$5" target="_blank">http$3://$4$5</a>', $body);
701        }
702
703        function get_signature($msg, $msg_number, $msg_folder)
704        {
705                foreach ($msg->file_type[$msg_number] as $index => $file_type)
706                {
707                        $file_type = strtolower($file_type);
708                        if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
709                        {
710                                if ($file_type == 'application/x-pkcs7-signature')
711                                {
712                                        $export_mail = new ExportEml();
713                                        $params['folder'] = $msg_folder;
714                                        $params['msgs_to_export'] = $msg_number;
715                                    $tempDir = ini_get("session.save_path");
716                                        $cert_file = $tempDir."/certificate_".base_convert(microtime(), 10, 36).".crt";                                 
717                                        $result = openssl_pkcs7_verify($export_mail->export_msg($params),PKCS7_NOVERIFY,$cert_file);
718                                        if (file_exists($cert_file))
719                                        {
720                                                $handle = fopen ($cert_file,"r");
721                                                $pemout = fread($handle,filesize($cert_file));
722                                                fclose($handle);
723                                                $cert=openssl_x509_parse($pemout);
724                                                $temp = "\\nSigned by: ".$cert[subject][CN];
725                                                $temp .= "\\nEmail Address: ".$cert[subject][emailAddress];
726                                                $temp .= "\\nCertificate issued by: ".$cert[issuer][CN]."\\n";
727                                        }
728                                    /* Message verified */
729                                    if ($result === true)
730                                            $sign = $temp;
731                                     else
732                                            $sign = "void";
733                                }
734                        }
735                }
736                return $sign;   
737        }
738
739        function get_thumbs($msg, $msg_number, $msg_folder)
740        {
741                $thumbs_array = array();
742                $i = 0;
743        foreach ($msg->file_type[$msg_number] as $index => $file_type)
744        {
745                $file_type = strtolower($file_type);
746                if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
747                        if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
748                                $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].">";
749                                $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>";
750                                        $thumbs_array[] = $href;
751                        }
752                        $i++;
753                }
754        }
755        return $thumbs_array;
756        }
757               
758        /*function delete_msg($params)
759        {
760                $folder = $params['folder'];
761                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
762               
763                $mbox_stream = $this->open_mbox($folder);
764               
765                foreach ($msgs_to_delete as $msg_number){
766                        imap_delete($mbox_stream, $msg_number, FT_UID);
767                }
768                imap_close($mbox_stream, CL_EXPUNGE);
769                return $params['msgs_to_delete'];
770        }*/
771
772        // Novo
773        function delete_msgs($params)
774        {
775               
776                $folder = $params['folder'];
777                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
778                $msgs_number = explode(",",$params['msgs_number']);
779                $border_ID = $params['border_ID'];
780               
781                $return = array();
782               
783                if ($params['get_previous_msg']){
784                        $return['previous_msg'] = $this->get_info_previous_msg($params);
785                        // Fix problem in unserialize function JS.
786                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
787                }
788
789                //$mbox_stream = $this->open_mbox($folder);
790                $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())));
791               
792                foreach ($msgs_number as $msg_number)
793                {
794                        if (imap_delete($mbox_stream, $msg_number, FT_UID));
795                                $return['msgs_number'][] = $msg_number;
796                }
797               
798                $return['folder'] = $folder;
799                $return['border_ID'] = $border_ID;
800               
801                if($mbox_stream)
802                        imap_close($mbox_stream, CL_EXPUNGE);
803                return $return;
804        }
805
806               
807        function refresh($params)
808        {
809                include("class.imap_attachment.inc.php");
810                $imap_attachment = new imap_attachment();               
811                $folder = $params['folder'];
812                $msg_range_begin = $params['msg_range_begin'];
813                $msg_range_end = $params['msg_range_end'];
814                $msgs_existent = $params['msgs_existent'];
815                $sort_box_type = $params['sort_box_type'];             
816                $sort_box_reverse = $params['sort_box_reverse'];
817                $msgs_in_the_server = array();
818                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
819                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
820
821                if(!count($sort_array_msg))
822                        return array();
823                       
824                $num_msgs = (count($sort_array_msg) - imap_num_recent($this->mbox));
825                $msgs_in_the_client = explode(",", $msgs_existent);
826
827               
828                for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= count($sort_array_msg))); $msg_range_begin++)
829                {
830                        $msgs_in_the_server[] = $sort_array_msg[$msg_range_begin-1];
831                }
832                if ((count($msgs_in_the_server) < 1) && ($msg_range_begin != 0))
833                {
834                        $range = $msg_range_end - $msg_range_begin;
835                        $msg_range_begin = $msg_range_begin - $range;
836                        $msg_range_end = $msg_range_end - $range;
837                        for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= count($sort_array_msg))); $msg_range_begin++)
838                        {
839                                $msgs_in_the_server[] = $sort_array_msg[$msg_range_begin-1];
840                        }
841                }
842               
843                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
844                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
845               
846                $msgs_to_exec = array();
847                if ((count($msg_to_insert)) && ($msgs_existent))
848                {
849                        foreach($msg_to_insert as $index => $msg_number)
850                        {
851                                if ($msgs_in_the_server[$index+1])
852                                {
853                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
854                                        $msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
855                                }
856                                else
857                                {
858                                        //$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
859                                        $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
860                                }
861                        }
862                        ksort($msgs_to_exec);
863                }
864                elseif(!$msgs_existent)
865                {
866                        foreach($msgs_in_the_server as $index => $msg_number)
867                        {
868                                $msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
869                        }
870                }
871               
872                $return = array();
873                $i = 0;
874                foreach($msgs_to_exec as $msg_number => $command)
875                {
876                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox , $msg_number), 80, 255);
877                        if (!is_object($header))
878                                return false;
879                       
880                        $return[$i]['msg_number']       = $msg_number;
881                        $return[$i]['command']          = $command;
882                       
883                        $return[$i]['msg_folder']       = $folder;
884                        $return[$i]['Recent']           = $header->Recent;
885                        $return[$i]['Unseen']           = $header->Unseen;
886                        $return[$i]['Answered']         = $header->Answered;
887                        $return[$i]['Deleted']          = $header->Deleted;
888                        $return[$i]['Draft']            = $header->Draft;
889                        $return[$i]['Flagged']          = $header->Flagged;
890
891                        $date_msg = date("d/m/Y",$header->udate);
892                        if (date("d/m/Y") == $date_msg)
893                                $return[$i]['udate'] = date("H:i",$header->udate);
894                        else
895                                $return[$i]['udate'] = $date_msg;
896                       
897                        $from = $header->from;
898                        $return[$i]['from'] = array();
899                        $tmp = imap_mime_header_decode($from[0]->personal);
900                        $return[$i]['from']['name'] = $tmp[0]->text;
901                        $return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
902                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
903                        if(!$return[$i]['from']['name'])
904                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
905                       
906                        /*$toaddress = imap_mime_header_decode($header->toaddress);
907                        $return[$i]['toaddress'] = '';
908                        foreach ($toaddress as $tmp)
909                                $return[$i]['toaddress'] .= $tmp->text;*/
910                        $to = $header->to;
911                        $return[$i]['to'] = array();
912                        $tmp = imap_mime_header_decode($to[0]->personal);
913                        $return[$i]['to']['name'] = $tmp[0]->text;
914                        $return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
915                        $return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
916                       
917                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
918
919                        $return[$i]['Size'] = $header->Size;
920                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
921                       
922                        $return[$i]['attachment'] = array();
923                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
924                        $i++;
925                }
926                $return['new_msgs'] = imap_num_recent($this->mbox);
927                $return['msgs_to_delete'] = $msg_to_delete;
928                if($this->mbox && is_resource($this->mbox))
929                        imap_close($this->mbox);
930                return $return;
931        }
932
933        function get_folders_list($params = null)
934        {
935                $mbox_stream = $this->open_mbox();             
936                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
937                $folders_list = imap_getmailboxes($mbox_stream, $serverString, "*");
938                $tmp = array();
939                $result = array();
940               
941                if (is_array($folders_list)) {
942                        reset($folders_list);
943                $ldap = new ldap_functions();
944                       
945                        $i = 0;
946                        while (list($key, $val) = each($folders_list)) {
947                                $status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
948                                $result[$i]['folder_unseen'] = $status->unseen;
949                       
950                                //$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
951                                $tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
952                                $folder_id = $tmp_folder_id[1];
953                                $result[$i]['folder_id'] = $folder_id;
954                               
955                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
956                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
957                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
958                                if (is_numeric($result[$i]['folder_name']))     {
959                                        if ($cn = $ldap->uid2cn($result[$i]['folder_name'])){
960                                                $result[$i]['folder_name'] = $cn;
961                                        }
962                                }
963                               
964                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
965                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
966                                       
967                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
968                                        $result[$i]['folder_hasChildren'] = 1;
969                                else
970                                        $result[$i]['folder_hasChildren'] = 0;
971
972                                $i++;                           
973                        }
974                }
975               
976                foreach ($result as $folder_info)
977                {
978                        $array_tmp[] = $folder_info['folder_id'];
979                }
980               
981                natcasesort($array_tmp);
982               
983                foreach ($array_tmp as $key => $folder_id)
984                {
985                        $result2[] = $result[$key];
986                }
987               
988                $current_folder = "INBOX";
989                if($params && $params['folder'])
990                        $current_folder = $params['folder'];
991                return array_merge($result2, $this->get_quota(array(folder_id => $current_folder)));
992        }
993       
994        function create_mailbox($arr)
995        {
996                $namebox        = $arr['newp'];
997                $mbox_stream = $this->open_mbox();
998                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
999                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
1000               
1001                $result = "Ok";
1002                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
1003                {
1004                        $result = implode("<br />\n", imap_errors());
1005                }       
1006               
1007                if($mbox_stream)
1008                        imap_close($mbox_stream);
1009                                       
1010                return $result;
1011               
1012        }
1013       
1014        function create_extra_mailbox($arr)
1015        {
1016                $nameboxs = explode(";",$arr['nw_folders']);
1017                $result = "";
1018                $mbox_stream = $this->open_mbox();
1019                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1020                foreach($nameboxs as $key=>$tmp){                       
1021                        if($tmp != ""){
1022                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1023                                        $result = implode("<br />\n", imap_errors());
1024                                        if($mbox_stream)
1025                                                imap_close($mbox_stream);                                       
1026                                        return $result;
1027                                }
1028                        }
1029                }
1030                if($mbox_stream)
1031                        imap_close($mbox_stream);
1032                return true;
1033        }
1034       
1035        function delete_mailbox($arr)
1036        {
1037                $namebox = $arr['del_past'];
1038                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1039                $mbox_stream = $this->open_mbox();
1040                //$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
1041               
1042                $result = "Ok";
1043                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1044                if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
1045                {
1046                        $result = implode("<br />\n", imap_errors());
1047                }
1048                if($mbox_stream)
1049                        imap_close($mbox_stream);
1050                return $result;
1051        }
1052       
1053        function ren_mailbox($arr)
1054        {
1055                $namebox = $arr['current'];
1056                $new_box = $arr['rename'];
1057                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1058                $mbox_stream = $this->open_mbox();
1059                //$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
1060               
1061                $result = "Ok";
1062                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
1063                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
1064               
1065                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1066                {
1067                        $result = imap_errors();                       
1068                }
1069                if($mbox_stream)
1070                        imap_close($mbox_stream);
1071                return $result;
1072               
1073        }
1074       
1075        function get_num_msgs($params)
1076        {
1077                $folder = $params['folder'];
1078                if(!$this->mbox || !is_resource($this->mbox)) {
1079                        $this->mbox = $this->open_mbox($folder);
1080                        if(!$this->mbox || !is_resource($this->mbox))
1081                        return imap_last_error();
1082                }               
1083                $num_msgs = imap_num_msg($this->mbox);
1084                if($this->mbox || is_resource($this->mbox))
1085                        imap_close($this->mbox);
1086               
1087                return $num_msgs;
1088        }
1089       
1090        function send_mail($params)
1091        {
1092                include_once("class.phpmailer.php");
1093                $mail = new PHPMailer();
1094                include_once("class.db_functions.inc.php");
1095                $db = new db_functions();
1096                $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
1097                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1098                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1099                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1100                $subject = $params['input_subject'];
1101                $msg_uid = $params['msg_id'];
1102                $return_receipt = $params['input_return_receipt'];
1103                $body = $params['body'];
1104                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
1105                $attachments = $params['FILES'];
1106                $forwarding_attachments = $params['forwarding_attachments'];
1107                 
1108                $folder =$params['folder'];
1109                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
1110                $folder_name = $params['folder_name'];         
1111                // Fix problem with cyrus delimiter changes.
1112                // Dots in names: enabled/disabled.                             
1113                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1114                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1115                // End Fix.
1116                if ($folder != 'null'){                 
1117                        $mail->SaveMessageInFolder = $folder;
1118                }
1119////////////////////////////////////////////////////////////////////////////////////////////////////
1120                $mail->SMTPDebug = false;
1121                               
1122                $mail->IsSMTP();
1123                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1124                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1125                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1126                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1127                if($fromaddress){
1128                        $mail->Sender = $mail->From;
1129                        $mail->SenderName = $mail->FromName;
1130                        $mail->FromName = $fromaddress[0];
1131                        $mail->From = $fromaddress[1];
1132                }
1133                               
1134                $this->add_recipients("to", $toaddress, &$mail);
1135                $this->add_recipients("cc", $ccaddress, &$mail);
1136                $this->add_recipients("cco", $ccoaddress, &$mail);
1137                $mail->Subject = $subject;
1138                $mail->IsHTML(true);
1139                $mail->Body = $params['body'];
1140
1141////////////////////////////////////////////////////////////////////////////////////////////////////
1142                //      Build CID for embedded Images!!!
1143                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
1144                $cid_imgs = '';
1145                $name_cid_files = array();
1146                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1147                $cid_array = array();
1148                foreach($cid_imgs[6] as $j => $val){
1149                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
1150                        {
1151                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
1152                        }
1153                        $cid = $cid_array[$cid_imgs[4][$j].$val];
1154                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
1155                       
1156                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
1157                                {
1158                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
1159                                        $fileName = "image_".($j).".jpg";
1160                                        $fileCode = "base64";
1161                                        $fileType = "image/jpg";
1162                                }
1163                                else
1164                                {
1165                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
1166                                        $file_description = unserialize(rawurldecode($attach_img));
1167
1168                                        foreach($file_description as $i => $descriptor){                               
1169                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
1170                                        }
1171                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
1172                                        $fileName = $file_description[2];
1173                                        $fileCode = $file_description[4];
1174                                        $fileType = $this->get_file_type($file_description[2]);
1175                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
1176                                }
1177                                $tempDir = ini_get("session.save_path");
1178                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
1179                                $f = fopen($tempDir.'/'.$file,"w");
1180                                fputs($f,$fileContent);
1181                                fclose($f);
1182                                if ($fileContent)
1183                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
1184                                //else
1185                                //      return "Error loading image attachment content";                                               
1186
1187                }
1188////////////////////////////////////////////////////////////////////////////////////////////////////
1189                //      Build Uploading Attachments!!!
1190                if (count($attachments))
1191                {
1192                        $total_uploaded_size = 0;
1193                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
1194                        foreach ($attachments as $attach)
1195                        {
1196                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
1197                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
1198                        }
1199                        if( $total_uploaded_size > $upload_max_filesize)
1200                                return 'false';                 
1201                }                       
1202////////////////////////////////////////////////////////////////////////////////////////////////////
1203                //      Build Forwarding Attachments!!!
1204                if (count($forwarding_attachments) > 0)
1205                {
1206                        // Bug fixed for array_search function
1207                        if(count($name_cid_files) > 0) {
1208                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
1209                                $name_cid_files[0] = null;
1210                        }                       
1211                       
1212                        foreach($forwarding_attachments as $forwarding_attachment)
1213                        {
1214                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
1215                                        $tmp = array_values($file_description);
1216                                        foreach($file_description as $i => $descriptor){                               
1217                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1218                                        }
1219                                        $file_description = $tmp;                                       
1220                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
1221                                        $fileName = $file_description[2];
1222                                        if(!array_search(trim($fileName),$name_cid_files)) {
1223                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
1224                                }
1225                        }
1226                }
1227
1228////////////////////////////////////////////////////////////////////////////////////////////////////
1229                // Disposition-Notification-To
1230                if ($return_receipt)
1231                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1232////////////////////////////////////////////////////////////////////////////////////////////////////
1233                $sent = $mail->Send();
1234                if(!$sent)
1235                {
1236                        return $mail->ErrorInfo;
1237                }
1238                else
1239                {
1240                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
1241                        {
1242                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
1243                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
1244                                $now = date("d/m/y H:i:s");
1245                                $addrs = $toaddress.$ccaddress.$ccoaddress;
1246                                $sent = trim($sent);                                                                                           
1247                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
1248                        }
1249                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts'])
1250                        {
1251                                $contacts = new dynamic_contacts();
1252                                $contacts->add_dynamic_contacts($toaddress.$ccaddress.$ccoaddress);
1253                        }
1254                        return true;
1255                }
1256        }
1257
1258        function add_recipients($recipient_type, $full_address, $mail)
1259        {
1260                $parse_address = imap_rfc822_parse_adrlist($full_address, "");         
1261                foreach ($parse_address as $val)
1262                {
1263                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
1264                        if ($val->mailbox == "INVALID_ADDRESS")
1265                                continue;
1266                       
1267                        if (empty($val->personal))
1268                        {
1269                                switch($recipient_type)
1270                                {
1271                                        case "to":
1272                                                $mail->AddAddress($val->mailbox."@".$val->host);
1273                                                break;
1274                                        case "cc":
1275                                                $mail->AddCC($val->mailbox."@".$val->host);
1276                                                break;
1277                                        case "cco":
1278                                                $mail->AddBCC($val->mailbox."@".$val->host);
1279                                                break;
1280                                }
1281                        }
1282                        else
1283                        {
1284                                switch($recipient_type)
1285                                {
1286                                        case "to":
1287                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
1288                                                break;
1289                                        case "cc":
1290                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
1291                                                break;
1292                                        case "cco":
1293                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
1294                                                break;
1295                                }
1296                        }
1297                }
1298                return true;
1299        }
1300       
1301        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
1302        {
1303                $mbox_stream = $this->open_mbox($msg_folder);                   
1304                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);           
1305                if($encoding == 'base64')
1306                        $fileContent = imap_base64($fileContent);
1307                else if($encoding == 'quoted-printable')
1308                        $fileContent = quoted_printable_decode($fileContent);                           
1309                return $fileContent;
1310        }
1311       
1312        function del_last_caracter($string)
1313        {
1314                $string = substr($string,0,(strlen($string) - 1));
1315                return $string;
1316        }
1317       
1318        function del_last_two_caracters($string)
1319        {
1320                $string = substr($string,0,(strlen($string) - 2));
1321                return $string;
1322        }
1323       
1324        function imap_sortfrom($sort_box_reverse, $search_box_type)
1325        {
1326                $sortfrom = array();
1327                $sortfrom_uid = array();
1328               
1329                $num_msgs = imap_num_msg($this->mbox);
1330                for ($i=1; $i<=$num_msgs; $i++)
1331                {
1332                        $header = imap_headerinfo($this->mbox, $i, 80, 255);
1333                        // List UNSEEN messages.
1334                        if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
1335                                continue;
1336                        }
1337                        // List SEEN messages.
1338                        elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
1339                                continue;
1340                        }
1341                        // List ANSWERED messages.                     
1342                        elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
1343                                continue;                               
1344                        }
1345                        // List FLAGGED messages.                       
1346                        elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
1347                                continue;
1348                        }
1349                                               
1350                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])                             
1351                                $from = $header->to;
1352                        else
1353                                $from = $header->from;
1354                       
1355                        $tmp = imap_mime_header_decode($from[0]->personal);                     
1356                       
1357                        if ($tmp[0]->text != "")
1358                                $sortfrom[$i] = $tmp[0]->text;
1359                        else
1360                                $sortfrom[$i] = $from[0]->mailbox . "@" . $from[0]->host;
1361                }
1362               
1363                natcasesort($sortfrom);
1364               
1365                foreach($sortfrom as $index => $header_msg)
1366                {       
1367                        $sortfrom_uid[] = imap_uid($this->mbox, $index);
1368                }
1369               
1370                if ($sort_box_reverse)
1371                        $sortfrom_uid = array_reverse($sortfrom_uid);
1372               
1373                return $sortfrom_uid;
1374        }
1375
1376        function move_search_messages($params){         
1377                $params['selected_messages'] = urldecode($params['selected_messages']);
1378                $params['new_folder'] = urldecode($params['new_folder']);
1379                $params['new_folder_name'] = urldecode($params['new_folder_name']);
1380                $sel_msgs = explode(",", $params['selected_messages']);
1381                @reset($sel_msgs);     
1382                $sorted_msgs = array();
1383                foreach($sel_msgs as $idx => $sel_msg) {
1384                        $sel_msg = explode(";", $sel_msg);
1385                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
1386                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
1387                         }     
1388                         else {
1389                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
1390                         }
1391                }
1392                @ksort($sorted_msgs);
1393                $last_return = false;           
1394                foreach($sorted_msgs as $folder => $msgs_number) {                     
1395                        $params['msgs_number'] = $msgs_number;
1396                        $params['folder'] = $folder;   
1397                        if($params['new_folder'] && $folder != $params['new_folder']){
1398                                $last_return = $this -> move_messages($params);                         
1399                        }
1400                        elseif(!$params['new_folder'] || $params['delete'] ){
1401                                $last_return = $this -> delete_msgs($params);
1402                                $last_return['deleted'] = true;
1403                        }
1404                }
1405                return $last_return;
1406        }
1407       
1408        function move_messages($params)
1409        {
1410                $folder = $params['folder'];           
1411                $mbox_stream = $this->open_mbox($folder);               
1412                $newmailbox = ($params['new_folder']);
1413                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
1414                $new_folder_name = $params['new_folder_name'];
1415                $msgs_number = $params['msgs_number'];
1416                $return = array('msgs_number' => $msgs_number,
1417                                                'folder' => $folder,
1418                                                'new_folder_name' => $new_folder_name,
1419                                                'border_ID' => $params['border_ID'],
1420                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
1421               
1422                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
1423        if (substr($folder,0,4) == 'user'){
1424                $acl = $this->getacltouser($folder);
1425                /*
1426                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
1427                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
1428                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
1429                 *   w - write (STORE flags other than SEEN and DELETED)
1430                 *   i - insert (perform APPEND, COPY into mailbox)
1431                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
1432                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
1433                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
1434                 *   a - administer (perform SETACL)
1435                        */
1436                        if (strpos($acl, "d") === false){
1437                                $return['status'] = false;
1438                                return $return;
1439                        }
1440        }
1441                               
1442                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.         
1443                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
1444                {
1445                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1446                        // Fix problem in unserialize function JS.
1447                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1448                }
1449               
1450                $mbox_stream = $this->open_mbox($folder);       
1451                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1452                        imap_expunge($mbox_stream);
1453                        if($mbox_stream)
1454                                imap_close($mbox_stream);
1455                        return $return;
1456                }else {
1457                        if(strstr(imap_last_error(),'Over quota')) {                           
1458                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
1459                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];                                                                       
1460                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];                                                           
1461                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1462                                $mbox           = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}INBOX", $accountID, $pass) or die(serialize(array('imap_error' => imap_last_error())));
1463                                if(!$mbox)
1464                                        return imap_last_error();
1465                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");                           
1466                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
1467                                        if($mbox_stream)
1468                                                imap_close($mbox_stream);
1469                                        if($mbox)                                                                       
1470                                                imap_close($mbox);
1471                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";                                                               
1472                                }
1473                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1474                                        imap_expunge($mbox_stream);
1475                                        if($mbox_stream)
1476                                                imap_close($mbox_stream);
1477                                        // return to original quota limit.
1478                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
1479                                                if($mbox)
1480                                                        imap_close($mbox);
1481                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
1482                                        }
1483                                        return $return;                                                                                                 
1484                                }
1485                                else {
1486                                        if($mbox_stream)
1487                                                imap_close($mbox_stream);
1488                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
1489                                                if($mbox)
1490                                                        imap_close($mbox);
1491                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
1492                                        }
1493                                        return imap_last_error();                               
1494                                }
1495                               
1496                        }
1497                        else {
1498                                if($mbox_stream)
1499                                        imap_close($mbox_stream);
1500                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
1501                        }
1502                }               
1503        }
1504       
1505        function save_msg($params)
1506        {
1507               
1508                include_once("class.phpmailer.php");
1509                $mail = new PHPMailer();
1510                include_once("class.db_functions.inc.php");
1511                $toaddress = $params['input_to'];
1512                $ccaddress = $params['input_cc'];
1513                $subject = $params['input_subject'];
1514                $msg_uid = $params['msg_id'];
1515                $body = $params['body'];
1516                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
1517                $body = preg_replace("/\n/"," ",$body);
1518                $body = preg_replace("/\r/","",$body);
1519                $forwarding_attachments = $params['forwarding_attachments'];
1520                $attachments = $params['FILES'];
1521                $return_files = $params['FILES'];
1522                 
1523                $folder = $params['folder'];
1524                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
1525                // Fix problem with cyrus delimiter changes.
1526                // Dots in names: enabled/disabled.                             
1527                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1528                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1529                // End Fix.
1530                                       
1531                $mail->SaveMessageInFolder = $folder;
1532                $mail->SMTPDebug = false;
1533                                               
1534                $mail->IsSMTP();
1535                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1536                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1537                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1538                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1539               
1540                $mail->Sender = $mail->From;
1541                $mail->SenderName = $mail->FromName;
1542                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1543                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
1544                               
1545                $this->add_recipients("to", $toaddress, &$mail);
1546                $this->add_recipients("cc", $ccaddress, &$mail);
1547                $mail->Subject = $subject;
1548                $mail->IsHTML(true);
1549                $mail->Body = $body;
1550               
1551                //      Build CID for embedded Images!!!
1552                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
1553                $cid_imgs = '';
1554                $name_cid_files = array();
1555                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1556                $cid_array = array();
1557                foreach($cid_imgs[6] as $j => $val){
1558                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
1559                        {
1560                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
1561                        }
1562                        $cid = $cid_array[$cid_imgs[4][$j].$val];
1563                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
1564                       
1565                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
1566                                {
1567                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
1568                                        //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
1569                                        $fileName = "image_".($j).".jpg";
1570                                        $fileCode = "base64";
1571                                        $fileType = "image/jpg";
1572                                        $file_attached[0] = $cid_imgs[2][$j];
1573                                        $file_attached[1] = $cid_imgs[4][$j];
1574                                        $file_attached[2] = $fileName;
1575                                        $file_attached[3] = $cid_imgs[6][$j];
1576                                        $file_attached[4] = 'base64';
1577                                        $file_attached[5] = strlen($fileContent); //Size of file
1578                                        $return_forward[] = $file_attached;
1579                                }
1580                                else
1581                                {
1582                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
1583                                        $file_description = unserialize(rawurldecode($attach_img));
1584                                        foreach($file_description as $i => $descriptor){                               
1585                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
1586                                        }
1587                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
1588                                        $fileName = $file_description[2];
1589                                        $fileCode = $file_description[4];
1590                                        $fileType = $this->get_file_type($file_description[2]);
1591                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
1592                                        if (!empty($file_description))
1593                                        {
1594                                                $file_description[5] = strlen($fileContent); //Size of file
1595                                                $return_forward[] = $file_description;
1596                                        }
1597                                }
1598                                $tempDir = ini_get("session.save_path");
1599                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
1600                                $f = fopen($tempDir.'/'.$file,"w");
1601                                fputs($f,$fileContent);
1602                                fclose($f);
1603                                if ($fileContent)
1604                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
1605                                //else
1606                                //      return "Error loading image attachment content";                                               
1607
1608                }
1609       
1610        //      Build Forwarding Attachments!!!         
1611                if (count($forwarding_attachments) > 0)
1612                {
1613                        foreach($forwarding_attachments as $forwarding_attachment)
1614                        {
1615                                $file_description = unserialize(rawurldecode($forwarding_attachment));
1616                                $tmp = array_values($file_description);
1617                                foreach($file_description as $i => $descriptor){                               
1618                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1619                                }
1620                                $file_description = $tmp;
1621                               
1622                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
1623                                $fileName = $file_description[2];
1624                               
1625                                $file_description[5] = strlen($fileContent); //Size of file
1626                                $return_forward[] = $file_description;
1627                       
1628                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
1629                        }
1630                }
1631               
1632                if ((count($return_forward) > 0) && (count($return_files) > 0))
1633                        $return_files = array_merge_recursive($return_forward,$return_files);
1634                else
1635                        if (count($return_files) < 1)
1636                                $return_files = $return_forward;
1637       
1638                //      Build Uploading Attachments!!!
1639                if (count($attachments))
1640                        foreach ($attachments as $attach)
1641                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name                 
1642       
1643       
1644               
1645                if(!empty($mail->AltBody))
1646            $mail->ContentType = "multipart/alternative";
1647
1648        $mail->error_count = 0; // reset errors
1649        $mail->SetMessageType();
1650        $header = $mail->CreateHeader();
1651        $body = $mail->CreateBody();
1652       
1653        if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
1654                {
1655                        $imap_options = '/tls/novalidate-cert';
1656                }
1657                else
1658                {
1659                        $imap_options = '/notls/novalidate-cert';
1660                }
1661                $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
1662                $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
1663                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1664                $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
1665                $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
1666       
1667                $new_header = str_replace("\n", "\r\n", $header);
1668                $new_body = str_replace("\n", "\r\n", $body);
1669               
1670                $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
1671                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
1672                $return['msg_no'] = $status->uidnext - 1;
1673                $return['folder_id'] = $folder;
1674               
1675                if($mbox_stream)
1676                        imap_close($mbox_stream);
1677                               
1678                foreach ($return_files as $index => $_attachment) {
1679                        if (array_key_exists("name",$_attachment)){
1680                                unset($return_files[$index]);
1681                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
1682                        }
1683                        else
1684                        {
1685                                unset($return_files[$index]);
1686                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
1687                        }
1688                }
1689               
1690                $return['files'] = serialize($return_files);
1691                               
1692                if (!$return['append'])
1693                        $return['append'] = imap_last_error();
1694               
1695                return $return;
1696        }
1697       
1698        function set_messages_flag($params)
1699        {
1700                $folder = $params['folder'];
1701                $msgs_to_set = $params['msgs_to_set'];
1702                $flag = $params['flag'];
1703                $return = array();
1704                $return["msgs_to_set"] = $msgs_to_set;
1705                $return["flag"] = $flag;
1706               
1707                if(!$this->mbox && !is_resource($this->mbox))
1708                        $this->mbox = $this->open_mbox($folder);
1709               
1710                if ($flag == "unseen")
1711                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
1712                elseif ($flag == "seen")
1713                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
1714                elseif ($flag == "answered"){
1715                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
1716                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
1717                }
1718                elseif ($flag == "forwarded")
1719                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
1720                elseif ($flag == "flagged")
1721                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
1722                elseif ($flag == "unflagged")
1723                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
1724               
1725                if($this->mbox && is_resource($this->mbox))
1726                        imap_close($this->mbox);
1727                return $return;
1728        }
1729       
1730        function get_file_type($file_name)
1731        {
1732                $file_name = strtolower($file_name);
1733                $strFileType = strrev(substr(strrev($file_name),0,4));
1734                if ($strFileType == ".asf")
1735                        return "video/x-ms-asf";
1736                if ($strFileType == ".avi")
1737                        return "video/avi";
1738                if ($strFileType == ".doc")
1739                        return "application/msword";
1740                if ($strFileType == ".zip")
1741                        return "application/zip";
1742                if ($strFileType == ".xls")
1743                        return "application/vnd.ms-excel";
1744                if ($strFileType == ".gif")
1745                        return "image/gif";
1746                if ($strFileType == ".jpg" || $strFileType == "jpeg")
1747                        return "image/jpeg";
1748                if ($strFileType == ".png")
1749                        return "image/png";
1750                if ($strFileType == ".wav")
1751                        return "audio/wav";
1752                if ($strFileType == ".mp3")
1753                        return "audio/mpeg3";
1754                if ($strFileType == ".mpg" || $strFileType == "mpeg")
1755                        return "video/mpeg";
1756                if ($strFileType == ".rtf")
1757                        return "application/rtf";
1758                if ($strFileType == ".htm" || $strFileType == "html")
1759                        return "text/html";
1760                if ($strFileType == ".xml")
1761                        return "text/xml";
1762                if ($strFileType == ".xsl")
1763                        return "text/xsl";
1764                if ($strFileType == ".css")
1765                        return "text/css";
1766                if ($strFileType == ".php")
1767                        return "text/php";
1768                if ($strFileType == ".asp")
1769                        return "text/asp";
1770                if ($strFileType == ".pdf")
1771                        return "application/pdf";
1772                if ($strFileType == ".txt")
1773                        return "text/plain";
1774                if ($strFileType == ".wmv")
1775                        return "video/x-ms-wmv";
1776                if ($strFileType == ".sxc")
1777                        return "application/vnd.sun.xml.calc";
1778                if ($strFileType == ".stc")
1779                        return "application/vnd.sun.xml.calc.template";
1780                if ($strFileType == ".sxd")
1781                        return "application/vnd.sun.xml.draw";
1782                if ($strFileType == ".std")
1783                        return "application/vnd.sun.xml.draw.template";
1784                if ($strFileType == ".sxi")
1785                        return "application/vnd.sun.xml.impress";
1786                if ($strFileType == ".sti")
1787                        return "application/vnd.sun.xml.impress.template";
1788                if ($strFileType == ".sxm")
1789                        return "application/vnd.sun.xml.math";
1790                if ($strFileType == ".sxw")
1791                        return "application/vnd.sun.xml.writer";
1792                if ($strFileType == ".sxq")
1793                        return "application/vnd.sun.xml.writer.global";
1794                if ($strFileType == ".stw")
1795                        return "application/vnd.sun.xml.writer.template";
1796               
1797               
1798                return "application/octet-stream";             
1799        }
1800       
1801        function htmlspecialchars_encode($str)
1802        {
1803                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
1804        }
1805        function htmlspecialchars_decode($str)
1806        {
1807                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
1808        }
1809       
1810        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse){
1811               
1812                if(!$this->mbox || !is_resource($this->mbox)){
1813                        $this->mbox = $this->open_mbox($folder);
1814                }
1815                switch($sort_box_type){
1816                        case 'SORTFROM':
1817                                return $this->imap_sortfrom($sort_box_reverse, $search_box_type);                               
1818                        case 'SORTSUBJECT':
1819                                return imap_sort($this->mbox, SORTSUBJECT, $sort_box_reverse, SE_UID, $search_box_type);                               
1820                        case 'SORTSIZE':
1821                                return imap_sort($this->mbox, SORTSIZE, $sort_box_reverse, SE_UID, $search_box_type);                           
1822                        default:
1823                                return imap_sort($this->mbox, SORTARRIVAL, $sort_box_reverse, SE_UID, $search_box_type);                                               
1824                }               
1825        }       
1826       
1827        function get_info_next_msg($params)
1828        {
1829                $msg_number = $params['msg_number'];
1830                $folder = $params['msg_folder'];
1831                $sort_box_type = $params['sort_box_type'];
1832                $sort_box_reverse = $params['sort_box_reverse'];
1833                $reuse_border = $params['reuse_border'];
1834                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1835                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);                             
1836               
1837                $success = false;
1838                if (is_array($sort_array_msg))
1839                {
1840                        foreach ($sort_array_msg as $i => $value){
1841                                if ($value == $msg_number)
1842                                {
1843                                        $success = true;
1844                                        break;
1845                                }
1846                        }
1847                }
1848
1849                if (! $success || $i >= sizeof($sort_array_msg)-1)
1850                {
1851                        $params['status'] = 'false';
1852                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
1853                        return $params;
1854                }
1855               
1856                $params = array();
1857                $params['msg_number'] = $sort_array_msg[($i+1)];
1858                $params['msg_folder'] = $folder;
1859               
1860                $return = $this->get_info_msg($params);         
1861                $return["reuse_border"] = $reuse_border;
1862                return $return;
1863        }
1864
1865        function get_info_previous_msg($params)
1866        {
1867                $msg_number = $params['msgs_number'];
1868                $folder = $params['folder'];
1869                $sort_box_type = $params['sort_box_type'];
1870                $sort_box_reverse = $params['sort_box_reverse'];
1871                $reuse_border = $params['reuse_border'];
1872                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
1873                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
1874               
1875                $success = false;
1876                if (is_array($sort_array_msg))
1877                {
1878                        foreach ($sort_array_msg as $i => $value){
1879                                if ($value == $msg_number)
1880                                {
1881                                        $success = true;
1882                                        break;
1883                                }
1884                        }
1885                }
1886                if (! $success || $i == 0)
1887                {
1888                        $params['status'] = 'false';
1889                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
1890                        return $params;
1891                }
1892               
1893                $params = array();
1894                $params['msg_number'] = $sort_array_msg[($i-1)];
1895                $params['msg_folder'] = $folder;
1896               
1897                $return = $this->get_info_msg($params);
1898                $return["reuse_border"] = $reuse_border;
1899                return $return;
1900        }
1901       
1902        // This function updates the values: quota, paging and new messages menu.
1903        function get_menu_values($params){
1904                $return_array = array();
1905                $return_array = $this->get_quota($params);
1906               
1907                $mbox_stream = $this->open_mbox($params['folder']);
1908                $return_array['num_msgs'] = imap_num_msg($mbox_stream);         
1909                if($mbox_stream)
1910                        imap_close($mbox_stream);
1911                               
1912                return $return_array;
1913        }
1914       
1915        function get_quota($params){
1916                // folder_id = user/{uid} for shared folders
1917                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
1918                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
1919                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];             
1920                }
1921                // folder_id = INBOX for inbox folders
1922                else
1923                        $folder_id = "INBOX";
1924               
1925                if(!$this->mbox || !is_resource($this->mbox))
1926                        $this->mbox = $this->open_mbox();
1927
1928                $quota = imap_get_quotaroot($this->mbox, $folder_id);
1929                if($this->mbox && is_resource($this->mbox))
1930                        imap_close($this->mbox);
1931                       
1932                if (!$quota){
1933                        return array(
1934                                'quota_percent' => 0,
1935                                'quota_used' => 0,
1936                                'quota_limit' =>  0
1937                        );
1938                }
1939               
1940                if(count($quota) && $quota['limit']) {
1941                        $quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
1942                        $quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
1943                        if($quota_used >= $quota_limit)
1944                                $quota_used = $quota_limit;
1945                        $quotaPercent = ($quota_used / $quota_limit)*100;
1946                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
1947
1948                        return array(
1949                                'quota_percent' => floor($quotaPercent),
1950                                'quota_used' => floor($quota_used),
1951                                'quota_limit' =>  floor($quota_limit)
1952                        );
1953                }
1954                else
1955                        return array();
1956        }
1957       
1958        function send_notification($params){
1959                require_once("class.phpmailer.php");
1960                $mail = new PHPMailer();
1961                 
1962                $toaddress = $params['notificationto'];
1963               
1964                $subject = 'Confirmação de leitura: ' . $params['subject'];
1965                $body = 'Sua mensagem: ' . $params['subject'] . '<br>';
1966                $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");
1967                $mail->SMTPDebug = false;
1968                $mail->IsSMTP();
1969                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1970                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1971                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1972                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1973                $mail->AddAddress($toaddress);
1974                $mail->Subject = $this->htmlspecialchars_decode($subject);
1975
1976                $mail->IsHTML(true);
1977                $mail->Body = $body;
1978               
1979                if(!$mail->Send()){
1980                        return $mail->ErrorInfo;
1981                }
1982                else
1983                        return true;
1984        }
1985       
1986        function empty_trash()
1987        {
1988                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
1989                $mbox_stream = $this->open_mbox($folder);
1990                $return = imap_delete($mbox_stream,'1:*');
1991                if($mbox_stream)
1992                        imap_close($mbox_stream, CL_EXPUNGE);
1993                return $return;
1994        }
1995       
1996        function search($params)
1997        {
1998                include("class.imap_attachment.inc.php");
1999                $imap_attachment = new imap_attachment();                               
2000                $criteria = $params['criteria'];
2001                $return = array();
2002                $folders = $this->get_folders_list();
2003               
2004                $j = 0;
2005                foreach($folders as $folder)
2006                {
2007                        $mbox_stream = $this->open_mbox($folder);
2008                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
2009                       
2010                        if ($messages == '')
2011                                continue;
2012               
2013                        $i = 0;
2014                        $return[$j] = array();
2015                        $return[$j]['folder_name'] = $folder['name'];
2016                       
2017                        foreach($messages as $msg_number)
2018                        {
2019                                $header = @imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $msg_number), 80, 255);
2020                                if (!is_object($header))
2021                                        return false;
2022                               
2023                                $return[$j][$i]['msg_folder']   = $folder['name'];
2024                                $return[$j][$i]['msg_number']   = $msg_number;
2025                                $return[$j][$i]['Recent']               = $header->Recent;
2026                                $return[$j][$i]['Unseen']               = $header->Unseen;
2027                                $return[$j][$i]['Answered']     = $header->Answered;
2028                                $return[$j][$i]['Deleted']              = $header->Deleted;
2029                                $return[$j][$i]['Draft']                = $header->Draft;
2030                                $return[$j][$i]['Flagged']              = $header->Flagged;
2031       
2032                                $date_msg = date("d/m/Y",$header->udate);
2033                                if (date("d/m/Y") == $date_msg)
2034                                        $return[$j][$i]['udate'] = date("H:i",$header->udate);
2035                                else
2036                                        $return[$j][$i]['udate'] = $date_msg;
2037                       
2038                                $fromaddress = imap_mime_header_decode($header->fromaddress);
2039                                $return[$j][$i]['fromaddress'] = '';
2040                                foreach ($fromaddress as $tmp)
2041                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
2042                       
2043                                $from = $header->from;
2044                                $return[$j][$i]['from'] = array();
2045                                $tmp = imap_mime_header_decode($from[0]->personal);
2046                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
2047                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
2048                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
2049
2050                                $to = $header->to;
2051                                $return[$j][$i]['to'] = array();
2052                                $tmp = imap_mime_header_decode($to[0]->personal);
2053                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
2054                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
2055                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
2056
2057                                $subject = imap_mime_header_decode($header->fetchsubject);
2058                                $return[$j][$i]['subject'] = '';
2059                                foreach ($subject as $tmp)
2060                                        $return[$j][$i]['subject'] .= $tmp->text;
2061
2062                                $return[$j][$i]['Size'] = $header->Size;
2063                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
2064                       
2065                                $return[$j][$i]['attachment'] = array();
2066                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
2067                                               
2068                                $i++;
2069                        }
2070                        $j++;
2071                        if($mbox_stream)
2072                                imap_close($mbox_stream);
2073                }
2074       
2075                return $return;
2076        }
2077       
2078        function delete_and_show_previous_message($params)
2079        {
2080                $return = $this->get_info_previous_msg($params);
2081               
2082                $params_tmp1 = array();
2083                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
2084                $params_tmp1['folder'] = $params['msg_folder'];
2085                $return_tmp1 = $this->delete_msg($params_tmp1);
2086               
2087                $return['msg_number_deleted'] = $return_tmp1;
2088               
2089                return $return;
2090        }
2091               
2092       
2093        function automatic_trash_cleanness($params)
2094        {
2095                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
2096                $criteria =  'BEFORE "'.$before_date.'"';
2097                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
2098                $messages = imap_search($mbox_stream, $criteria, SE_UID);
2099                if (is_array($messages)){
2100                        foreach ($messages as $msg_number){
2101                                imap_delete($mbox_stream, $msg_number, FT_UID);
2102                        }
2103                }
2104                if($mbox_stream)
2105                        imap_close($mbox_stream, CL_EXPUNGE);
2106                return $messages;
2107        }
2108//      Fix the search problem with special characters!!!!
2109        function remove_accents($string) {
2110                return strtr($string,
2111                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
2112                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
2113        }
2114
2115        function search_msg($params = ''){
2116                $retorno = "";
2117                $mbox_stream = "";
2118                $search = explode(",",$params['condition']);
2119                if($search){
2120                        $search_criteria = '';
2121                        foreach($search as $tmp)
2122                        {
2123                                $tmp1 = explode("##",$tmp);
2124                                $name_box = $tmp1[0];
2125                                unset($filter);
2126                                foreach($tmp1 as $index => $criteria)
2127                                {
2128                                        if ($index != 0 && strlen($criteria) != 0)
2129                                        {
2130                                                $filter_array = explode("<=>",rawurldecode($criteria));
2131                                                $filter .= " ".$filter_array[0];
2132                                                $filter .= '"'.$filter_array[1].'"';
2133                                        }
2134                                }               
2135                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
2136                                $filter = $this->remove_accents($filter);
2137                               
2138                                if(!is_resource($mbox_stream))
2139                                        $mbox_stream = $this->open_mbox($name_box);
2140                                else
2141                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
2142                       
2143                                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search   
2144                               
2145                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
2146                                        foreach($all_criterias as $criteria_fixed)
2147                                        {
2148                                                $_filter = $criteria_fixed . substr($filter,4);
2149                                       
2150                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
2151                                               
2152                                                if($search_criteria && count($search_criteria) < 50)
2153                                                {
2154                                                        foreach($search_criteria as $new_search){
2155                                                                $m_token = trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--".$new_search."##"."\n");
2156                                                                if(!@strstr($retorno,$m_token))
2157                                                                        $retorno .= $m_token;
2158                                                        }
2159                                                }                                               
2160                                                else if(count($search_criteria) >= 50)                                                 
2161                                                        return "many results";                                         
2162                                        }
2163                                }
2164                                else {
2165                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
2166                                        if( is_array( $search_criteria) )
2167                                        {
2168                                                foreach($search_criteria as $new_search)
2169                                                        $retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
2170                                        }
2171                                }
2172                        }
2173                }
2174                if($mbox_stream)
2175                        imap_close($mbox_stream);               
2176                                               
2177                return $retorno ? $retorno : "none";
2178        }
2179       
2180        function get_msg($uid_msg,$name_box, $mbox_stream )
2181        {
2182                $header = @imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $uid_msg), 80, 255);         
2183                $subject = $this->decode_string($header->fetchsubject);
2184                $from = $header->from[0]->mailbox;
2185                if($header->from[0]->personal != "")
2186                        $from = $header->from[0]->personal;
2187                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". date("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size);
2188                return $ret_msg;                   
2189        }       
2190       
2191        function size_msg($size){
2192                $var = floor($size/1024);
2193                if($var >= 1){
2194                        return $var." kb";     
2195                }else{
2196                        return $size ." b";     
2197                }
2198        }
2199
2200        function ob_array($the_object)
2201        {
2202           $the_array=array();
2203           if(!is_scalar($the_object))
2204           {
2205               foreach($the_object as $id => $object)
2206               {
2207                   if(is_scalar($object))
2208                   {
2209                       $the_array[$id]=$object;
2210                   }
2211                   else
2212                   {
2213                       $the_array[$id]=$this->ob_array($object);
2214                   }
2215               }
2216               return $the_array;
2217           }
2218           else
2219           {
2220               return $the_object;
2221           }
2222        }
2223       
2224        function getacl()
2225        {
2226                $this->ldap = new ldap_functions();
2227               
2228                $return = array();
2229                $mbox_stream = $this->open_mbox();     
2230                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
2231               
2232                $i = 0;
2233                foreach ($mbox_acl as $user => $acl)
2234                {
2235                        if ($user != $this->username)
2236                        {
2237                                $return[$i]['uid'] = $user;
2238                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
2239                        }
2240                        $i++;
2241                }
2242                return $return;
2243        }
2244       
2245        function setacl($params)
2246        {
2247                $old_users = $this->getacl();
2248                if (!count($old_users))
2249                        $old_users = array();
2250               
2251                $tmp_array = array();
2252                foreach ($old_users as $index => $user_info)
2253                {
2254                        $tmp_array[$index] = $user_info['uid'];
2255                }
2256                $old_users = $tmp_array;
2257               
2258                $users = unserialize($params['users']);
2259                if (!count($users))
2260                        $users = array();
2261               
2262                //$add_share = array_diff($users, $old_users);
2263                $remove_share = array_diff($old_users, $users);
2264
2265                $mbox_stream = $this->open_mbox();
2266
2267                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2268                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
2269
2270                /*if (count($add_share))
2271                {
2272                        foreach ($add_share as $index=>$uid)
2273                        {
2274                        if (is_array($mailboxes_list))
2275                        {
2276                        foreach ($mailboxes_list as $key => $val)
2277                        {
2278                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
2279                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
2280                        }
2281                        }
2282                        }
2283                }*/
2284               
2285                if (count($remove_share))
2286                {
2287                        foreach ($remove_share as $index=>$uid)
2288                        {
2289                        if (is_array($mailboxes_list))
2290                        {
2291                        foreach ($mailboxes_list as $key => $val)
2292                        {
2293                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
2294                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
2295                        }
2296                        }
2297                        }       
2298                }
2299               
2300                return true;
2301        }
2302       
2303        function getaclfromuser($params)
2304        {
2305                $useracl = $params['user'];
2306               
2307                $return = array();
2308                $return[$useracl] = 'false';
2309                $mbox_stream = $this->open_mbox();     
2310                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
2311               
2312                foreach ($mbox_acl as $user => $acl)
2313                {
2314                        if (($user != $this->username) && ($user == $useracl))
2315                        {
2316                                $return[$user] = $acl;
2317                        }
2318                }
2319                return $return;
2320        }
2321
2322        function getacltouser($user)
2323        {
2324                $return = array();
2325                $mbox_stream = $this->open_mbox();
2326                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
2327                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
2328                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
2329                if(substr($user,0,4) != 'user')
2330                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
2331                else
2332                  $mbox_acl = imap_getacl($mbox_stream, $user);
2333                return $mbox_acl[$this->username];
2334        }
2335       
2336
2337        function setaclfromuser($params)
2338        {
2339                $user = $params['user'];
2340                $acl = $params['acl'];
2341               
2342                $mbox_stream = $this->open_mbox();
2343
2344                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2345                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
2346
2347                if (is_array($mailboxes_list))
2348                {
2349                        foreach ($mailboxes_list as $key => $val)
2350                        {
2351                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
2352                                $folder = str_replace("&-", "&", $folder);
2353                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
2354                                {
2355                                        $return = imap_last_error();
2356                                }
2357                        }
2358                }
2359                if (isset($return))
2360                        return $return;
2361                else
2362                        return true;
2363        }
2364       
2365        function download_attachment($msg,$msgno)
2366        {
2367                $array_parts_attachments = array();             
2368                $array_parts_attachments['names'] = '';
2369                include("class.imap_attachment.inc.php");
2370                $imap_attachment = new imap_attachment();               
2371               
2372                if (count($msg->fname[$msgno]) > 0)
2373                {
2374                        $i = 0;
2375                        foreach ($msg->fname[$msgno] as $index=>$fname)
2376                        {
2377                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
2378                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($fname);
2379                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
2380                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
2381                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
2382                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
2383                                $i++;
2384                        }
2385                }
2386                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
2387                return $array_parts_attachments;
2388        }       
2389
2390        function spam($params)
2391        {
2392                $is_spam = $params['spam'];
2393                $folder = $params['folder'];
2394                $mbox_stream = $this->open_mbox($folder);
2395                $msgs_number = explode(',',$params['msgs_number']);
2396
2397                foreach($msgs_number as $msg_number) {
2398                        $header = imap_fetchheader($mbox_stream, imap_msgno($mbox_stream, $msg_number));
2399                        $body = imap_body($mbox_stream, imap_msgno($mbox_stream, $msg_number));
2400                        $msg = $header . $body;
2401                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2402                        $username = $this->username;
2403                        strtok($email, '@');
2404                        $domain = strtok('@');
2405
2406                        //Encontrar a assinatura do dspam no cabecalho
2407                        $v = explode("\r\n", $header);
2408                        foreach ($v as $linha){
2409                                if (eregi("^X-DSPAM-Signature", $linha)) {
2410                                       
2411                                        $args = explode(" ",$linha);
2412                                        $signature = $args[1];
2413                                }
2414                        }
2415
2416                        // feed dspam
2417                        switch($is_spam){
2418                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
2419                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
2420                        }
2421                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##');
2422                        $cmd = str_replace($tags,array($email,$username,$domain,$signature),$cmd);
2423                        system($cmd);
2424                }
2425                imap_close($mbox_stream);
2426                return false;
2427        }
2428}
2429?>
Note: See TracBrowser for help on using the repository browser.