source: branches/2.4/expressoMail1_2/inc/class.exporteml.inc.php @ 7228

Revision 7228, 27.3 KB checked in by douglas, 12 years ago (diff)

Ticket #0000 - Copiadas as alterações do Trunk. Versão final da 2.4.2.

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