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

Revision 2, 66.9 KB checked in by niltonneto, 17 years ago (diff)

Removida todas as tags usadas pelo CVS ($Id, $Source).
Primeira versão no CVS externo.

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