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

Revision 1375, 123.6 KB checked in by niltonneto, 15 years ago (diff)

Ticket #620 - Corrigido problema quando pasta "user" é criada no IMAP.

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