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

Revision 7673, 30.6 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

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