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

Revision 163, 73.0 KB checked in by niltonneto, 16 years ago (diff)

Correção das funcionalidades: Mover e Apagar, do resultado da pesquisa.
Otimizado código do CSS utilizado nas linhas da lista de mensagens.
Correção de algumas traduções.

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