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

Revision 51, 69.1 KB checked in by niltonneto, 17 years ago (diff)

Atualizações da versão nova.

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