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

Revision 670, 99.4 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #413

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