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

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