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

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