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

Revision 591, 87.0 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #395

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