source: companies/celepar/expressoMail1_2/inc/class.imap_functions.inc.php @ 763

Revision 763, 98.2 KB checked in by niltonneto, 15 years ago (diff)

Importação inicial do Expresso da Celepar

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