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

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