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

Revision 708, 99.9 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #465

  • 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 = gmdate("d/m/Y",$header->udate);
141                if (date("d/m/Y") == $date_msg)
142                        $head_array['udate'] = gmdate("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               
1395                //new_message_to backs to mailto: pattern
1396                $params['body'] = eregi_replace("<a href=\"javascript:new_message_to\('([^>]+)'\)\">[^>]+</a>","<a href='mailto:\\1'>\\1</a>",$params['body']);
1397               
1398                $toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
1399                $ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
1400                $ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
1401                $subject = $params['input_subject'];
1402                $msg_uid = $params['msg_id'];
1403                $return_receipt = $params['input_return_receipt'];
1404                $is_important = $params['input_important_message'];
1405                $body = $params['body'];
1406                //echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
1407                $attachments = $params['FILES'];
1408                $forwarding_attachments = $params['forwarding_attachments'];
1409                $local_attachments = $params['local_attachments'];
1410                 
1411                $folder =$params['folder'];
1412                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
1413                $folder_name = $params['folder_name'];         
1414                // Fix problem with cyrus delimiter changes.
1415                // Dots in names: enabled/disabled.                             
1416                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1417                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1418                // End Fix.
1419                if ($folder != 'null'){                 
1420                        $mail->SaveMessageInFolder = $folder;
1421                }
1422////////////////////////////////////////////////////////////////////////////////////////////////////
1423                $mail->SMTPDebug = false;
1424                               
1425                $mail->IsSMTP();
1426                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1427                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1428                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1429                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1430                if($fromaddress){
1431                        $mail->Sender = $mail->From;
1432                        $mail->SenderName = $mail->FromName;
1433                        $mail->FromName = $fromaddress[0];
1434                        $mail->From = $fromaddress[1];
1435                }
1436                               
1437                $this->add_recipients("to", $toaddress, &$mail);
1438                $this->add_recipients("cc", $ccaddress, &$mail);
1439                $this->add_recipients("cco", $ccoaddress, &$mail);
1440                $mail->Subject = $subject;
1441                $mail->IsHTML(true);
1442                $mail->Body = $params['body'];
1443
1444////////////////////////////////////////////////////////////////////////////////////////////////////
1445                //      Build CID for embedded Images!!!
1446                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
1447                $cid_imgs = '';
1448                $name_cid_files = array();
1449                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1450                $cid_array = array();
1451                foreach($cid_imgs[6] as $j => $val){
1452                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
1453                        {
1454                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
1455                        }
1456                        $cid = $cid_array[$cid_imgs[4][$j].$val];
1457                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
1458                       
1459                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
1460                                {
1461                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
1462                                        $fileName = "image_".($j).".jpg";
1463                                        $fileCode = "base64";
1464                                        $fileType = "image/jpg";
1465                                }
1466                                else
1467                                {
1468                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
1469                                        $file_description = unserialize(rawurldecode($attach_img));
1470
1471                                        foreach($file_description as $i => $descriptor){                               
1472                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
1473                                        }
1474                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
1475                                        $fileName = $file_description[2];
1476                                        $fileCode = $file_description[4];
1477                                        $fileType = $this->get_file_type($file_description[2]);
1478                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
1479                                }
1480                                $tempDir = ini_get("session.save_path");
1481                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
1482                                $f = fopen($tempDir.'/'.$file,"w");
1483                                fputs($f,$fileContent);
1484                                fclose($f);
1485                                if ($fileContent)
1486                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
1487                                //else
1488                                //      return "Error loading image attachment content";                                               
1489
1490                }
1491////////////////////////////////////////////////////////////////////////////////////////////////////
1492                //      Build Uploading Attachments!!!
1493                if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
1494                {
1495                        $total_uploaded_size = 0;
1496                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
1497                        foreach ($attachments as $attach)
1498                        {
1499                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
1500                                $total_uploaded_size = $total_uploaded_size + $attach['size'];
1501                        }
1502                        if( $total_uploaded_size > $upload_max_filesize)
1503                                return $this->parse_error("message file too big");                     
1504                }                       
1505                else if(($params['is_local_forward']=="1") && (count($local_attachments))) { //Caso seja forward de mensagens locais
1506                       
1507                        $total_uploaded_size = 0;
1508                        $upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;                       
1509                        foreach($local_attachments as $local_attachment) {
1510                                $file_description = unserialize(rawurldecode($local_attachment));
1511                                $tmp = array_values($file_description);
1512                                foreach($file_description as $i => $descriptor){                               
1513                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1514                                }
1515                                $mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
1516                                $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
1517                        }
1518                        if( $total_uploaded_size > $upload_max_filesize)
1519                                return 'false';
1520                }
1521////////////////////////////////////////////////////////////////////////////////////////////////////
1522                //      Build Forwarding Attachments!!!
1523                if (count($forwarding_attachments) > 0)
1524                {
1525                        // Bug fixed for array_search function
1526                        if(count($name_cid_files) > 0) {
1527                                $name_cid_files[count($name_cid_files)] = $name_cid_files[0];
1528                                $name_cid_files[0] = null;
1529                        }                       
1530                       
1531                        foreach($forwarding_attachments as $forwarding_attachment)
1532                        {
1533                                        $file_description = unserialize(rawurldecode($forwarding_attachment));
1534                                        $tmp = array_values($file_description);
1535                                        foreach($file_description as $i => $descriptor){                               
1536                                                $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
1537                                        }
1538                                        $file_description = $tmp;                                       
1539                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
1540                                        $fileName = $file_description[2];
1541                                        if(!array_search(trim($fileName),$name_cid_files)) {
1542                                                $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
1543                                }
1544                        }
1545                }
1546
1547////////////////////////////////////////////////////////////////////////////////////////////////////
1548                // Important message
1549                if($is_important)
1550                        $mail->isImportant();
1551
1552////////////////////////////////////////////////////////////////////////////////////////////////////
1553                // Disposition-Notification-To
1554                if ($return_receipt)
1555                        $mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1556////////////////////////////////////////////////////////////////////////////////////////////////////
1557
1558                $sent = $mail->Send();
1559               
1560                if(!$sent)
1561                {
1562                        return $this->parse_error($mail->ErrorInfo);
1563                }
1564                else
1565                {
1566                        if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
1567                        {
1568                                $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
1569                                $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
1570                                $now = date("d/m/y H:i:s");
1571                                $addrs = $toaddress.$ccaddress.$ccoaddress;
1572                                $sent = trim($sent);                                                                                           
1573                                error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
1574                        }
1575                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
1576                           $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
1577                                $contacts = new dynamic_contacts();
1578                                $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
1579                                return array("success" => true, "new_contacts" => $new_contacts);
1580                        }
1581                        return array("success" => true);
1582                }
1583        }
1584
1585        function add_recipients($recipient_type, $full_address, $mail)
1586        {
1587                $parse_address = imap_rfc822_parse_adrlist($full_address, "");         
1588                foreach ($parse_address as $val)
1589                {
1590                        //echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
1591                        if ($val->mailbox == "INVALID_ADDRESS")
1592                                continue;
1593                       
1594                        if (empty($val->personal))
1595                        {
1596                                switch($recipient_type)
1597                                {
1598                                        case "to":
1599                                                $mail->AddAddress($val->mailbox."@".$val->host);
1600                                                break;
1601                                        case "cc":
1602                                                $mail->AddCC($val->mailbox."@".$val->host);
1603                                                break;
1604                                        case "cco":
1605                                                $mail->AddBCC($val->mailbox."@".$val->host);
1606                                                break;
1607                                }
1608                        }
1609                        else
1610                        {
1611                                switch($recipient_type)
1612                                {
1613                                        case "to":
1614                                                $mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
1615                                                break;
1616                                        case "cc":
1617                                                $mail->AddCC($val->mailbox."@".$val->host, $val->personal);
1618                                                break;
1619                                        case "cco":
1620                                                $mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
1621                                                break;
1622                                }
1623                        }
1624                }
1625                return true;
1626        }
1627       
1628        function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
1629        {
1630                $mbox_stream = $this->open_mbox($msg_folder);                   
1631                $fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);           
1632                if($encoding == 'base64')
1633                        # The function imap_base64 adds a new line
1634                        # at ASCII text, with CRLF line terminators.
1635                        # So is being exchanged for base64_decode.
1636                        #
1637                        #$fileContent = imap_base64($fileContent);
1638                        $fileContent = base64_decode($fileContent);
1639                else if($encoding == 'quoted-printable')
1640                        $fileContent = quoted_printable_decode($fileContent);                           
1641                return $fileContent;
1642        }
1643       
1644        function del_last_caracter($string)
1645        {
1646                $string = substr($string,0,(strlen($string) - 1));
1647                return $string;
1648        }
1649       
1650        function del_last_two_caracters($string)
1651        {
1652                $string = substr($string,0,(strlen($string) - 2));
1653                return $string;
1654        }
1655       
1656        function messages_sort($sort_box_type,$sort_box_reverse, $search_box_type)
1657        {
1658                $sort = array();
1659                $sort_uid = array();
1660               
1661                $num_msgs = imap_num_msg($this->mbox);
1662                for ($i=1; $i<=$num_msgs; $i++)
1663                {
1664                        $header = $this->get_header(imap_uid($this->mbox,$i));
1665                        // List UNSEEN messages.
1666                        if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
1667                                continue;
1668                        }
1669                        // List SEEN messages.
1670                        elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
1671                                continue;
1672                        }
1673                        // List ANSWERED messages.                     
1674                        elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
1675                                continue;                               
1676                        }
1677                        // List FLAGGED messages.                       
1678                        elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
1679                                continue;
1680                        }
1681                                                                       
1682                        if($sort_box_type=='SORTFROM') {
1683                                if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])                             
1684                                        $from = $header->to;
1685                                else
1686                                        $from = $header->from;
1687                               
1688                                $tmp = imap_mime_header_decode($from[0]->personal);                     
1689                               
1690                                if ($tmp[0]->text != "")
1691                                        $sort[$i] = $tmp[0]->text;
1692                                else
1693                                        $sort[$i] = $from[0]->mailbox . "@" . $from[0]->host;
1694                        }
1695                        else if($sort_box_type=='SORTSUBJECT') {
1696                                $sort[$i] = $header->subject;
1697                        }
1698                        else if($sort_box_type=='SORTSIZE') {
1699                                $sort[$i] = $header->Size;
1700                        }
1701                        else {
1702                                $sort[$i] = $header->udate;
1703                        }
1704                       
1705                }
1706               
1707                natcasesort($sort);
1708               
1709                foreach($sort as $index => $header_msg)
1710                {       
1711                        $sort_uid[] = imap_uid($this->mbox, $index);
1712                }
1713               
1714                if ($sort_box_reverse)
1715                        $sort_uid = array_reverse($sort_uid);
1716               
1717                return $sort_uid;
1718
1719        }
1720       
1721        /**
1722         * Deprecated
1723         *
1724         * Replaced for the method messages_sort
1725         */
1726        function imap_sortfrom($sort_box_reverse, $search_box_type)
1727        {
1728                $sortfrom = array();
1729                $sortfrom_uid = array();
1730               
1731                $num_msgs = imap_num_msg($this->mbox);
1732                for ($i=1; $i<=$num_msgs; $i++)
1733                {
1734                        $header = $this->get_header(imap_uid($this->mbox,$i));
1735                        // List UNSEEN messages.
1736                        if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
1737                                continue;
1738                        }
1739                        // List SEEN messages.
1740                        elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
1741                                continue;
1742                        }
1743                        // List ANSWERED messages.                     
1744                        elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
1745                                continue;                               
1746                        }
1747                        // List FLAGGED messages.                       
1748                        elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
1749                                continue;
1750                        }
1751                                               
1752                        if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])                             
1753                                $from = $header->to;
1754                        else
1755                                $from = $header->from;
1756                       
1757                        $tmp = imap_mime_header_decode($from[0]->personal);                     
1758                       
1759                        if ($tmp[0]->text != "")
1760                                $sortfrom[$i] = $tmp[0]->text;
1761                        else
1762                                $sortfrom[$i] = $from[0]->mailbox . "@" . $from[0]->host;
1763                }
1764               
1765                natcasesort($sortfrom);
1766               
1767                foreach($sortfrom as $index => $header_msg)
1768                {       
1769                        $sortfrom_uid[] = imap_uid($this->mbox, $index);
1770                }
1771               
1772                if ($sort_box_reverse)
1773                        $sortfrom_uid = array_reverse($sortfrom_uid);
1774               
1775                return $sortfrom_uid;
1776        }
1777
1778        function move_search_messages($params){         
1779                $params['selected_messages'] = urldecode($params['selected_messages']);
1780                $params['new_folder'] = urldecode($params['new_folder']);
1781                $params['new_folder_name'] = urldecode($params['new_folder_name']);
1782                $sel_msgs = explode(",", $params['selected_messages']);
1783                @reset($sel_msgs);     
1784                $sorted_msgs = array();
1785                foreach($sel_msgs as $idx => $sel_msg) {
1786                        $sel_msg = explode(";", $sel_msg);
1787                         if(array_key_exists($sel_msg[0], $sorted_msgs)){
1788                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
1789                         }     
1790                         else {
1791                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
1792                         }
1793                }
1794                @ksort($sorted_msgs);
1795                $last_return = false;           
1796                foreach($sorted_msgs as $folder => $msgs_number) {                     
1797                        $params['msgs_number'] = $msgs_number;
1798                        $params['folder'] = $folder;   
1799                        if($params['new_folder'] && $folder != $params['new_folder']){
1800                                $last_return = $this -> move_messages($params);                         
1801                        }
1802                        elseif(!$params['new_folder'] || $params['delete'] ){
1803                                $last_return = $this -> delete_msgs($params);
1804                                $last_return['deleted'] = true;
1805                        }
1806                }
1807                return $last_return;
1808        }
1809       
1810        function move_messages($params)
1811        {
1812                $folder = $params['folder'];           
1813                $mbox_stream = $this->open_mbox($folder);               
1814                $newmailbox = ($params['new_folder']);
1815                $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
1816                $new_folder_name = $params['new_folder_name'];
1817                $msgs_number = $params['msgs_number'];
1818                $return = array('msgs_number' => $msgs_number,
1819                                                'folder' => $folder,
1820                                                'new_folder_name' => $new_folder_name,
1821                                                'border_ID' => $params['border_ID'],
1822                                                'status' => true); //Status foi adicionado para validar as permissoes ACL
1823               
1824                //Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
1825        if (substr($folder,0,4) == 'user'){
1826                $acl = $this->getacltouser($folder);
1827                /*
1828                 *   l - lookup (mailbox is visible to LIST/LSUB commands)
1829                 *   r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
1830                 *   s - keep seen/unseen information across sessions (STORE SEEN flag)
1831                 *   w - write (STORE flags other than SEEN and DELETED)
1832                 *   i - insert (perform APPEND, COPY into mailbox)
1833                 *   p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
1834                 *   c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
1835                 *   d - delete (STORE DELETED flag, perform EXPUNGE)
1836                 *   a - administer (perform SETACL)
1837                        */
1838                        if (strpos($acl, "d") === false){
1839                                $return['status'] = false;
1840                                return $return;
1841                        }
1842        }
1843        //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
1844        if (substr($new_folder_name,0,4) == 'user'){
1845                $this->ldap = new ldap_functions();
1846                $tmp_folder_name = explode($this->imap_delimiter, $new_folder_name);
1847                        $return['new_folder_name'] = array_pop($tmp_folder_name);
1848                        if (is_numeric($return['new_folder_name']))
1849                                if( $cn = $this->ldap->uid2cn($return['new_folder_name']))
1850                                        $return['new_folder_name'] = $cn;
1851        }
1852                               
1853                // Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.         
1854                if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
1855                {
1856                        $return['previous_msg'] = $this->get_info_previous_msg($params);
1857                        // Fix problem in unserialize function JS.
1858                        $return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
1859                }
1860               
1861                $mbox_stream = $this->open_mbox($folder);       
1862                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1863                        imap_expunge($mbox_stream);
1864                        if($mbox_stream)
1865                                imap_close($mbox_stream);
1866                        return $return;
1867                }else {
1868                        if(strstr(imap_last_error(),'Over quota')) {                           
1869                                $accountID      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
1870                                $pass           = $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];                                                                       
1871                                $userID         = $_SESSION['phpgw_info']['expressomail']['user']['userid'];                                                           
1872                                $server         = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
1873                                $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()))));
1874                                if(!$mbox)
1875                                        return imap_last_error();
1876                                $quota  = imap_get_quotaroot($mbox_stream, "INBOX");                           
1877                                if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
1878                                        if($mbox_stream)
1879                                                imap_close($mbox_stream);
1880                                        if($mbox)                                                                       
1881                                                imap_close($mbox);
1882                                        return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";                                                               
1883                                }
1884                                if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
1885                                        imap_expunge($mbox_stream);
1886                                        if($mbox_stream)
1887                                                imap_close($mbox_stream);
1888                                        // return to original quota limit.
1889                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
1890                                                if($mbox)
1891                                                        imap_close($mbox);
1892                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
1893                                        }
1894                                        return $return;                                                                                                 
1895                                }
1896                                else {
1897                                        if($mbox_stream)
1898                                                imap_close($mbox_stream);
1899                                        if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
1900                                                if($mbox)
1901                                                        imap_close($mbox);
1902                                                return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";                                                         
1903                                        }
1904                                        return imap_last_error();                               
1905                                }
1906                               
1907                        }
1908                        else {
1909                                if($mbox_stream)
1910                                        imap_close($mbox_stream);
1911                                return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
1912                        }
1913                }               
1914        }
1915       
1916        function save_msg($params)
1917        {
1918               
1919                include_once("class.phpmailer.php");
1920                $mail = new PHPMailer();
1921                include_once("class.db_functions.inc.php");
1922                $toaddress = $params['input_to'];
1923                $ccaddress = $params['input_cc'];
1924                $subject = $params['input_subject'];
1925                $msg_uid = $params['msg_id'];
1926                $body = $params['body'];
1927                $body = str_replace("%nbsp;","&nbsp;",$params['body']);
1928                $body = preg_replace("/\n/"," ",$body);
1929                $body = preg_replace("/\r/","",$body);
1930                $forwarding_attachments = $params['forwarding_attachments'];
1931                $attachments = $params['FILES'];
1932                $return_files = $params['FILES'];
1933                 
1934                $folder = $params['folder'];
1935                $folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");               
1936                // Fix problem with cyrus delimiter changes.
1937                // Dots in names: enabled/disabled.                             
1938                $folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
1939                $folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
1940                // End Fix.
1941                                       
1942                $mail->SaveMessageInFolder = $folder;
1943                $mail->SMTPDebug = false;
1944                                               
1945                $mail->IsSMTP();
1946                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
1947                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
1948                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
1949                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1950               
1951                $mail->Sender = $mail->From;
1952                $mail->SenderName = $mail->FromName;
1953                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
1954                $mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
1955                               
1956                $this->add_recipients("to", $toaddress, &$mail);
1957                $this->add_recipients("cc", $ccaddress, &$mail);
1958                $mail->Subject = $subject;
1959                $mail->IsHTML(true);
1960                $mail->Body = $body;
1961               
1962                //      Build CID for embedded Images!!!
1963                $pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
1964                $cid_imgs = '';
1965                $name_cid_files = array();
1966                preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
1967                $cid_array = array();
1968                foreach($cid_imgs[6] as $j => $val){
1969                                if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
1970                        {
1971                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
1972                        }
1973                        $cid = $cid_array[$cid_imgs[4][$j].$val];
1974                        $mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
1975                       
1976                                if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
1977                                {
1978                                        $fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
1979                                        //prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
1980                                        $fileName = "image_".($j).".jpg";
1981                                        $fileCode = "base64";
1982                                        $fileType = "image/jpg";
1983                                        $file_attached[0] = $cid_imgs[2][$j];
1984                                        $file_attached[1] = $cid_imgs[4][$j];
1985                                        $file_attached[2] = $fileName;
1986                                        $file_attached[3] = $cid_imgs[6][$j];
1987                                        $file_attached[4] = 'base64';
1988                                        $file_attached[5] = strlen($fileContent); //Size of file
1989                                        $return_forward[] = $file_attached;
1990                                }
1991                                else
1992                                {
1993                                        $attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
1994                                        $file_description = unserialize(rawurldecode($attach_img));
1995                                        foreach($file_description as $i => $descriptor){                               
1996                                                $file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
1997                                        }
1998                                        $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
1999                                        $fileName = $file_description[2];
2000                                        $fileCode = $file_description[4];
2001                                        $fileType = $this->get_file_type($file_description[2]);
2002                                        unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
2003                                        if (!empty($file_description))
2004                                        {
2005                                                $file_description[5] = strlen($fileContent); //Size of file
2006                                                $return_forward[] = $file_description;
2007                                        }
2008                                }
2009                                $tempDir = ini_get("session.save_path");
2010                                $file = "cid_image_".base_convert(microtime(), 10, 36).".dat";                                 
2011                                $f = fopen($tempDir.'/'.$file,"w");
2012                                fputs($f,$fileContent);
2013                                fclose($f);
2014                                if ($fileContent)
2015                                        $mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
2016                                //else
2017                                //      return "Error loading image attachment content";                                               
2018
2019                }
2020       
2021        //      Build Forwarding Attachments!!!         
2022                if (count($forwarding_attachments) > 0)
2023                {
2024                        foreach($forwarding_attachments as $forwarding_attachment)
2025                        {
2026                                $file_description = unserialize(rawurldecode($forwarding_attachment));
2027                                $tmp = array_values($file_description);
2028                                foreach($file_description as $i => $descriptor){                               
2029                                        $tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
2030                                }
2031                                $file_description = $tmp;
2032                               
2033                                $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
2034                                $fileName = $file_description[2];
2035                               
2036                                $file_description[5] = strlen($fileContent); //Size of file
2037                                $return_forward[] = $file_description;
2038                       
2039                                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
2040                        }
2041                }
2042               
2043                if ((count($return_forward) > 0) && (count($return_files) > 0))
2044                        $return_files = array_merge_recursive($return_forward,$return_files);
2045                else
2046                        if (count($return_files) < 1)
2047                                $return_files = $return_forward;
2048       
2049                //      Build Uploading Attachments!!!
2050                if (count($attachments))
2051                        foreach ($attachments as $attach)
2052                                $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name                 
2053       
2054       
2055               
2056                if(!empty($mail->AltBody))
2057            $mail->ContentType = "multipart/alternative";
2058
2059        $mail->error_count = 0; // reset errors
2060        $mail->SetMessageType();
2061        $header = $mail->CreateHeader();
2062        $body = $mail->CreateBody();
2063       
2064        if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
2065                {
2066                        $imap_options = '/tls/novalidate-cert';
2067                }
2068                else
2069                {
2070                        $imap_options = '/notls/novalidate-cert';
2071                }
2072                $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
2073                $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
2074                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
2075                $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
2076                $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
2077       
2078                $new_header = str_replace("\n", "\r\n", $header);
2079                $new_body = str_replace("\n", "\r\n", $body);
2080               
2081                $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
2082                $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
2083                $return['msg_no'] = $status->uidnext - 1;
2084                $return['folder_id'] = $folder;
2085               
2086                if($mbox_stream)
2087                        imap_close($mbox_stream);
2088                if (is_array($return_files))             
2089                foreach ($return_files as $index => $_attachment) {
2090                        if (array_key_exists("name",$_attachment)){
2091                                unset($return_files[$index]);
2092                                $return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
2093                        }
2094                        else
2095                        {
2096                                unset($return_files[$index]);
2097                                $return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
2098                        }
2099                }
2100               
2101                $return['files'] = serialize($return_files);
2102                $return["subject"] = $subject;
2103                               
2104                if (!$return['append'])
2105                        $return['append'] = imap_last_error();
2106               
2107                return $return;
2108        }
2109       
2110        function set_messages_flag($params)
2111        {
2112                $folder = $params['folder'];
2113                $msgs_to_set = $params['msgs_to_set'];
2114                $flag = $params['flag'];
2115                $return = array();
2116                $return["msgs_to_set"] = $msgs_to_set;
2117                $return["flag"] = $flag;
2118               
2119                if(!$this->mbox && !is_resource($this->mbox))
2120                        $this->mbox = $this->open_mbox($folder);
2121               
2122                if ($flag == "unseen")
2123                        $return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2124                elseif ($flag == "seen")
2125                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
2126                elseif ($flag == "answered"){
2127                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
2128                        imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
2129                }
2130                elseif ($flag == "forwarded")
2131                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
2132                elseif ($flag == "flagged")
2133                        $return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
2134                elseif ($flag == "unflagged") {
2135                        $flag_importance = false;
2136                        $msgs_number = explode(",",$msgs_to_set);
2137                        $unflagged_msgs = "";
2138                        foreach($msgs_number as $msg_number) {
2139                                preg_match('/importance *: *(.*)\r/i',
2140                                        imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2141                                        ,$importance);         
2142                                if(strtolower($importance[1])=="high" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2143                                        $flag_importance=true;
2144                                }
2145                                else {
2146                                        $unflagged_msgs.=$msg_number.",";
2147                                }                               
2148                        }
2149
2150                        if($unflagged_msgs!="") {
2151                                imap_clearflag_full($this->mbox,substr($unflagged_msgs,0,strlen($unflagged_msgs)-1), "\\Flagged", ST_UID);
2152                                $return["msgs_unflageds"] = substr($unflagged_msgs,0,strlen($unflagged_msgs)-1);
2153                        }
2154                        else {
2155                                $return["msgs_unflageds"] = false;
2156                        }
2157
2158                        if($flag_importance && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2159                                $return["status"] = false;
2160                                $return["msg"] = $this->functions->getLang("At least one of selected message cant be marked as normal");
2161                        }
2162                        else {
2163                                $return["status"] = true;
2164                        }
2165                }
2166               
2167                if($this->mbox && is_resource($this->mbox))
2168                        imap_close($this->mbox);
2169                return $return;
2170        }
2171       
2172        function get_file_type($file_name)
2173        {
2174                $file_name = strtolower($file_name);
2175                $strFileType = strrev(substr(strrev($file_name),0,4));
2176                if ($strFileType == ".asf")
2177                        return "video/x-ms-asf";
2178                if ($strFileType == ".avi")
2179                        return "video/avi";
2180                if ($strFileType == ".doc")
2181                        return "application/msword";
2182                if ($strFileType == ".zip")
2183                        return "application/zip";
2184                if ($strFileType == ".xls")
2185                        return "application/vnd.ms-excel";
2186                if ($strFileType == ".gif")
2187                        return "image/gif";
2188                if ($strFileType == ".jpg" || $strFileType == "jpeg")
2189                        return "image/jpeg";
2190                if ($strFileType == ".png")
2191                        return "image/png";
2192                if ($strFileType == ".wav")
2193                        return "audio/wav";
2194                if ($strFileType == ".mp3")
2195                        return "audio/mpeg3";
2196                if ($strFileType == ".mpg" || $strFileType == "mpeg")
2197                        return "video/mpeg";
2198                if ($strFileType == ".rtf")
2199                        return "application/rtf";
2200                if ($strFileType == ".htm" || $strFileType == "html")
2201                        return "text/html";
2202                if ($strFileType == ".xml")
2203                        return "text/xml";
2204                if ($strFileType == ".xsl")
2205                        return "text/xsl";
2206                if ($strFileType == ".css")
2207                        return "text/css";
2208                if ($strFileType == ".php")
2209                        return "text/php";
2210                if ($strFileType == ".asp")
2211                        return "text/asp";
2212                if ($strFileType == ".pdf")
2213                        return "application/pdf";
2214                if ($strFileType == ".txt")
2215                        return "text/plain";
2216                if ($strFileType == ".wmv")
2217                        return "video/x-ms-wmv";
2218                if ($strFileType == ".sxc")
2219                        return "application/vnd.sun.xml.calc";
2220                if ($strFileType == ".stc")
2221                        return "application/vnd.sun.xml.calc.template";
2222                if ($strFileType == ".sxd")
2223                        return "application/vnd.sun.xml.draw";
2224                if ($strFileType == ".std")
2225                        return "application/vnd.sun.xml.draw.template";
2226                if ($strFileType == ".sxi")
2227                        return "application/vnd.sun.xml.impress";
2228                if ($strFileType == ".sti")
2229                        return "application/vnd.sun.xml.impress.template";
2230                if ($strFileType == ".sxm")
2231                        return "application/vnd.sun.xml.math";
2232                if ($strFileType == ".sxw")
2233                        return "application/vnd.sun.xml.writer";
2234                if ($strFileType == ".sxq")
2235                        return "application/vnd.sun.xml.writer.global";
2236                if ($strFileType == ".stw")
2237                        return "application/vnd.sun.xml.writer.template";
2238               
2239               
2240                return "application/octet-stream";             
2241        }
2242       
2243        function htmlspecialchars_encode($str)
2244        {
2245                return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
2246        }
2247        function htmlspecialchars_decode($str)
2248        {
2249                return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
2250        }
2251       
2252        function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse){
2253               
2254                if(!$this->mbox || !is_resource($this->mbox)){
2255                        $this->mbox = $this->open_mbox($folder);
2256               
2257                }
2258
2259                return $this->messages_sort($sort_box_type,$sort_box_reverse, $search_box_type);
2260                /*switch($sort_box_type){
2261                        case 'SORTFROM':
2262                                return $this->imap_sortfrom($sort_box_reverse, $search_box_type);                               
2263                        case 'SORTSUBJECT':
2264                                return imap_sort($this->mbox, SORTSUBJECT, $sort_box_reverse, SE_UID, $search_box_type);                               
2265                        case 'SORTSIZE':
2266                                return imap_sort($this->mbox, SORTSIZE, $sort_box_reverse, SE_UID, $search_box_type);                           
2267                        default:
2268                                return imap_sort($this->mbox, SORTARRIVAL, $sort_box_reverse, SE_UID, $search_box_type);                                               
2269                }*/
2270        }       
2271       
2272        function get_info_next_msg($params)
2273        {
2274                $msg_number = $params['msg_number'];
2275                $folder = $params['msg_folder'];
2276                $sort_box_type = $params['sort_box_type'];
2277                $sort_box_reverse = $params['sort_box_reverse'];
2278                $reuse_border = $params['reuse_border'];
2279                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2280                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);                             
2281               
2282                $success = false;
2283                if (is_array($sort_array_msg))
2284                {
2285                        foreach ($sort_array_msg as $i => $value){
2286                                if ($value == $msg_number)
2287                                {
2288                                        $success = true;
2289                                        break;
2290                                }
2291                        }
2292                }
2293
2294                if (! $success || $i >= sizeof($sort_array_msg)-1)
2295                {
2296                        $params['status'] = 'false';
2297                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2298                        return $params;
2299                }
2300               
2301                $params = array();
2302                $params['msg_number'] = $sort_array_msg[($i+1)];
2303                $params['msg_folder'] = $folder;
2304               
2305                $return = $this->get_info_msg($params);         
2306                $return["reuse_border"] = $reuse_border;
2307                return $return;
2308        }
2309
2310        function get_info_previous_msg($params)
2311        {
2312                $msg_number = $params['msgs_number'];
2313                $folder = $params['folder'];
2314                $sort_box_type = $params['sort_box_type'];
2315                $sort_box_reverse = $params['sort_box_reverse'];
2316                $reuse_border = $params['reuse_border'];
2317                $search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
2318                $sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
2319               
2320                $success = false;
2321                if (is_array($sort_array_msg))
2322                {
2323                        foreach ($sort_array_msg as $i => $value){
2324                                if ($value == $msg_number)
2325                                {
2326                                        $success = true;
2327                                        break;
2328                                }
2329                        }
2330                }
2331                if (! $success || $i == 0)
2332                {
2333                        $params['status'] = 'false';
2334                        $params['command_to_exec'] = "delete_border('". $reuse_border ."');";
2335                        return $params;
2336                }
2337               
2338                $params = array();
2339                $params['msg_number'] = $sort_array_msg[($i-1)];
2340                $params['msg_folder'] = $folder;
2341               
2342                $return = $this->get_info_msg($params);
2343                $return["reuse_border"] = $reuse_border;
2344                return $return;
2345        }
2346       
2347        // This function updates the values: quota, paging and new messages menu.
2348        function get_menu_values($params){
2349                $return_array = array();
2350                $return_array = $this->get_quota($params);
2351               
2352                $mbox_stream = $this->open_mbox($params['folder']);
2353                $return_array['num_msgs'] = imap_num_msg($mbox_stream);         
2354                if($mbox_stream)
2355                        imap_close($mbox_stream);
2356                               
2357                return $return_array;
2358        }
2359       
2360        function get_quota($params){
2361                // folder_id = user/{uid} for shared folders
2362                if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
2363                        $array_folder =  explode($this->imap_delimiter,$params['folder_id']);
2364                        $folder_id = "user".$this->imap_delimiter.$array_folder[1];             
2365                }
2366                // folder_id = INBOX for inbox folders
2367                else
2368                        $folder_id = "INBOX";
2369               
2370                if(!$this->mbox)
2371                        $this->mbox = $this->open_mbox();
2372
2373                $quota = imap_get_quotaroot($this->mbox, $folder_id);
2374                if($this->mbox && is_resource($this->mbox))
2375                        imap_close($this->mbox);
2376                       
2377                if (!$quota){
2378                        return array(
2379                                'quota_percent' => 0,
2380                                'quota_used' => 0,
2381                                'quota_limit' =>  0
2382                        );
2383                }
2384               
2385                if(count($quota) && $quota['limit']) {
2386                        $quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
2387                        $quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
2388                        if($quota_used >= $quota_limit)
2389                        {
2390                                $quotaPercent = 100;
2391                        }
2392                        else
2393                        {
2394                        $quotaPercent = ($quota_used / $quota_limit)*100;
2395                        $quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
2396                        }
2397                        return array(
2398                                'quota_percent' => floor($quotaPercent),
2399                                'quota_used' => floor($quota_used),
2400                                'quota_limit' =>  floor($quota_limit)
2401                        );
2402                }
2403                else
2404                        return array();
2405        }
2406       
2407        function send_notification($params){
2408                require_once("class.phpmailer.php");
2409                $mail = new PHPMailer();
2410                 
2411                $toaddress = $params['notificationto'];
2412               
2413                $subject = 'Confirmação de leitura: ' . $params['subject'];
2414                $body = 'Sua mensagem: ' . $params['subject'] . '<br>';
2415                $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");
2416                $mail->SMTPDebug = false;
2417                $mail->IsSMTP();
2418                $mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
2419                $mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
2420                $mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2421                $mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
2422                $mail->AddAddress($toaddress);
2423                $mail->Subject = $this->htmlspecialchars_decode($subject);
2424
2425                $mail->IsHTML(true);
2426                $mail->Body = $body;
2427               
2428                if(!$mail->Send()){
2429                        return $mail->ErrorInfo;
2430                }
2431                else
2432                        return true;
2433        }
2434       
2435        function empty_trash()
2436        {
2437                $folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
2438                $mbox_stream = $this->open_mbox($folder);
2439                $return = imap_delete($mbox_stream,'1:*');
2440                if($mbox_stream)
2441                        imap_close($mbox_stream, CL_EXPUNGE);
2442                return $return;
2443        }
2444       
2445        function search($params)
2446        {
2447                include("class.imap_attachment.inc.php");
2448                $imap_attachment = new imap_attachment();                               
2449                $criteria = $params['criteria'];
2450                $return = array();
2451                $folders = $this->get_folders_list();
2452               
2453                $j = 0;
2454                foreach($folders as $folder)
2455                {
2456                        $mbox_stream = $this->open_mbox($folder);
2457                        $messages = imap_search($mbox_stream, $criteria, SE_UID);
2458                       
2459                        if ($messages == '')
2460                                continue;
2461               
2462                        $i = 0;
2463                        $return[$j] = array();
2464                        $return[$j]['folder_name'] = $folder['name'];
2465                       
2466                        foreach($messages as $msg_number)
2467                        {
2468                                $header = $this->get_header($msg_number);
2469                                if (!is_object($header))
2470                                        return false;
2471                               
2472                                $return[$j][$i]['msg_folder']   = $folder['name'];
2473                                $return[$j][$i]['msg_number']   = $msg_number;
2474                                $return[$j][$i]['Recent']               = $header->Recent;
2475                                $return[$j][$i]['Unseen']               = $header->Unseen;
2476                                $return[$j][$i]['Answered']     = $header->Answered;
2477                                $return[$j][$i]['Deleted']              = $header->Deleted;
2478                                $return[$j][$i]['Draft']                = $header->Draft;
2479                                $return[$j][$i]['Flagged']              = $header->Flagged;
2480       
2481                                $date_msg = gmdate("d/m/Y",$header->udate);
2482                                if (gmdate("d/m/Y") == $date_msg)
2483                                        $return[$j][$i]['udate'] = gmdate("H:i",$header->udate);
2484                                else
2485                                        $return[$j][$i]['udate'] = $date_msg;
2486                       
2487                                $fromaddress = imap_mime_header_decode($header->fromaddress);
2488                                $return[$j][$i]['fromaddress'] = '';
2489                                foreach ($fromaddress as $tmp)
2490                                        $return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
2491                       
2492                                $from = $header->from;
2493                                $return[$j][$i]['from'] = array();
2494                                $tmp = imap_mime_header_decode($from[0]->personal);
2495                                $return[$j][$i]['from']['name'] = $tmp[0]->text;
2496                                $return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
2497                                $return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
2498
2499                                $to = $header->to;
2500                                $return[$j][$i]['to'] = array();
2501                                $tmp = imap_mime_header_decode($to[0]->personal);
2502                                $return[$j][$i]['to']['name'] = $tmp[0]->text;
2503                                $return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
2504                                $return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
2505
2506                                $subject = imap_mime_header_decode($header->fetchsubject);
2507                                $return[$j][$i]['subject'] = '';
2508                                foreach ($subject as $tmp)
2509                                        $return[$j][$i]['subject'] .= $tmp->text;
2510
2511                                $return[$j][$i]['Size'] = $header->Size;
2512                                $return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
2513                       
2514                                $return[$j][$i]['attachment'] = array();
2515                                $return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
2516                                               
2517                                $i++;
2518                        }
2519                        $j++;
2520                        if($mbox_stream)
2521                                imap_close($mbox_stream);
2522                }
2523       
2524                return $return;
2525        }
2526       
2527        function delete_and_show_previous_message($params)
2528        {
2529                $return = $this->get_info_previous_msg($params);
2530               
2531                $params_tmp1 = array();
2532                $params_tmp1['msgs_to_delete'] = $params['msg_number'];
2533                $params_tmp1['folder'] = $params['msg_folder'];
2534                $return_tmp1 = $this->delete_msg($params_tmp1);
2535               
2536                $return['msg_number_deleted'] = $return_tmp1;
2537               
2538                return $return;
2539        }
2540               
2541       
2542        function automatic_trash_cleanness($params)
2543        {
2544                $before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
2545                $criteria =  'BEFORE "'.$before_date.'"';
2546                $mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
2547                $messages = imap_search($mbox_stream, $criteria, SE_UID);
2548                if (is_array($messages)){
2549                        foreach ($messages as $msg_number){
2550                                imap_delete($mbox_stream, $msg_number, FT_UID);
2551                        }
2552                }
2553                if($mbox_stream)
2554                        imap_close($mbox_stream, CL_EXPUNGE);
2555                return $messages;
2556        }
2557//      Fix the search problem with special characters!!!!
2558        function remove_accents($string) {
2559                return strtr($string,
2560                "?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ",
2561                "SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
2562        }
2563
2564        function search_msg($params = ''){             
2565                $retorno = "";
2566                $mbox_stream = "";
2567                if(strpos($params['condition'],"#")===false) { //local messages
2568                        $search=false;
2569                }
2570                else {
2571                        $search = explode(",",$params['condition']);                   
2572                }
2573
2574                if($search){
2575                        $search_criteria = '';
2576                        foreach($search as $tmp)
2577                        {
2578                                $tmp1 = explode("##",$tmp);
2579                                $name_box = $tmp1[0];
2580                                unset($filter);
2581                                foreach($tmp1 as $index => $criteria)
2582                                {
2583                                        if ($index != 0 && strlen($criteria) != 0)
2584                                        {
2585                                                $filter_array = explode("<=>",rawurldecode($criteria));
2586                                                $filter .= " ".$filter_array[0];
2587                                                $filter .= '"'.$filter_array[1].'"';
2588                                        }
2589                                }               
2590                                $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
2591                                $filter = $this->remove_accents($filter);
2592                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
2593                                $folder_name = explode($this->imap_delimiter,$name_box);
2594                                if (is_numeric($folder_name[1])) {
2595                                        $this->ldap = new ldap_functions();
2596                                        if ($cn = $this->ldap->uid2cn($folder_name[1])) {
2597                                                $folder_name[1] = $cn;
2598                                        }
2599                                }
2600                                $folder_name = implode($this->imap_delimiter,$folder_name);
2601                               
2602                                if(!is_resource($mbox_stream))
2603                                        $mbox_stream = $this->open_mbox($name_box);
2604                                else
2605                                        imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
2606                       
2607                                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search   
2608                               
2609                                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
2610                                        foreach($all_criterias as $criteria_fixed)
2611                                        {
2612                                                $_filter = $criteria_fixed . substr($filter,4);
2613                                       
2614                                                $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
2615                                               
2616                                                if($search_criteria && count($search_criteria) < 50)
2617                                                {
2618                                                        foreach($search_criteria as $new_search){
2619                                                                $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");
2620                                                                if(!@strstr($retorno,$m_token))
2621                                                                        $retorno .= $m_token;
2622                                                        }
2623                                                }                                               
2624                                                else if(count($search_criteria) >= 50)                                                 
2625                                                        return "many results";                                         
2626                                        }
2627                                }
2628                                else {
2629                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
2630                                        if( is_array( $search_criteria) )
2631                                        {
2632                                                foreach($search_criteria as $new_search)
2633                                                        $retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
2634                                        }
2635                                }
2636                        }
2637                }
2638                if($mbox_stream)
2639                        imap_close($mbox_stream);               
2640                                               
2641                return $retorno ? $retorno : "none";
2642        }
2643       
2644        function get_msg($uid_msg,$name_box, $mbox_stream )
2645        {
2646                $header = $this->get_header($uid_msg);         
2647                $flag = $header->Unseen.$header->Recent.$header->Flagged.$header->Draft;
2648                $subject = $this->decode_string($header->fetchsubject);
2649                $from = $header->from[0]->mailbox;
2650                if($header->from[0]->personal != "")
2651                        $from = $header->from[0]->personal;
2652                $ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size) ."--". $flag;
2653                return $ret_msg;                   
2654        }       
2655       
2656        function size_msg($size){
2657                $var = floor($size/1024);
2658                if($var >= 1){
2659                        return $var." kb";     
2660                }else{
2661                        return $size ." b";     
2662                }
2663        }
2664
2665        function ob_array($the_object)
2666        {
2667           $the_array=array();
2668           if(!is_scalar($the_object))
2669           {
2670               foreach($the_object as $id => $object)
2671               {
2672                   if(is_scalar($object))
2673                   {
2674                       $the_array[$id]=$object;
2675                   }
2676                   else
2677                   {
2678                       $the_array[$id]=$this->ob_array($object);
2679                   }
2680               }
2681               return $the_array;
2682           }
2683           else
2684           {
2685               return $the_object;
2686           }
2687        }
2688       
2689        function getacl()
2690        {
2691                $this->ldap = new ldap_functions();
2692               
2693                $return = array();
2694                $mbox_stream = $this->open_mbox();     
2695                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
2696               
2697                $i = 0;
2698                foreach ($mbox_acl as $user => $acl)
2699                {
2700                        if ($user != $this->username)
2701                        {
2702                                $return[$i]['uid'] = $user;
2703                                $return[$i]['cn'] = $this->ldap->uid2cn($user);
2704                        }
2705                        $i++;
2706                }
2707                return $return;
2708        }
2709       
2710        function setacl($params)
2711        {
2712                $old_users = $this->getacl();
2713                if (!count($old_users))
2714                        $old_users = array();
2715               
2716                $tmp_array = array();
2717                foreach ($old_users as $index => $user_info)
2718                {
2719                        $tmp_array[$index] = $user_info['uid'];
2720                }
2721                $old_users = $tmp_array;
2722               
2723                $users = unserialize($params['users']);
2724                if (!count($users))
2725                        $users = array();
2726               
2727                //$add_share = array_diff($users, $old_users);
2728                $remove_share = array_diff($old_users, $users);
2729
2730                $mbox_stream = $this->open_mbox();
2731
2732                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2733                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
2734
2735                /*if (count($add_share))
2736                {
2737                        foreach ($add_share as $index=>$uid)
2738                        {
2739                        if (is_array($mailboxes_list))
2740                        {
2741                        foreach ($mailboxes_list as $key => $val)
2742                        {
2743                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
2744                                                imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
2745                        }
2746                        }
2747                        }
2748                }*/
2749               
2750                if (count($remove_share))
2751                {
2752                        foreach ($remove_share as $index=>$uid)
2753                        {
2754                        if (is_array($mailboxes_list))
2755                        {
2756                        foreach ($mailboxes_list as $key => $val)
2757                        {
2758                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
2759                                                imap_setacl ($mbox_stream, $folder, "$uid", "");
2760                        }
2761                        }
2762                        }       
2763                }
2764               
2765                return true;
2766        }
2767       
2768        function getaclfromuser($params)
2769        {
2770                $useracl = $params['user'];
2771               
2772                $return = array();
2773                $return[$useracl] = 'false';
2774                $mbox_stream = $this->open_mbox();     
2775                $mbox_acl = imap_getacl($mbox_stream, 'INBOX');
2776               
2777                foreach ($mbox_acl as $user => $acl)
2778                {
2779                        if (($user != $this->username) && ($user == $useracl))
2780                        {
2781                                $return[$user] = $acl;
2782                        }
2783                }
2784                return $return;
2785        }
2786
2787        function getacltouser($user)
2788        {
2789                $return = array();
2790                $mbox_stream = $this->open_mbox();
2791                //Alterado, antes era 'imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
2792                //Afim de tratar as pastas compartilhadas, verificandos as permissoes de operacao sobre as mesmas
2793                //No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
2794                if(substr($user,0,4) != 'user')
2795                $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
2796                else
2797                  $mbox_acl = imap_getacl($mbox_stream, $user);
2798                return $mbox_acl[$this->username];
2799        }
2800       
2801
2802        function setaclfromuser($params)
2803        {
2804                $user = $params['user'];
2805                $acl = $params['acl'];
2806               
2807                $mbox_stream = $this->open_mbox();
2808
2809                $serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
2810                $mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
2811
2812                if (is_array($mailboxes_list))
2813                {
2814                        foreach ($mailboxes_list as $key => $val)
2815                        {
2816                                $folder = str_replace($serverString, "", imap_utf7_encode($val->name));
2817                                $folder = str_replace("&-", "&", $folder);
2818                                if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
2819                                {
2820                                        $return = imap_last_error();
2821                                }
2822                        }
2823                }
2824                if (isset($return))
2825                        return $return;
2826                else
2827                        return true;
2828        }
2829       
2830        function download_attachment($msg,$msgno)
2831        {
2832                $array_parts_attachments = array();             
2833                $array_parts_attachments['names'] = '';
2834                include_once("class.imap_attachment.inc.php");
2835                $imap_attachment = new imap_attachment();               
2836               
2837                if (count($msg->fname[$msgno]) > 0)
2838                {
2839                        $i = 0;
2840                        foreach ($msg->fname[$msgno] as $index=>$fname)
2841                        {
2842                                $array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
2843                                $array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($fname);
2844                                $array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
2845                                $array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
2846                                $array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
2847                                $array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
2848                                $i++;
2849                        }
2850                }
2851                $array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
2852                return $array_parts_attachments;
2853        }       
2854
2855        function spam($params)
2856        {
2857                $is_spam = $params['spam'];
2858                $folder = $params['folder'];
2859                $mbox_stream = $this->open_mbox($folder);
2860                $msgs_number = explode(',',$params['msgs_number']);
2861
2862                foreach($msgs_number as $msg_number) {
2863                        $header = imap_fetchheader($mbox_stream, imap_msgno($mbox_stream, $msg_number));
2864                        $body = imap_body($mbox_stream, imap_msgno($mbox_stream, $msg_number));
2865                        $msg = $header . $body;
2866                        $email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
2867                        $username = $this->username;
2868                        strtok($email, '@');
2869                        $domain = strtok('@');
2870
2871                        //Encontrar a assinatura do dspam no cabecalho
2872                        $v = explode("\r\n", $header);
2873                        foreach ($v as $linha){
2874                                if (eregi("^X-DSPAM-Signature", $linha)) {
2875                                       
2876                                        $args = explode(" ",$linha);
2877                                        $signature = $args[1];
2878                                }
2879                        }
2880
2881                        // feed dspam
2882                        switch($is_spam){
2883                                case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
2884                                case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
2885                        }
2886                        $tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##');
2887                        $cmd = str_replace($tags,array($email,$username,$domain,$signature),$cmd);
2888                        system($cmd);
2889                }
2890                imap_close($mbox_stream);
2891                return false;
2892        }
2893        function get_header($msg_number){
2894                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
2895                if (!is_object($header))
2896                        return false;
2897                // Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
2898                $pdate = date_parse($header->MailDate);
2899                $header->udate +=  $pdate['zone']*(-60);
2900               
2901                if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
2902                        $flag = preg_match('/importance *: *(.*)\r/i',
2903                                                imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
2904                                                ,$importance);         
2905                        $header->Flagged = $flag==0?false:strtolower($importance[1])=="high"?"F":false;
2906                }
2907               
2908                return $header;
2909        }
2910}
2911?>
Note: See TracBrowser for help on using the repository browser.