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

Revision 345, 80.9 KB checked in by niltonneto, 16 years ago (diff)
  • Frases truncadas devido ao commit anterior, proveniente de

charset incorreto usado, foram revertidas de forma correta;

  • Correção na inserção de imagens em nova mensagem;
  • Correção de problema com mensagens que contêm caracteres

especiais conflitantes com a função unserialize no Javascript;

  • Otimização das funções IMAP: replace_links,

htmlspecialchars_encode(decode);

  • Inserção de verificações em variáveis nulas;
  • Otimização do código que carrega a cota da pasta compartilhada,

evitando várias requisições ao servidor, ou seja, trazendo as
informações do IMAP em uma requisição.
-Correção ao mover/deletar mensagens do resultado da pesquisa.

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