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

Revision 96, 71.0 KB checked in by wmerlotto, 16 years ago (diff)

Continuação da internacionalização do Expresso. Retirado mais strings hardcoded e internacionalizada a as pastas do IMAP. Corrigido problema na caixa de filtros.

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