source: sandbox/2.4.2-expresso3/expressoMail1_2/inc/class.exporteml.inc.php @ 6745

Revision 6745, 27.2 KB checked in by marcosw, 12 years ago (diff)

Ticket #2947 - Melhoria na exportação de mensagem individual

  • 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($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($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                                } else {
428                                        $file = false;
429                                }                                                               
430                        }
431                        else
432                        {
433                                $file = false;
434                        }
435                        return $file;
436                }
437    }
438    }
439
440    function export_eml( $params ){
441
442        return $this->export_msg_data( $params['msgs_to_export'],
443                                       $params['folder'] );
444    }
445
446        function export_msg($params) {
447                $this-> folder = $params['folder'];
448                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
449                $array_ids = explode(',', $params['msgs_to_export']);
450                $error = False;
451                $fileNames = "";
452                $tempDir = $this->tempDir;
453                $this->connectImap();
454
455                // quando houver apenas um arquivo, exporta o .eml sem coloca-lo em zip
456                if (count($array_ids)==1)
457                {
458                        $header         = $this->getHeader($array_ids[0]);                                                                                     
459                        $body           = $this->getBody($array_ids[0]);                       
460                        $sEMLData       = $this->parseEml($header, $body);                     
461                        $fileName       = $this->CreateFileEml($sEMLData, $tempDir, $array_ids[0]."_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]);
462
463                        $header    = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $array_ids[0]), 80, 255);
464            $subject = $this->decode_subject($header->fetchsubject);
465
466                        imap_close($this->mbox_stream);
467                        if (!$fileName) {
468                                return false;
469                        } else {
470                                $return = array();
471                                $return[] = $tempDir.'/'.$fileName;
472                                $return[] = $subject;
473                                return $return;
474                        }
475                }
476        }
477
478    function export_msg_data($id_msg,$folder) {
479                $this->folder = $folder;
480                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
481
482                $this->connectImap();
483                $header         = $this-> getHeader($id_msg);
484                $body           = $this-> getBody($id_msg);
485
486                $msg_data = $header ."\r\n\r\n". $body;
487
488                imap_close($this->mbox_stream);
489                return $msg_data;
490        }
491
492                function export_to_archive($id_msg,$folder) {
493                $this->folder = $folder;
494                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
495                $tempDir = $this->tempDir;
496                                 
497                $this->connectImap();
498                $header         = $this-> getHeader($id_msg);
499                $body           = $this-> getBody($id_msg);
500               
501                $file = tempnam ($tempDir, 'source_#'.$id_msg);
502                $file .= '.php';
503                $fileName = basename ($file);
504                $f = fopen($file, "w");
505                fputs($f,$phpheader.$header ."\r\n\r\n". $body);
506                fclose($f);
507                $urlPath = 'tmpLclAtt/' . $fileName;
508                                 
509                imap_close($this->mbox_stream);
510                return "inc/gotodownload.php?idx_file=".$tempDir . '/'.$file."&newfilename=fonte_da_mensagem.txt";
511        }
512                                 
513        function remove_accents($string) {
514                /*
515                        $array1 = array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç" , "?", "\"", "!", "@", "#", "$", "%", "š", "&", "*", "(", ")", "-", "=", "+", "Ž", "`", "[", "]", "{", "}", "~", "^", ",", "<", ">", ";", ":", "/", "?", "\\", "|", "¹", "²", "³", "£", "¢", "¬", "§", "ª", "º", "°", "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");
516                        $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");
517                        return str_replace( $array1, $array2, $string );
518                */
519                return strtr($string,
520                        "áàâãäéèêëíìîïóòôõöúùûüç?\"'!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº°ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ",
521                        "aaaaaeeeeiiiiooooouuuuc___________________________________________AAAAAEEEEIIIIOOOOOUUUUC");
522        }
523
524        function get_attachments_headers( $folder, $id_number ){
525
526            $this->folder = mb_convert_encoding($folder, "UTF7-IMAP","UTF-8");
527               
528            $return_attachments = array();
529               
530            include_once("class.attachment.inc.php");
531
532            $imap_attachment = new attachment();
533            $imap_attachment->setStructureFromMail( $folder, $id_number );
534            $attachments = $imap_attachment->getAttachmentsInfo();
535
536                foreach($attachments as $i => $attachment){
537
538                    $fileContent = $imap_attachment->getAttachment( $attachment['pid'] );
539                       
540                    $headers = "<?php header('Content-Type: {$attachment['type']}');
541                                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
542                                header('Pragma: public');
543                                header('Expires: 0'); // set expiration time
544                                      header('Content-Disposition: attachment; filename=\"{$attachment['name']}\"');\n
545                                      echo '$fileContent';?>";
546                       
547                    $return_attachments[ $attachment['name'] ] = array( "content" => $headers, "pid" => $attachment['pid'] );
548                        }
549
550            return( $return_attachments );
551                        }
552                       
553        function get_attachments_in_array($params) {
554                $return_attachments = array();
555
556                $attachments = $this->get_attachments_headers( $params['folder'], $params['num_msg'] );
557
558                if( !empty( $attachments ) )
559                {
560                    foreach($attachments as $fileNameReal => $attachment){
561
562                            array_push($return_attachments,array('name' => $fileNameReal, 'pid' =>$attachment['pid'], 'contentType' => $this->getFileType( $fileNameReal  ) ));
563                }
564        }
565
566                return $return_attachments;
567
568        }
569       
570        private function getFileType($nameFile) {
571                $strFileType = strrev(substr(strrev(strtolower($nameFile)),0,4));
572                $ContentType = "application/octet-stream";
573                if ($strFileType == ".asf")
574                        $ContentType = "video/x-ms-asf";
575                if ($strFileType == ".avi")
576                        $ContentType = "video/avi";
577                if ($strFileType == ".doc")
578                        $ContentType = "application/msword";
579                if ($strFileType == ".zip")
580                        $ContentType = "application/zip";
581                if ($strFileType == ".xls")
582                        $ContentType = "application/vnd.ms-excel";
583                if ($strFileType == ".gif")
584                        $ContentType = "image/gif";
585                if ($strFileType == ".png")
586                        $ContentType = "image/png";
587                if ($strFileType == ".jpg" || $strFileType == "jpeg")
588                        $ContentType = "image/jpeg";
589                if ($strFileType == ".wav")
590                        $ContentType = "audio/wav";
591                if ($strFileType == ".mp3")
592                        $ContentType = "audio/mpeg3";
593                if ($strFileType == ".mpg" || $strFileType == "mpeg")
594                        $ContentType = "video/mpeg";
595                if ($strFileType == ".rtf")
596                        $ContentType = "application/rtf";
597                if ($strFileType == ".htm" || $strFileType == "html")
598                        $ContentType = "text/html";
599                if ($strFileType == ".xml")
600                        $ContentType = "text/xml";
601                if ($strFileType == ".xsl")
602                        $ContentType = "text/xsl";
603                if ($strFileType == ".css")
604                        $ContentType = "text/css";
605                if ($strFileType == ".php")
606                        $ContentType = "text/php";
607                if ($strFileType == ".asp")
608                        $ContentType = "text/asp";
609                if ($strFileType == ".pdf")
610                        $ContentType = "application/pdf";
611                if ($strFileType == ".txt")
612                        $ContentType = "text/plain";
613                if ($strFileType == ".log")
614                        $ContentType = "text/plain";
615                if ($strFileType == ".wmv")
616                        $ContentType = "video/x-ms-wmv";
617                if ($strFileType == ".sxc")
618                        $ContentType = "application/vnd.sun.xml.calc";
619                if ($strFileType == ".odt")
620                        $ContentType = "application/vnd.oasis.opendocument.text";
621                if ($strFileType == ".stc")
622                        $ContentType = "application/vnd.sun.xml.calc.template";
623                if ($strFileType == ".sxd")
624                        $ContentType = "application/vnd.sun.xml.draw";
625                if ($strFileType == ".std")
626                        $ContentType = "application/vnd.sun.xml.draw.template";
627                if ($strFileType == ".sxi")
628                        $ContentType = "application/vnd.sun.xml.impress";
629                if ($strFileType == ".sti")
630                        $ContentType = "application/vnd.sun.xml.impress.template";
631                if ($strFileType == ".sxm")
632                        $ContentType = "application/vnd.sun.xml.math";
633                if ($strFileType == ".sxw")
634                        $ContentType = "application/vnd.sun.xml.writer";
635                if ($strFileType == ".sxq")
636                        $ContentType = "application/vnd.sun.xml.writer.global";
637                if ($strFileType == ".stw")
638                        $ContentType = "application/vnd.sun.xml.writer.template";
639                if ($strFileType == ".ps")
640                        $ContentType = "application/postscript";
641                if ($strFileType == ".pps")
642                        $ContentType = "application/vnd.ms-powerpoint";
643                if ($strFileType == ".odt")
644                        $ContentType = "application/vnd.oasis.opendocument.text";
645                if ($strFileType == ".ott")
646                        $ContentType = "application/vnd.oasis.opendocument.text-template";
647                if ($strFileType == ".oth")
648                        $ContentType = "application/vnd.oasis.opendocument.text-web";
649                if ($strFileType == ".odm")
650                        $ContentType = "application/vnd.oasis.opendocument.text-master";
651                if ($strFileType == ".odg")
652                        $ContentType = "application/vnd.oasis.opendocument.graphics";
653                if ($strFileType == ".otg")
654                        $ContentType = "application/vnd.oasis.opendocument.graphics-template";
655                if ($strFileType == ".odp")
656                        $ContentType = "application/vnd.oasis.opendocument.presentation";
657                if ($strFileType == ".otp")
658                        $ContentType = "application/vnd.oasis.opendocument.presentation-template";
659                if ($strFileType == ".ods")
660                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet";
661                if ($strFileType == ".ots")
662                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet-template";
663                if ($strFileType == ".odc")
664                        $ContentType = "application/vnd.oasis.opendocument.chart";
665                if ($strFileType == ".odf")
666                        $ContentType = "application/vnd.oasis.opendocument.formula";
667                if ($strFileType == ".odi")
668                        $ContentType = "application/vnd.oasis.opendocument.image";
669                if ($strFileType == ".ndl")
670                        $ContentType = "application/vnd.lotus-notes";
671                if ($strFileType == ".eml")
672                        $ContentType = "text/plain";
673                if ($strFileType == ".png")
674                        $ContentType = "image/png";
675                return $ContentType;
676        }
677       
678        function download_all_attachments($params) {
679               
680                require_once dirname(__FILE__).'/class.attachment.inc.php';
681                $atObj = new attachment();
682                $atObj->setStructureFromMail($params['folder'],$params['num_msg']);
683                $attachments = $atObj->getAttachmentsInfo();
684                $id_number = $params['num_msg'];               
685                $tempDir = $this->tempDir;
686                $tempSubDir = $_SESSION['phpgw_session']['session_id'];
687                $fileNames = '';
688                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
689                $this-> folder = $params['folder'];
690                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
691               
692                $fileNames = Array();
693                       
694                for ($i = 0; $i < count($attachments); $i++)
695                {
696                   $attachments[$i]['name'] = $this->remove_accents($attachments[$i]['name']);
697                   $fileNames[$i] = $attachments[$i]['name'];
698                }
699
700                for ($i = 0; $i < count($attachments); $i++)
701                {
702                        $fileName = $attachments[$i]['name'];
703                        $result = array_keys($fileNames, $fileName);
704
705                        // Detecta duplicatas
706                        if (count($result) > 1)
707                        {
708                            for ($j = 1; $j < count($result); $j++)
709                            {
710                                $replacement = '('.$j.')$0';
711                                if (preg_match('/\.\w{2,4}$/', $fileName))
712                                {
713                                    $fileNames[$result[$j]] = preg_replace('/\.\w{2,4}$/', $replacement, $fileName);
714                                }
715                                else
716                                {
717                                    $fileNames[$result[$j]] .= "($j)";
718                                }
719                                $attachments[$result[$j]]['name'] = $fileNames[$result[$j]];
720                            }
721                        }
722                        // Fim detecta duplicatas
723
724                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
725                        if(!$f)
726                                return False;                   
727                        $fileContent = $atObj->getAttachment( $attachments[$i]['pid'] );       
728                                fputs($f,$fileContent);
729                               
730                        fclose($f);
731               
732                }
733                imap_close($this->mbox_stream);
734                $nameFileZip = '';
735               
736                if(!empty($fileNames)) {
737                        $nameFileZip = $this -> createFileZip($fileNames, $tempDir . '/'.$tempSubDir);                                         
738                        if($nameFileZip)
739                                $file =  $tempDir . '/'.$tempSubDir.'/'.$nameFileZip;
740                        else {
741                                $file = false;
742                        }
743                }
744                else
745                        $file = false; 
746                return $file;
747        }
748
749        function getHeader($msg_number){                       
750                return imap_fetchheader($this->mbox_stream, $msg_number, FT_UID);
751        }
752       
753        function getBody($msg_number){
754                $header = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number), 80, 255);
755                $body = imap_body($this->mbox_stream, $msg_number, FT_UID);
756                if(($header->Unseen == 'U') || ($header->Recent == 'N')){
757                        imap_clearflag_full($this->mbox_stream, $msg_number, "\\Seen", ST_UID);
758                }
759                return $body;
760        }
761
762        function decode_subject($string){
763                if ((strpos(strtolower($string), '=?iso-8859-1') !== false)
764                        || (strpos(strtolower($string), '=?windows-1252') !== false)){
765                        $elements = imap_mime_header_decode($string);
766                        foreach ($elements as $el)
767                                $return .= $el->text;
768                }
769                else if (strpos(strtolower($string), '=?utf-8') !== false) {
770                        $elements = imap_mime_header_decode($string);
771                        foreach ($elements as $el){
772                                $charset = $el->charset;
773                                $text    = $el->text;
774                                if(!strcasecmp($charset, "utf-8") ||
775                                !strcasecmp($charset, "utf-7")) {
776                                $text = iconv($charset, "ISO-8859-1", $text);
777                        }
778                        $return .= $text;
779                        }
780                }
781                else
782                        $return = $string;
783
784                return $this->remove_accents($return);         
785        }
786}
787// END CLASS
788?>
Note: See TracBrowser for help on using the repository browser.