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

Revision 46, 68.8 KB checked in by niltonneto, 17 years ago (diff)

* empty log message *

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