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

Revision 6, 67.3 KB checked in by niltonneto, 17 years ago (diff)

Corrigido problema ocorrido na mudança do cyrus_delimiter no Expresso.

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