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

Revision 628, 93.4 KB checked in by niltonneto, 16 years ago (diff)

Resolve #412

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