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

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