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

Revision 53, 68.6 KB checked in by niltonneto, 17 years ago (diff)

Vide change_log.txt

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