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

Revision 426, 83.4 KB checked in by niltonneto, 16 years ago (diff)

http://www.expressolivre.org/dev/ticket/326

Incluir o campo CCo na cópia da mensagem enviada.

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