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

Revision 1012, 105.4 KB checked in by rafaelraymundo, 15 years ago (diff)

Ticket #550 - Escapando comandos que são executados no shell na função "insert_mail".

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