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 *
RevLine 
[2]1<?php
2include_once("class.functions.inc.php");
3include_once("class.ldap_functions.inc.php");
[91]4include_once("class.exporteml.inc.php");
5
[2]6class imap_functions
7{
8        var $public_functions = array
[449]9        (       
[2]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'];
[449]28                $this->functions          = new functions();           
[2]29                $this->has_cid = false;
[449]30               
[2]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        {
[51]43                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
[2]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();
[53]52                $folder = $params['folder'];
[2]53                $msg_range_begin = $params['msg_range_begin'];
54                $msg_range_end = $params['msg_range_end'];
[449]55                $sort_box_type = $params['sort_box_type'];             
[53]56                $sort_box_reverse = $params['sort_box_reverse'];
[51]57                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
[449]58                $sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);                               
59               
[2]60                $return = array();
61                $i = 0;
[46]62                $num_msgs = (is_array($sort_array_msg) ? count($sort_array_msg) : 0);
[449]63                if($num_msgs) {
[46]64                        for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= $num_msgs)); $msg_range_begin++)
[2]65                {
66                        $msg_number = $sort_array_msg[$msg_range_begin-1];
67
[51]68                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
[2]69                        if (!is_object($header))
[449]70                                return false;                   
71                       
[2]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;
[449]79                                $return[$i]['Draft']    = $header->Draft;       
[2]80                        }
81                        $return[$i]['Deleted'] = $header->Deleted;
82                        $return[$i]['Flagged'] = $header->Flagged;
[449]83                       
[2]84                        $return[$i]['msg_number'] = $msg_number;
85                        //$return[$i]['msg_folder'] = $folder;
[449]86                       
[2]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;
[449]92                       
[2]93                        $from = $header->from;
94                        $return[$i]['from'] = array();
95                        $tmp = imap_mime_header_decode($from[0]->personal);
[37]96                        $return[$i]['from']['name'] = $this->decode_string($tmp[0]->text);
[2]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);
[37]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'];
[2]107                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
108
109                        $return[$i]['Size'] = $header->Size;
[449]110                       
[2]111                        $return[$i]['attachment'] = array();
[449]112                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);                     
[2]113                        $i++;
114                }
[46]115                }
[449]116                $return['num_msgs'] = $num_msgs;               
117               
[2]118                return $return;
119        }
[449]120       
[2]121        function decode_string($string)
[449]122        {       
[2]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        }
[449]147       
[2]148        function get_info_msg($params)
149        {
[51]150                $return = array();
[2]151                $msg_number = $params['msg_number'];
[205]152                $msg_folder = $params['msg_folder'];
[449]153               
[411]154                if(!$this->mbox || !is_resource($this->mbox))
[449]155                        $this->mbox = $this->open_mbox($msg_folder);           
156               
[205]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                }
[51]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);
[449]164               
[51]165                $return['body']                 = $return_get_body['body'];
166                $return['attachments']  = $return_get_body['attachments'];
[91]167                $return['thumbs']               = $return_get_body['thumbs'];
168                $return['signature']    = $return_get_body['signature'];
[449]169               
[2]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;
[449]178                $return['Deleted']      = $header->Deleted;             
[2]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;
[449]186                        $return['Draft']        = $header->Draft;       
[2]187                }
188
189                $return['msg_number'] = $msg_number;
190                $return['msg_folder'] = $msg_folder;
[449]191       
[2]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;
[449]197               
198                $return['msg_day'] = $date_msg;
[2]199                $return['msg_hour'] = date("H:i",$header->udate);
[449]200               
[2]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);
[449]205                       
[2]206                        $timestamp_now = strtotime("now");
207                        $timestamp_msg_time = $header->udate;
208                        $timestamp_diff = $timestamp_now - $timestamp_msg_time;
[449]209                       
[2]210                        if (gmdate("H",$timestamp_diff) > 0)
211                        {
[197]212                                $return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
[2]213                        }
214                        else
215                        {
216                                if (gmdate("i",$timestamp_diff) == 0){
[197]217                                        $return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
[2]218                                }
219                                elseif (gmdate("i",$timestamp_diff) == 1){
[197]220                                        $return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
[2]221                                }
222                                else{
[197]223                                        $return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
[2]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                }
[449]231               
[2]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'];
[449]246               
[2]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;";
[320]277                                        if ($tmp->host != 'unspecified-domain')
278                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
279                                        else
280                                                $return['toaddress2'] .= $tmp->mailbox;
[2]281                                        $return['toaddress2'] .= "&gt;";
282                                        $return['toaddress2'] .= ", ";
283                                }
284                                else
285                                {
[320]286                                        if ($tmp->host != 'unspecified-domain')
287                                                $return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
288                                        else
289                                                $return['toaddress2'] .= $tmp->mailbox;
[2]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;";
[449]298                }       
299               
[2]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'] = "";
[449]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']);
[426]357                }
[449]358                else
359                {
360                        $return['bcc'] = "";
361                }       
[426]362
[2]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);
[41]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                                        }
[2]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;
[449]393               
[2]394                return $return;
395        }
[449]396       
[2]397        function get_body_msg($msg_number, $msg_folder)
398        {
399                include_once("class.message_components.inc.php");
[51]400                $msg = &new message_components($this->mbox);
[2]401                $msg->fetch_structure($msg_number);
[51]402                $return = array();
[449]403                $return['attachments'] = $this-> download_attachment($msg,$msg_number);         
[51]404                if(!$this->has_cid)
[91]405                {
[178]406                        $return['thumbs']  = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
[91]407                        $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
[449]408                }                       
409               
[2]410                if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
411                {
412                        $attachment = array(); //No attachments
[449]413                       
[2]414                        $content = '';
415                        if (strtolower($msg->structure[$msg_number]->subtype) == "plain")
416                        {
[51]417                                $content .= nl2br($this->decodeBody((imap_body($this->mbox, $msg_number, FT_UID)), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]));
[2]418                        }
419                        else if (strtolower($msg->structure[$msg_number]->subtype) == "html")
420                        {
[51]421                                $content .= $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
[2]422                        }
423                }
[449]424                else
[2]425                { //Complicated message, multiple parts
426                        $html_body = '';
427                        $content = '';
428                        $has_multipart = true;
429                        $this->has_cid = false;
[449]430                       
[2]431                        if (strtolower($msg->structure[$msg_number]->subtype) == "related")
432                                $this->has_cid = true;
[449]433                       
[469]434                        if (strtolower($msg->structure[$msg_number]->subtype) == "alternative") {
435                                $show_only_html = false;
436                                foreach($msg->pid[$msg_number] as $values => $msg_part) {
[432]437                                        $file_type = strtolower($msg->file_type[$msg_number][$values]);
438                                        if($file_type == "text/html")
[469]439                                                $show_only_html = true;                 
[432]440                                }
[469]441                        }
[2]442                        else
443                                $show_only_html = false;
444
445                        foreach($msg->pid[$msg_number] as $values => $msg_part)
446                        {
[449]447                               
[2]448                                $file_type = strtolower($msg->file_type[$msg_number][$values]);
449                                if($file_type == "message/rfc822")
450                                        $has_multipart = false;
[449]451       
[2]452                                if($file_type == "multipart/alternative")
453                                        $has_multipart = false;
[449]454       
455                                if(($file_type == "text/plain"
[2]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)) {
[449]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])));                                                     
[2]464                                                }
465                                        }
466                                        // if HTML attachment file size > 300kb, then it will not expand.
[449]467                                        else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < 307200)
[2]468                                        {
[51]469                                                $content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
[2]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'>";
[449]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]));                                           
[2]476
477                                }
[65]478                                else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
[449]479                                       
[2]480                                        include_once("class.imap_attachment.inc.php");
481                                        $att = new imap_attachment();
[51]482                                        $attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
[449]483                                        if($attachments['number_attachments'] > 0) {                                                                                           
[2]484                                                foreach($attachments ['attachment'] as $index => $attachment){
485                                                        if(strtolower($attachment['type']) == "delivery-status" ||
[449]486                                                                strtolower($attachment['type']) == "rfc822" ||                                                         
[65]487                                                                strtolower($attachment['type']) == "rfc822-headers" ||
[2]488                                                                strtolower($attachment['type']) == "plain"
489                                                        ){
[449]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'>";                                   
[2]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>";
[449]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>";                                                               
[2]498                                                                $ix_part =      strtolower($attachment['type']) == "delivery-status" ? 1 : 0;
[449]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;                 
[2]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)
[51]508                                        $content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
[25]509                                else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
[449]510                                        $content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));                         
[2]511                        }
[449]512                }
[2]513                // Force message with flag Seen (imap_fetchbody not works correctly)
[449]514                $params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");                               
[2]515                $this->set_messages_flag($params);
[205]516                $content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
[2]517                $content = $this->replace_special_characters($content);
[51]518                $return['body'] = $content;
519                return $return;
[2]520        }
[449]521       
[2]522        function htmlfilter($body)
523        {
524                require_once('htmlfilter.inc');
[449]525               
[2]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                                        )
[449]598                                    ),     
599         
[2]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                );
[449]625       
626       
[2]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                );
[449]636       
[2]637            return $trusted_body;
638        }
[449]639       
[2]640        function decodeBody($body, $encoding, $charset=null)
641        {
642                /**
643                * replace e-mail by anchor.
644                */
645                // HTML Filter
[13]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);
[2]647        $body = str_replace("\r\n", "\n", $body);
648                if ($encoding == 'quoted-printable')
649            {
[449]650                       
[2]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);
[449]657                        }               
[2]658                        $body = str_replace($myqprinta,$myqprintb,($body));
659                        $body = quoted_printable_decode($body);
[449]660                while (ereg("=\n", $body))
[2]661                {
662                        $body = ereg_replace ("=\n", '', $body);
663                }
664        }
[449]665        else if ($encoding == 'base64')
[2]666        {
667                $body = base64_decode($body);
668        }
[449]669        /*else if ($encoding == '7bit')
[12]670        {
[449]671                $body = quoted_printable_decode($body);                                         
[13]672        }*/
[2]673                // All other encodings are returned raw.
674                if (strtolower($charset) == "utf-8")
675                        return utf8_decode($body);
676        else
677                        return $body;
678        }
[449]679       
[205]680        function process_embedded_images($msg, $msgno, $body, $msg_folder)
[2]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                }
[449]696               
[2]697                return $body;
698        }
[449]699       
[2]700        function replace_special_characters($body)
701        {
702                // Suspected TAGS!
[449]703                /*$tag_list = Array(   
[2]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
[449]712                // Layout problem: Change html elements
713                // with absolute position to relate position, CASE INSENSITIVE.
[6]714                $body = @eregi_replace("POSITION: ABSOLUTE;","",$body);
715
[2]716                $tag_list = Array('head','blink','object','frame',
717                        'iframe','layer','ilayer','plaintext','script',
[63]718                        'applet','embed','frameset','xml','xmp','style');
[2]719
720                $body = $this-> replace_links($body);
[449]721                $blocked_tags = array();               
[2]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
[449]733        function replace_links($body) {                                 
734                $matches = array();
[2]735                // Verify exception.
[449]736                @preg_match("/<a href=\"notes:\/\/\//",$body,$matches);
[2]737                // It no has exception,then open the link in new window.
[449]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);
[2]747        }
748
[91]749        function get_signature($msg, $msg_number, $msg_folder)
[449]750        {
[91]751                foreach ($msg->file_type[$msg_number] as $index => $file_type)
752                {
753                        $file_type = strtolower($file_type);
[449]754                        if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
[91]755                        {
[449]756                                if ($file_type == 'application/x-pkcs7-signature')
[91]757                                {
758                                        $export_mail = new ExportEml();
759                                        $params['folder'] = $msg_folder;
760                                        $params['msgs_to_export'] = $msg_number;
[109]761                                    $tempDir = ini_get("session.save_path");
[449]762                                        $cert_file = $tempDir."/certificate_".base_convert(microtime(), 10, 36).".crt";                                 
[109]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                                        }
[91]774                                    /* Message verified */
775                                    if ($result === true)
[109]776                                            $sign = $temp;
[91]777                                     else
778                                            $sign = "void";
779                                }
780                        }
781                }
[449]782                return $sign;   
[91]783        }
784
[51]785        function get_thumbs($msg, $msg_number, $msg_folder)
[2]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        }
[449]803               
[2]804        /*function delete_msg($params)
805        {
806                $folder = $params['folder'];
807                $msgs_to_delete = explode(",",$params['msgs_to_delete']);
[449]808               
[2]809                $mbox_stream = $this->open_mbox($folder);
[449]810               
[2]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        {
[449]821               
[2]822                $folder = $params['folder'];
[51]823                $folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
[2]824                $msgs_number = explode(",",$params['msgs_number']);
825                $border_ID = $params['border_ID'];
[449]826               
[2]827                $return = array();
[449]828               
829                if ($params['get_previous_msg']){
[2]830                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]831                        // Fix problem in unserialize function JS.
832                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
833                }
[2]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())));
[449]837               
[2]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                }
[449]843               
[2]844                $return['folder'] = $folder;
845                $return['border_ID'] = $border_ID;
[449]846               
[51]847                if($mbox_stream)
848                        imap_close($mbox_stream, CL_EXPUNGE);
[2]849                return $return;
850        }
851
[449]852               
[2]853        function refresh($params)
854        {
855                include("class.imap_attachment.inc.php");
[449]856                $imap_attachment = new imap_attachment();               
[2]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'];
[449]861                $sort_box_type = $params['sort_box_type'];             
[2]862                $sort_box_reverse = $params['sort_box_reverse'];
863                $msgs_in_the_server = array();
[53]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);
[51]866
867                if(!count($sort_array_msg))
868                        return array();
[449]869                       
[51]870                $num_msgs = (count($sort_array_msg) - imap_num_recent($this->mbox));
871                $msgs_in_the_client = explode(",", $msgs_existent);
872
[449]873               
[2]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                }
[449]888               
[2]889                $msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
[271]890                $msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
[449]891               
[2]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                }
[449]917               
[2]918                $return = array();
919                $i = 0;
920                foreach($msgs_to_exec as $msg_number => $command)
921                {
[51]922                        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox , $msg_number), 80, 255);
[2]923                        if (!is_object($header))
924                                return false;
[449]925                       
[2]926                        $return[$i]['msg_number']       = $msg_number;
927                        $return[$i]['command']          = $command;
[449]928                       
[2]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;
[449]942                       
[2]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;
[449]948                        //$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
[2]949                        if(!$return[$i]['from']['name'])
950                                $return[$i]['from']['name'] = $return[$i]['from']['email'];
[449]951                       
[2]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'] . '>';
[449]962                       
[2]963                        $return[$i]['subject'] = $this->decode_string($header->fetchsubject);
964
965                        $return[$i]['Size'] = $header->Size;
966                        $return[$i]['reply_toaddress'] = $header->reply_toaddress;
[449]967                       
[2]968                        $return[$i]['attachment'] = array();
[51]969                        $return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
[2]970                        $i++;
971                }
[51]972                $return['new_msgs'] = imap_num_recent($this->mbox);
[271]973                $return['msgs_to_delete'] = $msg_to_delete;
[411]974                if($this->mbox && is_resource($this->mbox))
[51]975                        imap_close($this->mbox);
[2]976                return $return;
977        }
978
[449]979        function get_folders_list($params = null)
[2]980        {
[449]981                $mbox_stream = $this->open_mbox();             
[115]982                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
[2]983                $folders_list = imap_getmailboxes($mbox_stream, $serverString, "*");
984                $tmp = array();
985                $result = array();
[449]986               
[2]987                if (is_array($folders_list)) {
988                        reset($folders_list);
[449]989                       
[2]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;
[449]994                       
[2]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;
[449]999                               
[2]1000                                $tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
1001                                $result[$i]['folder_name'] = array_pop($tmp_folder_parent);
[96]1002                                $result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
[325]1003                                if (is_numeric($result[$i]['folder_name']))     {
[469]1004                                        $this->ldap = new ldap_functions();
[432]1005                                        if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])){
[325]1006                                                $result[$i]['folder_name'] = $cn;
1007                                        }
1008                                }
[449]1009                               
[2]1010                                $tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
1011                                $result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
[449]1012                                       
[96]1013                                if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
[2]1014                                        $result[$i]['folder_hasChildren'] = 1;
1015                                else
1016                                        $result[$i]['folder_hasChildren'] = 0;
1017
[449]1018                                $i++;                           
[2]1019                        }
1020                }
[449]1021               
[2]1022                foreach ($result as $folder_info)
1023                {
1024                        $array_tmp[] = $folder_info['folder_id'];
1025                }
[449]1026               
[2]1027                natcasesort($array_tmp);
[449]1028               
[2]1029                foreach ($array_tmp as $key => $folder_id)
1030                {
1031                        $result2[] = $result[$key];
1032                }
[449]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)));
[2]1038        }
[449]1039       
[2]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'];
[51]1045                $namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
[449]1046               
[2]1047                $result = "Ok";
[51]1048                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
[2]1049                {
1050                        $result = implode("<br />\n", imap_errors());
[449]1051                }       
1052               
[51]1053                if($mbox_stream)
1054                        imap_close($mbox_stream);
[449]1055                                       
[2]1056                return $result;
[449]1057               
[2]1058        }
[449]1059       
[2]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'];
[449]1066                foreach($nameboxs as $key=>$tmp){                       
[2]1067                        if($tmp != ""){
1068                                if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
1069                                        $result = implode("<br />\n", imap_errors());
[51]1070                                        if($mbox_stream)
[449]1071                                                imap_close($mbox_stream);                                       
[2]1072                                        return $result;
1073                                }
1074                        }
1075                }
[51]1076                if($mbox_stream)
1077                        imap_close($mbox_stream);
[2]1078                return true;
1079        }
[449]1080       
[2]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");
[449]1087               
[2]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                }
[51]1094                if($mbox_stream)
1095                        imap_close($mbox_stream);
[2]1096                return $result;
1097        }
[449]1098       
[2]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");
[449]1106               
[2]1107                $result = "Ok";
1108                $namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
[51]1109                $new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
[449]1110               
[2]1111                if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
1112                {
[449]1113                        $result = imap_errors();                       
[2]1114                }
[51]1115                if($mbox_stream)
1116                        imap_close($mbox_stream);
[2]1117                return $result;
[449]1118               
[2]1119        }
[449]1120       
[2]1121        function get_num_msgs($params)
1122        {
1123                $folder = $params['folder'];
[411]1124                if(!$this->mbox || !is_resource($this->mbox)) {
[2]1125                        $this->mbox = $this->open_mbox($folder);
[411]1126                        if(!$this->mbox || !is_resource($this->mbox))
[2]1127                        return imap_last_error();
[449]1128                }               
[2]1129                $num_msgs = imap_num_msg($this->mbox);
[432]1130                if($this->mbox && is_resource($this->mbox))
[51]1131                        imap_close($this->mbox);
[449]1132               
[2]1133                return $num_msgs;
1134        }
[449]1135       
[2]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']) : "";
[449]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                }
[2]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'];
[271]1162                $msg_uid = $params['msg_id'];
[2]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'];
[449]1168                 
[51]1169                $folder =$params['folder'];
[449]1170                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
1171                $folder_name = $params['folder_name'];         
[6]1172                // Fix problem with cyrus delimiter changes.
[449]1173                // Dots in names: enabled/disabled.                             
[6]1174                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1175                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1176                // End Fix.
[449]1177                if ($folder != 'null'){                 
[2]1178                        $mail->SaveMessageInFolder = $folder;
1179                }
1180////////////////////////////////////////////////////////////////////////////////////////////////////
1181                $mail->SMTPDebug = false;
[449]1182                               
[2]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                }
[449]1194                               
[2]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'];
[271]1201
[2]1202////////////////////////////////////////////////////////////////////////////////////////////////////
[271]1203                //      Build CID for embedded Images!!!
[449]1204                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
[271]1205                $cid_imgs = '';
1206                $name_cid_files = array();
1207                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1208                $cid_array = array();
[449]1209                foreach($cid_imgs[6] as $j => $val){
1210                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
[271]1211                        {
[449]1212                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
[271]1213                        }
[449]1214                        $cid = $cid_array[$cid_imgs[4][$j].$val];
[271]1215                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
[449]1216                       
1217                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
[271]1218                                {
[449]1219                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
[271]1220                                        $fileName = "image_".($j).".jpg";
1221                                        $fileCode = "base64";
1222                                        $fileType = "image/jpg";
1223                                }
1224                                else
1225                                {
[449]1226                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
[271]1227                                        $file_description = unserialize(rawurldecode($attach_img));
1228
[449]1229                                        foreach($file_description as $i => $descriptor){                               
[271]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]);
[449]1236                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
[271]1237                                }
1238                                $tempDir = ini_get("session.save_path");
[449]1239                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
[271]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
[449]1246                                //      return "Error loading image attachment content";                                               
[271]1247
1248                }
1249////////////////////////////////////////////////////////////////////////////////////////////////////
[2]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)
[449]1261                                return 'false';                 
1262                }                       
[2]1263////////////////////////////////////////////////////////////////////////////////////////////////////
[271]1264                //      Build Forwarding Attachments!!!
[2]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;
[449]1271                        }                       
1272                       
[2]1273                        foreach($forwarding_attachments as $forwarding_attachment)
1274                        {
[271]1275                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
1276                                        $tmp = array_values($file_description);
[449]1277                                        foreach($file_description as $i => $descriptor){                               
[271]1278                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1279                                        }
[449]1280                                        $file_description = $tmp;                                       
[271]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]));
[63]1285                                }
[2]1286                        }
1287                }
[37]1288
[2]1289////////////////////////////////////////////////////////////////////////////////////////////////////
1290                // Disposition-Notification-To
1291                if ($return_receipt)
1292                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1293////////////////////////////////////////////////////////////////////////////////////////////////////
[117]1294                $sent = $mail->Send();
1295                if(!$sent)
[2]1296                {
1297                        return $mail->ErrorInfo;
1298                }
1299                else
1300                {
[449]1301                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
[117]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;
[449]1307                                $sent = trim($sent);                                                                                           
[117]1308                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
1309                        }
[485]1310                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
1311                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
[469]1312                                $contacts = new dynamic_contacts();
[485]1313                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
1314                                return array("success" => true, "new_contacts" => $new_contacts);
[413]1315                        }
[485]1316                        return array("success" => true);
[2]1317                }
1318        }
1319
1320        function add_recipients($recipient_type, $full_address, $mail)
1321        {
[449]1322                $parse_address = imap_rfc822_parse_adrlist($full_address, "");         
1323                foreach ($parse_address as $val)
[2]1324                {
1325                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
1326                        if ($val->mailbox == "INVALID_ADDRESS")
1327                                continue;
[449]1328                       
[2]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        }
[449]1362       
[2]1363        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
1364        {
[449]1365                $mbox_stream = $this->open_mbox($msg_folder);                   
1366                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);           
[2]1367                if($encoding == 'base64')
[449]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);
[2]1374                else if($encoding == 'quoted-printable')
[449]1375                        $fileContent = quoted_printable_decode($fileContent);                           
[2]1376                return $fileContent;
1377        }
[449]1378       
[2]1379        function del_last_caracter($string)
1380        {
1381                $string = substr($string,0,(strlen($string) - 1));
[449]1382                return $string;
[2]1383        }
[449]1384       
[2]1385        function del_last_two_caracters($string)
1386        {
1387                $string = substr($string,0,(strlen($string) - 2));
[449]1388                return $string;
[2]1389        }
[449]1390       
[53]1391        function imap_sortfrom($sort_box_reverse, $search_box_type)
[2]1392        {
1393                $sortfrom = array();
1394                $sortfrom_uid = array();
[449]1395               
[51]1396                $num_msgs = imap_num_msg($this->mbox);
[2]1397                for ($i=1; $i<=$num_msgs; $i++)
1398                {
[51]1399                        $header = imap_headerinfo($this->mbox, $i, 80, 255);
[53]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                        }
[449]1408                        // List ANSWERED messages.                     
[53]1409                        elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
[449]1410                                continue;                               
[53]1411                        }
[449]1412                        // List FLAGGED messages.                       
[53]1413                        elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
1414                                continue;
1415                        }
[449]1416                                               
1417                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])                             
[2]1418                                $from = $header->to;
1419                        else
1420                                $from = $header->from;
[449]1421                       
1422                        $tmp = imap_mime_header_decode($from[0]->personal);                     
1423                       
[2]1424                        if ($tmp[0]->text != "")
[53]1425                                $sortfrom[$i] = $tmp[0]->text;
[2]1426                        else
[53]1427                                $sortfrom[$i] = $from[0]->mailbox . "@" . $from[0]->host;
[2]1428                }
[449]1429               
[2]1430                natcasesort($sortfrom);
[449]1431               
[2]1432                foreach($sortfrom as $index => $header_msg)
[449]1433                {       
[53]1434                        $sortfrom_uid[] = imap_uid($this->mbox, $index);
[2]1435                }
[449]1436               
[2]1437                if ($sort_box_reverse)
1438                        $sortfrom_uid = array_reverse($sortfrom_uid);
[449]1439               
[2]1440                return $sortfrom_uid;
1441        }
[51]1442
[449]1443        function move_search_messages($params){         
1444                $params['selected_messages'] = urldecode($params['selected_messages']);
[163]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']);
[449]1448                @reset($sel_msgs);     
[163]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];
[449]1454                         }     
[163]1455                         else {
1456                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
1457                         }
1458                }
1459                @ksort($sorted_msgs);
[449]1460                $last_return = false;           
1461                foreach($sorted_msgs as $folder => $msgs_number) {                     
[163]1462                        $params['msgs_number'] = $msgs_number;
[449]1463                        $params['folder'] = $folder;   
[163]1464                        if($params['new_folder'] && $folder != $params['new_folder']){
[449]1465                                $last_return = $this -> move_messages($params);                         
[163]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        }
[449]1474       
[2]1475        function move_messages($params)
1476        {
[449]1477                $folder = $params['folder'];           
1478                $mbox_stream = $this->open_mbox($folder);               
[51]1479                $newmailbox = ($params['new_folder']);
1480                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
[2]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,
[325]1486                                                'border_ID' => $params['border_ID'],
1487                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
[449]1488               
[325]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        }
[432]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        }
[449]1517                               
1518                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.         
[51]1519                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
[449]1520                {
[2]1521                        $return['previous_msg'] = $this->get_info_previous_msg($params);
[449]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);       
[2]1527                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1528                        imap_expunge($mbox_stream);
[51]1529                        if($mbox_stream)
1530                                imap_close($mbox_stream);
[2]1531                        return $return;
1532                }else {
[449]1533                        if(strstr(imap_last_error(),'Over quota')) {                           
[2]1534                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
[449]1535                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];                                                                       
1536                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];                                                           
[2]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();
[449]1541                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");                           
[2]1542                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
[51]1543                                        if($mbox_stream)
1544                                                imap_close($mbox_stream);
[449]1545                                        if($mbox)                                                                       
[51]1546                                                imap_close($mbox);
[449]1547                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";                                                               
[2]1548                                }
1549                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1550                                        imap_expunge($mbox_stream);
[51]1551                                        if($mbox_stream)
1552                                                imap_close($mbox_stream);
[2]1553                                        // return to original quota limit.
1554                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]1555                                                if($mbox)
1556                                                        imap_close($mbox);
[449]1557                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
[2]1558                                        }
[449]1559                                        return $return;                                                                                                 
[2]1560                                }
1561                                else {
[51]1562                                        if($mbox_stream)
1563                                                imap_close($mbox_stream);
[2]1564                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
[51]1565                                                if($mbox)
1566                                                        imap_close($mbox);
[449]1567                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
[2]1568                                        }
[449]1569                                        return imap_last_error();                               
[2]1570                                }
[449]1571                               
[2]1572                        }
1573                        else {
[51]1574                                if($mbox_stream)
1575                                        imap_close($mbox_stream);
1576                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
[2]1577                        }
[449]1578                }               
[2]1579        }
[449]1580       
[2]1581        function save_msg($params)
1582        {
[449]1583               
[271]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'];
[320]1590                $msg_uid = $params['msg_id'];
[2]1591                $body = $params['body'];
1592                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
[155]1593                $body = preg_replace("/\n/"," ",$body);
[51]1594                $body = preg_replace("/\r/","",$body);
[271]1595                $forwarding_attachments = $params['forwarding_attachments'];
1596                $attachments = $params['FILES'];
1597                $return_files = $params['FILES'];
[449]1598                 
[271]1599                $folder = $params['folder'];
[449]1600                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
[271]1601                // Fix problem with cyrus delimiter changes.
[449]1602                // Dots in names: enabled/disabled.                             
[271]1603                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1604                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1605                // End Fix.
[449]1606                                       
[271]1607                $mail->SaveMessageInFolder = $folder;
1608                $mail->SMTPDebug = false;
[449]1609                                               
[271]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'];
[449]1615               
[271]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'];
[449]1620                               
[271]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;
[449]1626               
[320]1627                //      Build CID for embedded Images!!!
[449]1628                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
[320]1629                $cid_imgs = '';
1630                $name_cid_files = array();
1631                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1632                $cid_array = array();
[449]1633                foreach($cid_imgs[6] as $j => $val){
1634                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
[320]1635                        {
[449]1636                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
[320]1637                        }
[449]1638                        $cid = $cid_array[$cid_imgs[4][$j].$val];
[320]1639                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
[449]1640                       
1641                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
[320]1642                                {
[449]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)
[320]1645                                        $fileName = "image_".($j).".jpg";
1646                                        $fileCode = "base64";
1647                                        $fileType = "image/jpg";
[449]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;
[320]1655                                }
1656                                else
1657                                {
[449]1658                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
[320]1659                                        $file_description = unserialize(rawurldecode($attach_img));
[449]1660                                        foreach($file_description as $i => $descriptor){                               
[320]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]);
[449]1667                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
[320]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");
[449]1675                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
[320]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
[449]1682                                //      return "Error loading image attachment content";                                               
[320]1683
1684                }
[449]1685       
1686        //      Build Forwarding Attachments!!!         
[271]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);
[449]1693                                foreach($file_description as $i => $descriptor){                               
[271]1694                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1695                                }
1696                                $file_description = $tmp;
[449]1697                               
[271]1698                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
1699                                $fileName = $file_description[2];
[449]1700                               
[271]1701                                $file_description[5] = strlen($fileContent); //Size of file
1702                                $return_forward[] = $file_description;
[449]1703                       
[271]1704                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
1705                        }
1706                }
[449]1707               
[271]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;
[449]1713       
[271]1714                //      Build Uploading Attachments!!!
1715                if (count($attachments))
1716                        foreach ($attachments as $attach)
[449]1717                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name                 
1718       
1719       
1720               
[271]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();
[449]1728       
[271]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);
[449]1742       
[271]1743                $new_header = str_replace("\n", "\r\n", $header);
1744                $new_body = str_replace("\n", "\r\n", $body);
[449]1745               
[271]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;
[449]1750               
[51]1751                if($mbox_stream)
1752                        imap_close($mbox_stream);
[449]1753                               
[271]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                }
[449]1765               
[271]1766                $return['files'] = serialize($return_files);
[449]1767                               
[2]1768                if (!$return['append'])
1769                        $return['append'] = imap_last_error();
[449]1770               
[2]1771                return $return;
1772        }
[449]1773       
[2]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;
[449]1782               
[411]1783                if(!$this->mbox && !is_resource($this->mbox))
[51]1784                        $this->mbox = $this->open_mbox($folder);
[449]1785               
[2]1786                if ($flag == "unseen")
[51]1787                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]1788                elseif ($flag == "seen")
[51]1789                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
[2]1790                elseif ($flag == "answered"){
[51]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);
[2]1793                }
1794                elseif ($flag == "forwarded")
[51]1795                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
[2]1796                elseif ($flag == "flagged")
[51]1797                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
[2]1798                elseif ($flag == "unflagged")
[51]1799                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
[449]1800               
[411]1801                if($this->mbox && is_resource($this->mbox))
[51]1802                        imap_close($this->mbox);
[2]1803                return $return;
1804        }
[449]1805       
[2]1806        function get_file_type($file_name)
1807        {
1808                $file_name = strtolower($file_name);
1809                $strFileType = strrev(substr(strrev($file_name),0,4));
[449]1810                if ($strFileType == ".asf")
[2]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";
[449]1836                if ($strFileType == ".xml")
[2]1837                        return "text/xml";
[449]1838                if ($strFileType == ".xsl")
[2]1839                        return "text/xsl";
[449]1840                if ($strFileType == ".css")
[2]1841                        return "text/css";
[449]1842                if ($strFileType == ".php")
[2]1843                        return "text/php";
[449]1844                if ($strFileType == ".asp")
[2]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";
[449]1872               
1873               
1874                return "application/octet-stream";             
[2]1875        }
[449]1876       
[2]1877        function htmlspecialchars_encode($str)
1878        {
[449]1879                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
[2]1880        }
1881        function htmlspecialchars_decode($str)
1882        {
[449]1883                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
[2]1884        }
[449]1885       
[53]1886        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse){
[449]1887               
[411]1888                if(!$this->mbox || !is_resource($this->mbox)){
[51]1889                        $this->mbox = $this->open_mbox($folder);
[449]1890               
[411]1891                }
[432]1892
[2]1893                switch($sort_box_type){
1894                        case 'SORTFROM':
[449]1895                                return $this->imap_sortfrom($sort_box_reverse, $search_box_type);                               
[2]1896                        case 'SORTSUBJECT':
[449]1897                                return imap_sort($this->mbox, SORTSUBJECT, $sort_box_reverse, SE_UID, $search_box_type);                               
[2]1898                        case 'SORTSIZE':
[449]1899                                return imap_sort($this->mbox, SORTSIZE, $sort_box_reverse, SE_UID, $search_box_type);                           
[53]1900                        default:
[449]1901                                return imap_sort($this->mbox, SORTARRIVAL, $sort_box_reverse, SE_UID, $search_box_type);                                               
1902                }               
1903        }       
1904       
[53]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;
[449]1913                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);                             
1914               
[320]1915                $success = false;
1916                if (is_array($sort_array_msg))
[2]1917                {
[320]1918                        foreach ($sort_array_msg as $i => $value){
1919                                if ($value == $msg_number)
1920                                {
1921                                        $success = true;
1922                                        break;
1923                                }
1924                        }
[2]1925                }
1926
[320]1927                if (! $success || $i >= sizeof($sort_array_msg)-1)
[2]1928                {
1929                        $params['status'] = 'false';
1930                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
1931                        return $params;
1932                }
[449]1933               
[2]1934                $params = array();
1935                $params['msg_number'] = $sort_array_msg[($i+1)];
1936                $params['msg_folder'] = $folder;
[449]1937               
1938                $return = $this->get_info_msg($params);         
[2]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'];
[53]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);
[449]1952               
[320]1953                $success = false;
1954                if (is_array($sort_array_msg))
[2]1955                {
[320]1956                        foreach ($sort_array_msg as $i => $value){
1957                                if ($value == $msg_number)
1958                                {
1959                                        $success = true;
1960                                        break;
1961                                }
1962                        }
[2]1963                }
[320]1964                if (! $success || $i == 0)
1965                {
[2]1966                        $params['status'] = 'false';
1967                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
1968                        return $params;
1969                }
[449]1970               
[2]1971                $params = array();
1972                $params['msg_number'] = $sort_array_msg[($i-1)];
1973                $params['msg_folder'] = $folder;
[449]1974               
[2]1975                $return = $this->get_info_msg($params);
1976                $return["reuse_border"] = $reuse_border;
1977                return $return;
1978        }
[449]1979       
[2]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);
[449]1984               
[2]1985                $mbox_stream = $this->open_mbox($params['folder']);
[449]1986                $return_array['num_msgs'] = imap_num_msg($mbox_stream);         
[51]1987                if($mbox_stream)
1988                        imap_close($mbox_stream);
[449]1989                               
1990                return $return_array;
[2]1991        }
[449]1992       
[325]1993        function get_quota($params){
[449]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)
[51]2004                        $this->mbox = $this->open_mbox();
[345]2005
[325]2006                $quota = imap_get_quotaroot($this->mbox, $folder_id);
[411]2007                if($this->mbox && is_resource($this->mbox))
[51]2008                        imap_close($this->mbox);
[449]2009                       
[2]2010                if (!$quota){
2011                        return array(
2012                                'quota_percent' => 0,
2013                                'quota_used' => 0,
2014                                'quota_limit' =>  0
2015                        );
2016                }
[449]2017               
[2]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                }
[449]2032                else
[2]2033                        return array();
2034        }
[449]2035       
[2]2036        function send_notification($params){
2037                require_once("class.phpmailer.php");
2038                $mail = new PHPMailer();
[449]2039                 
[2]2040                $toaddress = $params['notificationto'];
[449]2041               
2042                $subject = 'Confirmação de leitura: ' . $params['subject'];
[2]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;
[449]2056               
[2]2057                if(!$mail->Send()){
2058                        return $mail->ErrorInfo;
2059                }
2060                else
2061                        return true;
2062        }
[449]2063       
[2]2064        function empty_trash()
2065        {
[449]2066                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
[2]2067                $mbox_stream = $this->open_mbox($folder);
2068                $return = imap_delete($mbox_stream,'1:*');
[51]2069                if($mbox_stream)
2070                        imap_close($mbox_stream, CL_EXPUNGE);
[2]2071                return $return;
2072        }
[449]2073       
[2]2074        function search($params)
2075        {
2076                include("class.imap_attachment.inc.php");
[449]2077                $imap_attachment = new imap_attachment();                               
[2]2078                $criteria = $params['criteria'];
2079                $return = array();
2080                $folders = $this->get_folders_list();
[449]2081               
[2]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);
[449]2087                       
[2]2088                        if ($messages == '')
2089                                continue;
[449]2090               
[2]2091                        $i = 0;
2092                        $return[$j] = array();
2093                        $return[$j]['folder_name'] = $folder['name'];
[449]2094                       
[2]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;
[449]2100                               
[2]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;
[449]2109       
[2]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;
[449]2115                       
[2]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);
[449]2120                       
[2]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;
[449]2126                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
[2]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;
[449]2133                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
[2]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;
[449]2142                       
[2]2143                                $return[$j][$i]['attachment'] = array();
2144                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
[449]2145                                               
[2]2146                                $i++;
2147                        }
2148                        $j++;
[51]2149                        if($mbox_stream)
2150                                imap_close($mbox_stream);
[2]2151                }
[449]2152       
[2]2153                return $return;
2154        }
[449]2155       
[2]2156        function delete_and_show_previous_message($params)
2157        {
2158                $return = $this->get_info_previous_msg($params);
[449]2159               
[2]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);
[449]2164               
[2]2165                $return['msg_number_deleted'] = $return_tmp1;
[449]2166               
[2]2167                return $return;
2168        }
[449]2169               
2170       
[2]2171        function automatic_trash_cleanness($params)
2172        {
2173                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
2174                $criteria =  'BEFORE "'.$before_date.'"';
[325]2175                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
[2]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                }
[51]2182                if($mbox_stream)
2183                        imap_close($mbox_stream, CL_EXPUNGE);
[2]2184                return $messages;
2185        }
2186//      Fix the search problem with special characters!!!!
2187        function remove_accents($string) {
[449]2188                return strtr($string,
2189                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
[2]2190                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
2191        }
2192
[469]2193        function search_msg($params = ''){             
[2]2194                $retorno = "";
[271]2195                $mbox_stream = "";
[2]2196                $search = explode(",",$params['condition']);
2197                if($search){
2198                        $search_criteria = '';
[271]2199                        foreach($search as $tmp)
2200                        {
[2]2201                                $tmp1 = explode("##",$tmp);
2202                                $name_box = $tmp1[0];
[372]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                                        }
[449]2212                                }               
2213                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
[372]2214                                $filter = $this->remove_accents($filter);
[469]2215                                //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
[432]2216                                $folder_name = explode($this->imap_delimiter,$name_box);
[469]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;
[432]2221                                        }
2222                                }
2223                                $folder_name = implode($this->imap_delimiter,$folder_name);
[449]2224                               
[271]2225                                if(!is_resource($mbox_stream))
[372]2226                                        $mbox_stream = $this->open_mbox($name_box);
[271]2227                                else
2228                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
[449]2229                       
2230                                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search   
2231                               
[271]2232                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
2233                                        foreach($all_criterias as $criteria_fixed)
2234                                        {
[372]2235                                                $_filter = $criteria_fixed . substr($filter,4);
[449]2236                                       
[372]2237                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
[449]2238                                               
[271]2239                                                if($search_criteria && count($search_criteria) < 50)
2240                                                {
[2]2241                                                        foreach($search_criteria as $new_search){
[449]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");
[271]2243                                                                if(!@strstr($retorno,$m_token))
[2]2244                                                                        $retorno .= $m_token;
2245                                                        }
[449]2246                                                }                                               
2247                                                else if(count($search_criteria) >= 50)                                                 
2248                                                        return "many results";                                         
[2]2249                                        }
[271]2250                                }
[2]2251                                else {
[271]2252                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
[372]2253                                        if( is_array( $search_criteria) )
2254                                        {
2255                                                foreach($search_criteria as $new_search)
[449]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");
[2]2257                                        }
2258                                }
2259                        }
[271]2260                }
2261                if($mbox_stream)
[449]2262                        imap_close($mbox_stream);               
2263                                               
[2]2264                return $retorno ? $retorno : "none";
2265        }
[449]2266       
[271]2267        function get_msg($uid_msg,$name_box, $mbox_stream )
2268        {
[449]2269                $header = @imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $uid_msg), 80, 255);         
[163]2270                $subject = $this->decode_string($header->fetchsubject);
2271                $from = $header->from[0]->mailbox;
[2]2272                if($header->from[0]->personal != "")
2273                        $from = $header->from[0]->personal;
[449]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       
[2]2278        function size_msg($size){
2279                $var = floor($size/1024);
2280                if($var >= 1){
[449]2281                        return $var." kb";     
[2]2282                }else{
[449]2283                        return $size ." b";     
[2]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        }
[449]2310       
[2]2311        function getacl()
2312        {
2313                $this->ldap = new ldap_functions();
[449]2314               
[2]2315                $return = array();
[449]2316                $mbox_stream = $this->open_mbox();     
[2]2317                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[449]2318               
[2]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        }
[449]2331       
[2]2332        function setacl($params)
2333        {
2334                $old_users = $this->getacl();
2335                if (!count($old_users))
2336                        $old_users = array();
[449]2337               
[2]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;
[449]2344               
[2]2345                $users = unserialize($params['users']);
2346                if (!count($users))
2347                        $users = array();
[449]2348               
[2]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                }*/
[449]2371               
[2]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                        }
[449]2384                        }       
[2]2385                }
[449]2386               
[2]2387                return true;
2388        }
[449]2389       
[2]2390        function getaclfromuser($params)
2391        {
2392                $useracl = $params['user'];
[449]2393               
[2]2394                $return = array();
2395                $return[$useracl] = 'false';
[449]2396                $mbox_stream = $this->open_mbox();     
[2]2397                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
[449]2398               
[2]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();
[325]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')
[449]2417                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
[325]2418                else
2419                  $mbox_acl = imap_getacl($mbox_stream, $user);
[2]2420                return $mbox_acl[$this->username];
2421        }
[449]2422       
[2]2423
2424        function setaclfromuser($params)
2425        {
2426                $user = $params['user'];
2427                $acl = $params['acl'];
[449]2428               
[2]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                        {
[449]2438                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
2439                                $folder = str_replace("&-", "&", $folder);
[2]2440                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
2441                                {
[449]2442                                        $return = imap_last_error();
[2]2443                                }
2444                        }
2445                }
[449]2446                if (isset($return))
2447                        return $return;
2448                else
2449                        return true;
[2]2450        }
[449]2451       
[51]2452        function download_attachment($msg,$msgno)
2453        {
[449]2454                $array_parts_attachments = array();             
[51]2455                $array_parts_attachments['names'] = '';
2456                include("class.imap_attachment.inc.php");
[449]2457                $imap_attachment = new imap_attachment();               
2458               
[51]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;
[449]2475        }       
[69]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'];
[449]2489                        $username = $this->username;
[69]2490                        strtok($email, '@');
2491                        $domain = strtok('@');
2492
[449]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
[69]2503                        // feed dspam
[449]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);
[78]2510                        system($cmd);
[69]2511                }
2512                imap_close($mbox_stream);
2513                return false;
2514        }
[2]2515}
[278]2516?>
Note: See TracBrowser for help on using the repository browser.