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

Revision 13, 67.5 KB checked in by niltonneto, 17 years ago (diff)

* empty log message *

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