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

Revision 485, 85.5 KB checked in by niltonneto, 16 years ago (diff)

Quando os contatos dinâmicos estiverem habilitados para o usuário:

  • Número máximo de contatos é carregado do array salvo na sessão, evitando a chamada AJAX ao

carregar módulo, que era invocada em preferences.js pela funçao get_number_of_contacts().

  • Ao invés de usar a função JS init() para recarregar o autocompletar, que é muito pesado, apenas

atualizar a variavel "contacts" com os novos contatos dinãmicos adicionados, retornados pela
função que envia o email, verificando se os mesmos já não existem.

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