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

Revision 205, 73.2 KB checked in by niltonneto, 16 years ago (diff)

ver Ticket #154 e #155;
Otimizar verificação do Fora de Escritório;
Otimizar código que salva as preferências;

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