source: trunk/expressoMail1_2/inc/class.exporteml.inc.php @ 8135

Revision 8135, 29.0 KB checked in by thiago, 11 years ago (diff)

Ticket #3428 - Retirado alguns códigos que não estão em uso.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2/***************************************************************************************\
3* Export EML Format Message Mail                                                                                                                *
4* Written by Nilton Neto (Celepar) <niltonneto@celepar.pr.gov.br>                                               *
5* ------------------------------------------------------------------------------------  *
6*  This program is free software; you can redistribute it and/or modify it                              *
7*   under the terms of the GNU General Public License as published by the                               *
8*  Free Software Foundation; either version 2 of the License, or (at your                               *
9*  option) any later version.                                                                                                                   *
10\****************************************************************************************/
11// BEGIN CLASS
12class ExportEml
13{
14        var $msg;
15        var $folder;
16        var $mbox_stream;
17        var $tempDir;
18
19        function ExportEml() {
20           
21                //TODO: modificar o caminho hardcodificado '/tmp' para o definido na configuracao do expresso
22                //$this->tempDir = $GLOBALS['phpgw_info']['server']['temp_dir'];
23                $this->tempDir = '/tmp';
24        }
25       
26        function connectImap(){
27       
28                $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
29                $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
30                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
31                $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
32               
33                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
34                {
35                        $imap_options = '/tls/novalidate-cert';
36                }
37                else
38                {
39                        $imap_options = '/notls/novalidate-cert';
40                }
41                $this->mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$this->folder, $username, $password);
42        }
43       
44        //export message to EML Format
45        function parseEml($header, $body)       
46        {               
47                $sEmailHeader = $header;
48                $sEmailBody = $body;
49                $sEMail = $sEmailHeader . "\r\n\r\n" . $sEmailBody;             
50                return $sEMail;
51        }
52
53        // create EML File.
54        // Funcao alterada para tratar a exportacao
55        // de mensagens arquivadas localmente.
56        // Rommel Cysne (rommel.cysne@serpro.gov.br)
57        // em 17/12/2008.
58
59    function createFileEml_by_localFolder($sEMLData, $tempDir, $file){
60
61        $file = "{$file}.eml";
62
63        $f = fopen($tempDir.'/'.$file,"w");
64        if(!$f)
65            return False;
66
67        fputs($f,$sEMLData);
68        fclose($f);
69       
70        return $file;
71    }
72
73        function createFileEml($sEMLData, $tempDir, $id, $subject=false, $i=false)
74    {
75        if($id)
76        {
77            $header    = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $id), 80, 255);
78            $subject = $this->decode_subject($header->fetchsubject);
79                       
80            if (strlen($subject) > 60)
81                $subject = substr($subject, 0, 59);
82 
83                        //$subject = preg_replace('/\//', '\'', $subject);
84                        $from = "áàâãäéèêëíìîïóòôõöúùûüç?\"!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº° .ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ";
85                        $to =   "aaaaaeeeeiiiiooooouuuuc______________________________________________AAAAAEEEEIIIIOOOOOUUUUC";
86                        $subject = strtr($subject,$from,$to);
87
88                        $subject = preg_replace('/[^a-zA-Z0-9_]/i', '_', $subject);
89                        $file = $subject."_".$id.".eml";
90                } else{
91                        // Se mensagem for arquivada localmente, $subject (assunto da mensagem)
92                        // sera passado para compor o nome do arquivo .eml;
93
94                        if($subject && $i){
95                                $from = "áàâãäéèêëíìîïóòôõöúùûüç?\"!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº° .ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ";
96                                $to =   "aaaaaeeeeiiiiooooouuuuc______________________________________________AAAAAEEEEIIIIOOOOOUUUUC";
97                                $subject = strtr($subject,$from,$to);
98
99                                $subject = preg_replace('/[^a-zA-Z0-9_]/i', '_', $subject);
100
101                                // é necessário que a sessão faça parte do nome do arquivo para que o mesmo não venha vazio o.O
102                                $file = $subject."_".$i."_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".eml"; 
103                        } else{
104                                $file = "email_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".eml";
105                }   
106        }
107       
108        $f = fopen($tempDir.'/'.$file,"w");
109        if(!$f)
110            return False;
111       
112        fputs($f,$sEMLData);
113        fclose($f);
114       
115        return $file;
116    }
117
118        function createFileZip($files, $tempDir){       
119
120                $tmp_zip_filename = "email_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".zip";
121                if (!empty($files))
122                {
123                    if (is_array($files))
124                    {
125                        $files_count = count($files);
126                        for ($i=0; $i < $files_count; ++$i)
127                        {
128                            $files[$i] = escapeshellarg($files[$i]);
129                        }
130                        $files = implode(' ', $files);
131                    }
132                    else
133                    {
134                        $files = escapeshellcmd($files);
135                    }
136                }
137
138
139$command = "cd " . escapeshellarg($tempDir) . " && nice zip -m9 " . escapeshellarg($tmp_zip_filename) . " " .  $files;
140
141
142                if(!exec($command)) {
143                        $command = "cd " .  escapeshellarg($tempDir) . " && rm ".$files." ". escapeshellarg($tmp_zip_filename);
144                        exec($command);
145                        return null;
146                }
147
148                return $tmp_zip_filename;
149                               
150        }
151
152
153function export_all($params){
154
155                $this->folder = $params['folder'];
156                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
157                $fileNames = "";
158                $tempDir = $this->tempDir;
159                $this->connectImap();
160               
161                $msgs = imap_search($this->mbox_stream,"ALL",SE_UID);
162
163                if($msgs){
164                        foreach($msgs as $nMsgs){
165
166                                $header         = $this-> getHeader($nMsgs);                                                             
167                                $body           = $this-> getBody($nMsgs);             
168
169                                $sEMLData       = $this -> parseEml($header, $body);
170                                $fileName       = $this -> CreateFileEml($sEMLData, $tempDir,$nMsgs);
171                                if(!$fileName)  {
172                                        $error = True;                                 
173                                        break;
174                                }
175                                else
176                                        $fileNames .= "\"".$fileName."\" ";                     
177                               
178                        }
179                       
180                        imap_close($this->mbox_stream);
181                       
182                        $nameFileZip = 'False';                 
183                        if($fileNames && !$error) {                     
184                                $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
185                                if($nameFileZip)                       
186                                        $file = $tempDir.'/'.$nameFileZip;
187                                else {
188                                        $file = false;
189                                }                                                               
190                        }
191                        else
192                                $file = false;
193                }else{
194                        $file["empty_folder"] = true;
195                }
196                return $file;
197               
198        }
199
200        // Funcao alterada para tratar a exportacao
201        // de mensagens arquivadas localmente.
202        // Rommel Cysne (rommel.cysne@serpro.gov.br)
203        // em 17/12/2008.
204        // 
205        // Funcao alterada para que, quando houver 
206        // apenas um arquivo a ser exportado,
207        // não seja criado em zip
208        //
209        // Funcao altarada para exportar uma ou
210        // varia mensagens de um pesquisa
211
212        function makeAll($params) {
213        //Exporta menssagens selecionadas na pesquisa
214        if($params['folder'] === 'false'){
215               
216                $this->folder = $params['folder'];
217                $error = False;
218                $fileNames = "";
219               
220                $sel_msgs = explode(",", $params['msgs_to_export']);
221                @reset($sel_msgs);
222                $sorted_msgs = array();
223                foreach($sel_msgs as $idx => $sel_msg) {
224                        $sel_msg = explode(";", $sel_msg);
225                        if(array_key_exists($sel_msg[0], $sorted_msgs)){
226                                $sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
227                        }
228                        else {
229                                $sorted_msgs[$sel_msg[0]] = $sel_msg[1];
230                        }
231                }
232                       
233                unset($sorted_msgs['']);                       
234
235               
236                // Verifica se as n mensagens selecionadas
237                // se encontram em um mesmo folder
238                if (count($sorted_msgs)==1){
239                        $array_names_keys = array_keys($sorted_msgs);
240                        $this->folder = mb_convert_encoding($array_names_keys[0], "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
241                        $msg_number = explode(',', $sorted_msgs[$array_names_keys[0]]);
242                        $tempDir = $this->tempDir;
243                        $this->connectImap();
244                       
245                        //verifica se apenas uma mensagem foi selecionada e exportar em .eml                   
246                        if(count($msg_number) == 1){
247                                $header         = $this->getHeader($msg_number[0]);
248                                $body           = $this->getBody($msg_number[0]);                       
249                                $sEMLData       = $this->parseEml($header, $body);                     
250                                $fileName       = $this->CreateFileEml($sEMLData, $tempDir, $msg_number[0]."_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]);
251               
252                                $header    = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number[0]), 80, 255);
253                $subject = $this->decode_subject(html_entity_decode($header->fetchsubject));
254
255                                imap_close($this->mbox_stream);
256                                if (!$fileName) {
257                                        return false;
258                                }else{
259                                        $return = array();
260                                        $return[] = $tempDir.'/'.$fileName;
261                                        $return[] = $subject;
262                                        return $return;
263                                }
264                        }
265                       
266                        //cria um .zip com as mensagens selecionadas
267            $msg_number_count = count($msg_number);
268                        for($i = 0; $i < $msg_number_count; ++$i)
269                        {
270                                $header         = $this-> getHeader($msg_number[$i]);                                                                                   
271                                $body           = $this-> getBody($msg_number[$i]);                     
272                                $sEMLData       = $this -> parseEml($header, $body);                   
273                                $fileName       = $this -> CreateFileEml($sEMLData, $tempDir, $msg_number[$i]);
274
275                                if(!$fileName)
276                                {
277                                        $error = True;                                 
278                                        break;
279                                } else{
280                                        $fileNames .= "\"".$fileName."\" ";                     
281                                }
282                        }
283                        imap_close($this->mbox_stream);
284
285                        $nameFileZip = 'False';                 
286                        if($fileNames && !$error)
287                        {
288                                $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
289                                if($nameFileZip)
290                                {               
291                                        $file = $tempDir.'/'.$nameFileZip;
292                                } else {
293                                        $file = false;
294                                }                                                               
295                        }
296                        else
297                        {
298                                $file = false;
299                        }
300
301                        return $file;                   
302               
303                //exporta mensagens de diferentes pastas
304                }else{
305                        $array_names_keys = array_keys($sorted_msgs);
306
307            $array_names_keys_count = count($array_names_keys);
308                        for($i = 0; $i < $array_names_keys_count; ++$i){
309                                $this->folder = mb_convert_encoding($array_names_keys[$i], "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
310                                $msg_number = explode(',', $sorted_msgs[$array_names_keys[$i]]);
311                                $tempDir = $this->tempDir;
312                                $this->connectImap();
313
314                $msg_number_count = count($msg_number);
315                                for($j = 0; $j < $msg_number_count; ++$j)
316                                {
317                                        $header         = $this-> getHeader($msg_number[$j]);                                                                                   
318                                        $body           = $this-> getBody($msg_number[$j]);                     
319                                        $sEMLData       = $this -> parseEml($header, $body);                   
320                                        $fileName       = $this -> CreateFileEml($sEMLData, $tempDir, $msg_number[$j]);
321
322                                        if(!$fileName)
323                                        {
324                                                $error = True;                                 
325                                                break;
326                                        } else{
327                                                $fileNames .= "\"".$fileName."\" ";                     
328                                        }
329                                }
330                                imap_close($this->mbox_stream);
331                        }
332                        $nameFileZip = 'False';                 
333                        if($fileNames && !$error)
334                        {
335                                $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
336                                if($nameFileZip)
337                                {               
338                                        $file = $tempDir.'/'.$nameFileZip;
339                                } else {
340                                        $file = false;
341                                }                                                               
342                        }
343                        else
344                        {
345                                $file = false;
346                        }
347                        return $file;
348                }
349        }else{
350                // Exportacao de mensagens arquivadas localmente
351                if($params['l_msg'] == "t")
352                {
353                // Recebe todos os subjects e bodies das mensagens locais selecionadas para exportacao
354                // e gera arrays com os conteudos separados;
355                $array_mesgs = explode('@@',$params['mesgs']);
356                $array_subjects = explode('@@',$params['subjects']);
357            $array_ids = explode(',', $params['msgs_to_export']);
358                        $tempDir = $this->tempDir;
359                       
360                        include_once("class.imap_functions.inc.php");
361                        $imapf = new imap_functions();
362
363                        // quando houver apenas um arquivo, exporta o .eml sem coloca-lo em zip
364                        if (count($array_ids)==1)
365                        {
366                                $sEMLData=$imapf->treat_base64_from_post($array_mesgs[0]);
367                                $fileName=$this->CreateFileEml($sEMLData, $tempDir,'',$array_subjects[0],"offline");
368                                return $tempDir.'/'.$fileName;
369                        }
370
371                        // Para cada mensagem selecionada sera gerado um arquivo .eml cujo titulo sera o assunto (subject) da mesma;
372                foreach($array_ids as $i=>$id) {
373                                $sEMLData=$imapf->treat_base64_from_post($array_mesgs[$i]);
374                                $fileName=$this->CreateFileEml($sEMLData, $tempDir,'',$array_subjects[$i],$i);
375                                if(!$fileName){
376                                        $error = True;
377                                        break;
378                                } else{
379                                        $fileNames .= "\"".$fileName."\" ";
380                                }
381                        }
382                        $nameFileZip = 'False';
383                        if($fileNames && !$error) {
384                                $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
385                                if($nameFileZip){
386                                        $file = $tempDir.'/'.$nameFileZip;
387                                } else{
388                                        $file = false;
389                                }
390
391                        } else{
392                                $file = false;
393                        }
394            return $file;
395               
396                } else
397                // Exportacao de mensagens da caixa de entrada (imap) - processo original do Expresso
398                {
399                        $this-> folder = $params['folder'];
400                        $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
401                        $array_ids = explode(',', $params['msgs_to_export']);
402                        $error = False;
403                        $fileNames = "";
404                        $tempDir = $this->tempDir;
405                        $this->connectImap();
406
407                        // quando houver apenas um arquivo, exporta o .eml sem coloca-lo em zip
408                        if (count($array_ids)==1)
409                        {
410                                $header         = $this->getHeader($array_ids[0]);                                                                                     
411                                $body           = $this->getBody($array_ids[0]);                       
412                                $sEMLData       = $this->parseEml($header, $body);                     
413                                $fileName       = $this->CreateFileEml($sEMLData, $tempDir, $array_ids[0]."_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]);
414                       
415                                $header    = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $array_ids[0]), 80, 255);
416                    $subject = $this->decode_subject(html_entity_decode($header->fetchsubject));
417
418                                imap_close($this->mbox_stream);
419                                if (!$fileName) {
420                                        return false;
421                                } else {
422                                        $return = array();
423                                        $return[] = $tempDir.'/'.$fileName;
424                                        $return[] = $subject;
425                                        return $return;
426                                }
427                        }
428
429            $array_ids_count = count($array_ids);
430                        for($i = 0; $i < $array_ids_count; ++$i)
431                        {
432                                $header         = $this-> getHeader($array_ids[$i]);                                                                                   
433                                $body           = $this-> getBody($array_ids[$i]);                     
434                                $sEMLData       = $this -> parseEml($header, $body);                   
435                                $fileName       = $this -> CreateFileEml($sEMLData, $tempDir, $array_ids[$i]);
436
437                                if(!$fileName)
438                                {
439                                        $error = True;                                 
440                                        break;
441                                } else {
442                                        $fileNames .= "\"".$fileName."\" ";                     
443                                }
444                        }
445                        imap_close($this->mbox_stream);
446
447                        $nameFileZip = 'False';                 
448                        if($fileNames && !$error)
449                        {
450                                $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
451                                if($nameFileZip)
452                                {               
453                                        $file = $tempDir.'/'.$nameFileZip;
454                                        $ret[] = $file;
455                                    return $ret; 
456                                } else {
457                                        $file = false;
458                                }                                                               
459                        }
460                        else
461                        {
462                                $file = false;
463                        }
464                        return $file;
465                }
466    }
467    }
468
469    function export_eml( $params ){
470
471        return $this->export_msg_data( $params['msgs_to_export'],
472                                       $params['folder'] );
473    }
474
475        function export_msg($params) {
476                $this-> folder = $params['folder'];
477                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
478                $array_ids = explode(',', $params['msgs_to_export']);
479                $error = False;
480                $fileNames = "";
481                $tempDir = $this->tempDir;
482                $this->connectImap();
483
484                // quando houver apenas um arquivo, exporta o .eml sem coloca-lo em zip
485                if (count($array_ids)==1)
486                {
487                        $header         = $this->getHeader($array_ids[0]);                                                                                     
488                        $body           = $this->getBody($array_ids[0]);                       
489                        $sEMLData       = $this->parseEml($header, $body);                     
490                        $fileName       = $this->CreateFileEml($sEMLData, $tempDir, $array_ids[0]."_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]);
491
492                        $header    = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $array_ids[0]), 80, 255);
493            $subject = $this->decode_subject(html_entity_decode($header->fetchsubject));
494
495                        imap_close($this->mbox_stream);
496                        if (!$fileName) {
497                                return false;
498                        } else {
499                                $return = array();
500                                $return[] = $tempDir.'/'.$fileName;
501                                $return[] = $subject;
502                                return $return;
503                        }
504                }
505        }
506
507        //MAILARCHIVER
508        function js_source_var($params) {
509                $this-> folder = $params['folder'];
510                if(!$this->folder){
511                   $aux = explode(';',$params['msgs_to_export']);
512                   $this->folder = $aux[0];
513                   $id_number = $aux[1];
514                }
515                else{
516                        $id_number = $params['msgs_to_export'];
517                }
518                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
519                $tempDir = ini_get("session.save_path");
520
521                $this->connectImap();
522                $header         = $this-> getHeader($id_number);
523                $body           = $this-> getBody($id_number);
524               
525                if(!strpos($header,"Date: ")){
526                        $header = "Date: " . $this->getHeaderInfo($id_number)->Date . "\r\n" .$header ;
527                }
528
529                imap_close($this->mbox_stream);
530
531                $input = $header . "\r\n\r\n" . $body;
532                $input = preg_replace('/\x1d/', '', $input); //remove special char control detected (hex 1D)
533               
534                return($input);
535        }
536       
537    function export_msg_data($id_msg,$folder) {
538                $this->folder = $folder;
539                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
540
541                $this->connectImap();
542                $header         = $this-> getHeader($id_msg);
543                $body           = $this-> getBody($id_msg);
544
545                $msg_data = $header ."\r\n\r\n". $body;
546
547                imap_close($this->mbox_stream);
548                return $msg_data;
549        }
550
551                function export_to_archive($id_msg,$folder) {
552                $this->folder = $folder;
553                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
554                $tempDir = $this->tempDir;
555                                 
556                $this->connectImap();
557                $header         = $this-> getHeader($id_msg);
558                $body           = $this-> getBody($id_msg);
559               
560                $file = tempnam ($tempDir, 'source_#'.$id_msg);
561                $file .= '.php';
562                $fileName = basename ($file);
563                $f = fopen($file, "w");
564                fputs($f,$phpheader.$header ."\r\n\r\n". $body);
565                fclose($f);
566                $urlPath = 'tmpLclAtt/' . $fileName;
567                                 
568                imap_close($this->mbox_stream);
569                return "inc/gotodownload.php?idx_file=".$tempDir . '/'.$file."&newfilename=fonte_da_mensagem.txt";
570        }
571                                 
572        function remove_accents($string) {
573                /*
574                        $array1 = array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç" , "?", "\"", "!", "@", "#", "$", "%", "š", "&", "*", "(", ")", "-", "=", "+", "Ž", "`", "[", "]", "{", "}", "~", "^", ",", "<", ">", ";", ":", "/", "?", "\\", "|", "¹", "²", "³", "£", "¢", "¬", "§", "ª", "º", "°", "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");
575                        $array2 = array("a", "a", "a", "a", "a", "e", "e", "e", "e", "i", "i", "i", "i", "o", "o", "o", "o", "o", "u", "u", "u", "u", "c" , "" , ""  , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" ,  "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "A", "A", "A", "A", "A", "E", "E", "E", "E", "I", "I", "I", "I", "O", "O", "O", "O", "O", "U", "U", "U", "U", "C");
576                        return str_replace( $array1, $array2, $string );
577                */
578                return strtr($string,
579                        "áàâãäéèêëíìîïóòôõöúùûüç?\"'!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº°ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ",
580                        "aaaaaeeeeiiiiooooouuuuc___________________________________________AAAAAEEEEIIIIOOOOOUUUUC");
581        }
582
583        function get_attachments_headers( $folder, $id_number ){
584
585            $this->folder = mb_convert_encoding($folder, "UTF7-IMAP","UTF-8");
586               
587            $return_attachments = array();
588               
589            include_once("class.attachment.inc.php");
590
591            $imap_attachment = new attachment();
592            $imap_attachment->setStructureFromMail( $folder, $id_number );
593            $attachments = $imap_attachment->getAttachmentsInfo();
594
595                foreach($attachments as $i => $attachment){
596
597                    $fileContent = $imap_attachment->getAttachment( $attachment['pid'] );
598                       
599                    $headers = "<?php header('Content-Type: {$attachment['type']}');
600                                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
601                                header('Pragma: public');
602                                header('Expires: 0'); // set expiration time
603                                      header('Content-Disposition: attachment; filename=\"{$attachment['name']}\"');\n
604                                      echo '$fileContent';?>";
605                       
606                    $return_attachments[ $attachment['name'] ] = array( "content" => $headers, "pid" => $attachment['pid'] );
607                        }
608
609            return( $return_attachments );
610                        }
611                       
612        function get_attachments_in_array($params) {
613                $return_attachments = array();
614
615                $attachments = $this->get_attachments_headers( $params['folder'], $params['num_msg'] );
616
617                if( !empty( $attachments ) )
618                {
619                    foreach($attachments as $fileNameReal => $attachment){
620
621                            array_push($return_attachments,array('name' => $fileNameReal, 'pid' =>$attachment['pid'], 'contentType' => $this->getFileType( $fileNameReal  ) ));
622                }
623        }
624
625                return $return_attachments;
626
627        }
628       
629        private function getFileType($nameFile) {
630                $strFileType = strrev(substr(strrev(strtolower($nameFile)),0,4));
631                $ContentType = "application/octet-stream";
632                if ($strFileType == ".asf")
633                        $ContentType = "video/x-ms-asf";
634                if ($strFileType == ".avi")
635                        $ContentType = "video/avi";
636                if ($strFileType == ".doc")
637                        $ContentType = "application/msword";
638                if ($strFileType == ".zip")
639                        $ContentType = "application/zip";
640                if ($strFileType == ".xls")
641                        $ContentType = "application/vnd.ms-excel";
642                if ($strFileType == ".gif")
643                        $ContentType = "image/gif";
644                if ($strFileType == ".png")
645                        $ContentType = "image/png";
646                if ($strFileType == ".jpg" || $strFileType == "jpeg")
647                        $ContentType = "image/jpeg";
648                if ($strFileType == ".wav")
649                        $ContentType = "audio/wav";
650                if ($strFileType == ".mp3")
651                        $ContentType = "audio/mpeg3";
652                if ($strFileType == ".mpg" || $strFileType == "mpeg")
653                        $ContentType = "video/mpeg";
654                if ($strFileType == ".rtf")
655                        $ContentType = "application/rtf";
656                if ($strFileType == ".htm" || $strFileType == "html")
657                        $ContentType = "text/html";
658                if ($strFileType == ".xml")
659                        $ContentType = "text/xml";
660                if ($strFileType == ".xsl")
661                        $ContentType = "text/xsl";
662                if ($strFileType == ".css")
663                        $ContentType = "text/css";
664                if ($strFileType == ".php")
665                        $ContentType = "text/php";
666                if ($strFileType == ".asp")
667                        $ContentType = "text/asp";
668                if ($strFileType == ".pdf")
669                        $ContentType = "application/pdf";
670                if ($strFileType == ".txt")
671                        $ContentType = "text/plain";
672                if ($strFileType == ".log")
673                        $ContentType = "text/plain";
674                if ($strFileType == ".wmv")
675                        $ContentType = "video/x-ms-wmv";
676                if ($strFileType == ".sxc")
677                        $ContentType = "application/vnd.sun.xml.calc";
678                if ($strFileType == ".odt")
679                        $ContentType = "application/vnd.oasis.opendocument.text";
680                if ($strFileType == ".stc")
681                        $ContentType = "application/vnd.sun.xml.calc.template";
682                if ($strFileType == ".sxd")
683                        $ContentType = "application/vnd.sun.xml.draw";
684                if ($strFileType == ".std")
685                        $ContentType = "application/vnd.sun.xml.draw.template";
686                if ($strFileType == ".sxi")
687                        $ContentType = "application/vnd.sun.xml.impress";
688                if ($strFileType == ".sti")
689                        $ContentType = "application/vnd.sun.xml.impress.template";
690                if ($strFileType == ".sxm")
691                        $ContentType = "application/vnd.sun.xml.math";
692                if ($strFileType == ".sxw")
693                        $ContentType = "application/vnd.sun.xml.writer";
694                if ($strFileType == ".sxq")
695                        $ContentType = "application/vnd.sun.xml.writer.global";
696                if ($strFileType == ".stw")
697                        $ContentType = "application/vnd.sun.xml.writer.template";
698                if ($strFileType == ".ps")
699                        $ContentType = "application/postscript";
700                if ($strFileType == ".pps")
701                        $ContentType = "application/vnd.ms-powerpoint";
702                if ($strFileType == ".odt")
703                        $ContentType = "application/vnd.oasis.opendocument.text";
704                if ($strFileType == ".ott")
705                        $ContentType = "application/vnd.oasis.opendocument.text-template";
706                if ($strFileType == ".oth")
707                        $ContentType = "application/vnd.oasis.opendocument.text-web";
708                if ($strFileType == ".odm")
709                        $ContentType = "application/vnd.oasis.opendocument.text-master";
710                if ($strFileType == ".odg")
711                        $ContentType = "application/vnd.oasis.opendocument.graphics";
712                if ($strFileType == ".otg")
713                        $ContentType = "application/vnd.oasis.opendocument.graphics-template";
714                if ($strFileType == ".odp")
715                        $ContentType = "application/vnd.oasis.opendocument.presentation";
716                if ($strFileType == ".otp")
717                        $ContentType = "application/vnd.oasis.opendocument.presentation-template";
718                if ($strFileType == ".ods")
719                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet";
720                if ($strFileType == ".ots")
721                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet-template";
722                if ($strFileType == ".odc")
723                        $ContentType = "application/vnd.oasis.opendocument.chart";
724                if ($strFileType == ".odf")
725                        $ContentType = "application/vnd.oasis.opendocument.formula";
726                if ($strFileType == ".odi")
727                        $ContentType = "application/vnd.oasis.opendocument.image";
728                if ($strFileType == ".ndl")
729                        $ContentType = "application/vnd.lotus-notes";
730                if ($strFileType == ".eml")
731                        $ContentType = "text/plain";
732                if ($strFileType == ".png")
733                        $ContentType = "image/png";
734                return $ContentType;
735        }
736       
737        function download_all_attachments($params) {
738               
739                require_once dirname(__FILE__).'/class.attachment.inc.php';
740                $atObj = new attachment();
741                $atObj->setStructureFromMail($params['folder'],$params['num_msg']);
742                $attachments = $atObj->getAttachmentsInfo();
743                $id_number = $params['num_msg'];               
744                $tempDir = $this->tempDir;
745                $tempSubDir = $_SESSION['phpgw_session']['session_id'];
746                $fileNames = '';
747                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
748                $this-> folder = $params['folder'];
749                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
750               
751                $fileNames = Array();
752                $attachments_count = count($attachments);
753                for ($i = 0; $i < $attachments_count; ++$i)
754                {
755                   $attachments[$i]['name'] = $this->remove_accents($attachments[$i]['name']);
756                   $fileNames[$i] = $attachments[$i]['name'];
757                }
758
759                $attachments_count = count($attachments);
760                for ($i = 0; $i < $attachments_count; ++$i)
761                {
762                        $fileName = $attachments[$i]['name'];
763                        $result = array_keys($fileNames, $fileName);
764
765                        // Detecta duplicatas
766                        if (count($result) > 1)
767                        {
768                            $result_count = count($result);
769                            for ($j = 1; $j < $result_count; ++$j)
770                            {
771                                $replacement = '('.$j.')$0';
772                                if (preg_match('/\.\w{2,4}$/', $fileName))
773                                {
774                                    $fileNames[$result[$j]] = preg_replace('/\.\w{2,4}$/', $replacement, $fileName);
775                                }
776                                else
777                                {
778                                    $fileNames[$result[$j]] .= "($j)";
779                                }
780                                $attachments[$result[$j]]['name'] = $fileNames[$result[$j]];
781                            }
782                        }
783                        // Fim detecta duplicatas
784
785                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
786                        if(!$f)
787                                return False;                   
788                        $fileContent = $atObj->getAttachment( $attachments[$i]['pid'] );       
789                                fputs($f,$fileContent);
790                               
791                        fclose($f);
792               
793                }
794                imap_close($this->mbox_stream);
795                $nameFileZip = '';
796               
797                if(!empty($fileNames)) {
798                        $nameFileZip = $this -> createFileZip($fileNames, $tempDir . '/'.$tempSubDir);                                         
799                        if($nameFileZip)
800                                $file =  $tempDir . '/'.$tempSubDir.'/'.$nameFileZip;
801                        else {
802                                $file = false;
803                        }
804                }
805                else
806                        $file = false; 
807                return $file;
808        }
809
810        function getHeader($msg_number){                       
811                return imap_fetchheader($this->mbox_stream, $msg_number, FT_UID);
812        }
813
814        function getHeaderInfo($msg_number){                   
815                $header = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number), 80, 255);
816                return $header;
817        }
818       
819        function getBody($msg_number){
820                $header = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number), 80, 255);
821                $body = imap_body($this->mbox_stream, $msg_number, FT_UID);
822                if(($header->Unseen == 'U') || ($header->Recent == 'N')){
823                        imap_clearflag_full($this->mbox_stream, $msg_number, "\\Seen", ST_UID);
824                }
825                return $body;
826        }
827
828        function decode_subject($string){
829                if ((strpos(strtolower($string), '=?iso-8859-1') !== false)
830                        || (strpos(strtolower($string), '=?windows-1252') !== false)){
831                        $elements = imap_mime_header_decode($string);
832                        foreach ($elements as $el)
833                                $return .= $el->text;
834                }
835                else if (strpos(strtolower($string), '=?utf-8') !== false) {
836                        $elements = imap_mime_header_decode($string);
837                        foreach ($elements as $el){
838                                $charset = $el->charset;
839                                $text    = $el->text;
840                                if(!strcasecmp($charset, "utf-8") ||
841                                !strcasecmp($charset, "utf-7")) {
842                                $text = iconv($charset, "ISO-8859-1", $text);
843                        }
844                        $return .= $text;
845                        }
846                }
847                else
848                        $return = $string;
849
850                return $this->remove_accents($return);         
851        }
852}
853// END CLASS
854?>
Note: See TracBrowser for help on using the repository browser.