source: sandbox/2.5.0-expresso1/expressoMail1_2/inc/class.exporteml.inc.php @ 7157

Revision 7157, 28.2 KB checked in by airton, 12 years ago (diff)

Ticket #3088 - Melhoria no arquivamento local - Funcionalidade de arquivamento de mensagens

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