source: sandbox/2.2.0.2/expressoMail1_2/inc/class.exporteml.inc.php @ 4416

Revision 4416, 22.6 KB checked in by airton, 13 years ago (diff)

Ticket #1887 - Redefinicao do parser de email - Todas as adequacoes feitas no parser.

  • 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 = ereg_replace('/', '\'', $subject);
69                        $from = "áàâãäéèêëíìîïóòôõöúùûüç?\"!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº° .ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ";
70                        $to =   "aaaaaeeeeiiiiooooouuuuc______________________________________________AAAAAEEEEIIIIOOOOOUUUUC";
71                        $subject = strtr($subject,$from,$to);
72
73                        $subject = eregi_replace("[^a-zA-Z0-9_]", "_", $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 = eregi_replace("[^a-zA-Z0-9_]", "_", $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        function makeAll($params) {
186                // Exportacao de mensagens arquivadas localmente
187                if($params['l_msg'] == "t")
188                {
189                // Recebe todos os subjects e bodies das mensagens locais selecionadas para exportacao
190                // e gera arrays com os conteudos separados;
191                $array_mesgs = explode('@@',$params['mesgs']);
192                $array_subjects = explode('@@',$params['subjects']);
193            $array_ids = explode(',', $params['msgs_to_export']);
194                        $tempDir = $this->tempDir;
195                       
196                        include_once("class.imap_functions.inc.php");
197                        $imapf = new imap_functions();
198
199                        // quando houver apenas um arquivo, exporta o .eml sem coloca-lo em zip
200                        if (count($array_ids)==1)
201                        {
202                                $sEMLData=$imapf->treat_base64_from_post($array_mesgs[$i]);
203                                $fileName=$this->CreateFileEml($sEMLData, $tempDir,'',$array_subjects[$i],$i);
204                                return $tempDir.'/'.$fileName;
205                        }
206
207                        // Para cada mensagem selecionada sera gerado um arquivo .eml cujo titulo sera o assunto (subject) da mesma;
208                foreach($array_ids as $i=>$id) {
209                                $sEMLData=$imapf->treat_base64_from_post($array_mesgs[$i]);
210                                $fileName=$this->CreateFileEml($sEMLData, $tempDir,'',$array_subjects[$i],$i);
211                                if(!$fileName){
212                                        $error = True;
213                                        break;
214                                } else{
215                                        $fileNames .= "\"".$fileName."\" ";
216                                }
217                        }
218                        $nameFileZip = 'False';
219                        if($fileNames && !$error) {
220                                $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
221                                if($nameFileZip){
222                                        $file = $tempDir.'/'.$nameFileZip;
223                                } else{
224                                        $file = false;
225                                }
226
227                        } else{
228                                $file = false;
229                        }
230
231            return $file;
232               
233                } else
234                // Exportacao de mensagens da caixa de entrada (imap) - processo original do Expresso
235                {
236                        $this-> folder = $params['folder'];
237                        $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
238                        $array_ids = explode(',', $params['msgs_to_export']);
239                        $error = False;
240                        $fileNames = "";
241                        $tempDir = $this->tempDir;
242                        $this->connectImap();
243
244                        // quando houver apenas um arquivo, exporta o .eml sem coloca-lo em zip
245                        if (count($array_ids)==1)
246                        {
247                                $header         = $this->getHeader($array_ids[0]);                                                                                     
248                                $body           = $this->getBody($array_ids[0]);                       
249                                $sEMLData       = $this->parseEml($header, $body);                     
250                                $fileName       = $this->CreateFileEml($sEMLData, $tempDir, $array_ids[0]."_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]);
251
252                                imap_close($this->mbox_stream);
253                                if (!$fileName) {
254                                        return false;
255                                } else {
256                                        return $tempDir.'/'.$fileName;
257                                }
258                        }
259
260                        for($i = 0; $i < count($array_ids); $i++)
261                        {
262                                $header         = $this-> getHeader($array_ids[$i]);                                                                                   
263                                $body           = $this-> getBody($array_ids[$i]);                     
264                                $sEMLData       = $this -> parseEml($header, $body);                   
265                                $fileName       = $this -> CreateFileEml($sEMLData, $tempDir, $array_ids[$i]);
266
267                                if(!$fileName)
268                                {
269                                        $error = True;                                 
270                                        break;
271                                } else {
272                                        $fileNames .= "\"".$fileName."\" ";                     
273                                }
274                        }
275                        imap_close($this->mbox_stream);
276
277                        $nameFileZip = 'False';                 
278                        if($fileNames && !$error)
279                        {
280                                $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
281                                if($nameFileZip)
282                                {               
283                                        $file = $tempDir.'/'.$nameFileZip;
284                                } else {
285                                        $file = false;
286                                }                                                               
287                        }
288                        else
289                        {
290                                $file = false;
291                        }
292
293                        return $file;
294                }
295    }
296
297        function export_msg($params) {
298                $this-> folder = $params['folder'];
299                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
300                $id_number = $params['msgs_to_export'];
301                $tempDir = $this->tempDir;
302                $this->connectImap();
303                $header         = $this-> getHeader($id_number);
304                $body           = $this-> getBody($id_number);
305               
306                $file = "source_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]."_".time().".php"; //source_[sessao]_[timestamp].php
307                $f = fopen($tempDir.'/'.$file,"w");
308                fputs($f,$header ."\r\n\r\n". $body);
309                fclose($f);
310               
311                imap_close($this->mbox_stream);
312                return $tempDir.'/'.$file;
313        }
314
315    function export_msg_data($id_msg,$folder) {
316                $this->folder = $folder;
317                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
318
319                $this->connectImap();
320                $header         = $this-> getHeader($id_msg);
321                $body           = $this-> getBody($id_msg);
322
323                $msg_data = $header ."\r\n\r\n". $body;
324
325                imap_close($this->mbox_stream);
326                return $msg_data;
327        }
328
329                function export_to_archive($id_msg,$folder) {
330                $this-> folder = $folder;
331                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
332                   
333                $tempDir = $this->tempDir;
334                                 
335                $this->connectImap();
336                $header         = $this-> getHeader($id_msg);
337                $body           = $this-> getBody($id_msg);
338                $name = md5($_SESSION[ 'phpgw_session' ][ 'session_id' ].microtime());
339               
340                $file = $_SESSION[ 'phpgw_session' ][ 'session_id' ].$name;
341                $f = fopen($tempDir . '/'.$file,"w");
342                fputs($f,utf8_encode($header) ."\r\n\r\n". utf8_encode($body));
343                fclose($f);
344                                 
345                imap_close($this->mbox_stream);
346                return "inc/gotodownload.php?idx_file=".$tempDir . '/'.$file."&newfilename=fonte_da_mensagem.txt";
347                                 
348        }
349
350        function get_attachments_in_array($params) {
351                $return_attachments = array();
352
353                $id_number = $params['num_msg'];               
354                $attachments =unserialize(rawurldecode($params['s_attachments']));
355               
356                $tempDir = dirname( __FILE__ ) . '/../tmpLclAtt';
357                $tempSubDir = md5(microtime());
358                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
359               
360                $this-> folder = $params['folder'];
361                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
362                $this->connectImap();
363
364                include_once("class.imap_attachment.inc.php");
365
366                $imap_attachment = new imap_attachment();
367                $attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
368                foreach($attachments as $i => $attachment){
369                        if($i && $i == 'names')
370                                continue;
371                        $fileNameReal = $this->remove_accents($attachment['name']);
372                        $ContentType = $this->getFileType($fileNameReal);
373                        $fileName = $fileNameReal . ".php";
374                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
375                        if(!$f)
376                                return $tempDir . '/'.$tempSubDir.'/'.$fileName;                       
377
378                        $fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachment['pid'], FT_UID);
379                        $urlPath = 'tmpLclAtt/'.$tempSubDir.'/'.$fileName;
380                       
381                        $headers = "<?php header('Content-Type: ".$ContentType."');
382                                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
383                                header('Pragma: public');
384                                header('Expires: 0'); // set expiration time
385                                header('Content-Disposition: attachment; filename=\"". addslashes($fileNameReal) ."\"');\n echo ";
386                       
387                        if($attachment['encoding'] == 'base64') {
388                                $headers.=" imap_base64('".$fileContent."');?>";
389                        }
390                        else if($attachment['encoding'] == 'quoted_printable_decode') {
391                                $headers.=" quoted_printable_decode('".$fileContent."');?>";
392                        }
393                        else {
394                                $headers.=" '".$fileContent."';?>";
395                        }
396                       
397                        fputs($f,$headers);
398
399                        array_push($return_attachments,array('name' => $fileName,'url' => $urlPath,'pid' =>$attachment['pid']));
400                        fclose($f);
401                }
402                imap_close($this->mbox_stream);
403                return $return_attachments;
404        }
405
406
407        function remove_accents($string) {
408                /*
409                        $array1 = array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç" , "?", "\"", "!", "@", "#", "$", "%", "š", "&", "*", "(", ")", "-", "=", "+", "Ž", "`", "[", "]", "{", "}", "~", "^", ",", "<", ">", ";", ":", "/", "?", "\\", "|", "¹", "²", "³", "£", "¢", "¬", "§", "ª", "º", "°", "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");
410                        $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");
411                        return str_replace( $array1, $array2, $string );
412                */
413                return strtr($string,
414                        "áàâãäéèêëíìîïóòôõöúùûüç?\"'!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº°ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ",
415                        "aaaaaeeeeiiiiooooouuuuc___________________________________________AAAAAEEEEIIIIOOOOOUUUUC");
416        }
417       
418
419        private function getFileType($nameFile) {
420                $strFileType = strrev(substr(strrev(strtolower($nameFile)),0,4));
421                $ContentType = "application/octet-stream";
422                if ($strFileType == ".asf")
423                        $ContentType = "video/x-ms-asf";
424                if ($strFileType == ".avi")
425                        $ContentType = "video/avi";
426                if ($strFileType == ".doc")
427                        $ContentType = "application/msword";
428                if ($strFileType == ".zip")
429                        $ContentType = "application/zip";
430                if ($strFileType == ".xls")
431                        $ContentType = "application/vnd.ms-excel";
432                if ($strFileType == ".gif")
433                        $ContentType = "image/gif";
434                if ($strFileType == ".png")
435                        $ContentType = "image/png";
436                if ($strFileType == ".jpg" || $strFileType == "jpeg")
437                        $ContentType = "image/jpeg";
438                if ($strFileType == ".wav")
439                        $ContentType = "audio/wav";
440                if ($strFileType == ".mp3")
441                        $ContentType = "audio/mpeg3";
442                if ($strFileType == ".mpg" || $strFileType == "mpeg")
443                        $ContentType = "video/mpeg";
444                if ($strFileType == ".rtf")
445                        $ContentType = "application/rtf";
446                if ($strFileType == ".htm" || $strFileType == "html")
447                        $ContentType = "text/html";
448                if ($strFileType == ".xml")
449                        $ContentType = "text/xml";
450                if ($strFileType == ".xsl")
451                        $ContentType = "text/xsl";
452                if ($strFileType == ".css")
453                        $ContentType = "text/css";
454                if ($strFileType == ".php")
455                        $ContentType = "text/php";
456                if ($strFileType == ".asp")
457                        $ContentType = "text/asp";
458                if ($strFileType == ".pdf")
459                        $ContentType = "application/pdf";
460                if ($strFileType == ".txt")
461                        $ContentType = "text/plain";
462                if ($strFileType == ".log")
463                        $ContentType = "text/plain";
464                if ($strFileType == ".wmv")
465                        $ContentType = "video/x-ms-wmv";
466                if ($strFileType == ".sxc")
467                        $ContentType = "application/vnd.sun.xml.calc";
468                if ($strFileType == ".odt")
469                        $ContentType = "application/vnd.oasis.opendocument.text";
470                if ($strFileType == ".stc")
471                        $ContentType = "application/vnd.sun.xml.calc.template";
472                if ($strFileType == ".sxd")
473                        $ContentType = "application/vnd.sun.xml.draw";
474                if ($strFileType == ".std")
475                        $ContentType = "application/vnd.sun.xml.draw.template";
476                if ($strFileType == ".sxi")
477                        $ContentType = "application/vnd.sun.xml.impress";
478                if ($strFileType == ".sti")
479                        $ContentType = "application/vnd.sun.xml.impress.template";
480                if ($strFileType == ".sxm")
481                        $ContentType = "application/vnd.sun.xml.math";
482                if ($strFileType == ".sxw")
483                        $ContentType = "application/vnd.sun.xml.writer";
484                if ($strFileType == ".sxq")
485                        $ContentType = "application/vnd.sun.xml.writer.global";
486                if ($strFileType == ".stw")
487                        $ContentType = "application/vnd.sun.xml.writer.template";
488                if ($strFileType == ".ps")
489                        $ContentType = "application/postscript";
490                if ($strFileType == ".pps")
491                        $ContentType = "application/vnd.ms-powerpoint";
492                if ($strFileType == ".odt")
493                        $ContentType = "application/vnd.oasis.opendocument.text";
494                if ($strFileType == ".ott")
495                        $ContentType = "application/vnd.oasis.opendocument.text-template";
496                if ($strFileType == ".oth")
497                        $ContentType = "application/vnd.oasis.opendocument.text-web";
498                if ($strFileType == ".odm")
499                        $ContentType = "application/vnd.oasis.opendocument.text-master";
500                if ($strFileType == ".odg")
501                        $ContentType = "application/vnd.oasis.opendocument.graphics";
502                if ($strFileType == ".otg")
503                        $ContentType = "application/vnd.oasis.opendocument.graphics-template";
504                if ($strFileType == ".odp")
505                        $ContentType = "application/vnd.oasis.opendocument.presentation";
506                if ($strFileType == ".otp")
507                        $ContentType = "application/vnd.oasis.opendocument.presentation-template";
508                if ($strFileType == ".ods")
509                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet";
510                if ($strFileType == ".ots")
511                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet-template";
512                if ($strFileType == ".odc")
513                        $ContentType = "application/vnd.oasis.opendocument.chart";
514                if ($strFileType == ".odf")
515                        $ContentType = "application/vnd.oasis.opendocument.formula";
516                if ($strFileType == ".odi")
517                        $ContentType = "application/vnd.oasis.opendocument.image";
518                if ($strFileType == ".ndl")
519                        $ContentType = "application/vnd.lotus-notes";
520                if ($strFileType == ".eml")
521                        $ContentType = "text/plain";
522                return $ContentType;
523        }
524       
525        function download_all_attachments($params) {
526               
527                $id_number = $params['num_msg'];               
528                $attachments =unserialize(rawurldecode($params['s_attachments']));
529               
530                $tempDir = $this->tempDir;
531                $tempSubDir = $_SESSION['phpgw_session']['session_id'];
532                $fileNames = '';
533                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
534                $this-> folder = $params['folder'];
535                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
536                $this->connectImap();
537                include("class.imap_attachment.inc.php");
538                $imap_attachment = new imap_attachment();
539                $attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
540               
541                $fileNames = Array();
542                       
543                for ($i = 0; $i < count($attachments); $i++)
544                {
545                   $attachments[$i]['name'] = $this->remove_accents($attachments[$i]['name']);
546                   $fileNames[$i] = $attachments[$i]['name'];
547                }
548
549                for ($i = 0; $i < count($attachments); $i++)
550                {
551                        $fileName = $attachments[$i]['name'];
552                        $result = array_keys($fileNames, $fileName);
553
554                        // Detecta duplicatas
555                        if (count($result) > 1)
556                        {
557                            for ($j = 1; $j < count($result); $j++)
558                            {
559                                $replacement = '('.$j.')$0';
560                                if (preg_match('/\.\w{2,4}$/', $fileName))
561                                {
562                                    $fileNames[$result[$j]] = preg_replace('/\.\w{2,4}$/', $replacement, $fileName);
563                                }
564                                else
565                                {
566                                    $fileNames[$result[$j]] .= "($j)";
567                                }
568                                $attachments[$result[$j]]['name'] = $fileNames[$result[$j]];
569                            }
570                        }
571                        // Fim detecta duplicatas
572
573                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
574                        if(!$f)
575                                return False;                   
576                                               
577                        $fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachments[$i]['pid'], FT_UID);
578                        if($attachments[$i]['encoding'] == 'base64')
579                                fputs($f,imap_base64($fileContent));
580                        else           
581                                fputs($f,$fileContent);
582                               
583                        fclose($f);
584               
585                }
586                imap_close($this->mbox_stream);
587                $nameFileZip = '';
588               
589                if(!empty($fileNames)) {
590                        $nameFileZip = $this -> createFileZip($fileNames, $tempDir . '/'.$tempSubDir);                                         
591                        if($nameFileZip)
592                                $file =  $tempDir . '/'.$tempSubDir.'/'.$nameFileZip;
593                        else {
594                                $file = false;
595                        }
596                }
597                else
598                        $file = false; 
599                return $file;
600        }
601
602        function getHeader($msg_number){                       
603                return imap_fetchheader($this->mbox_stream, $msg_number, FT_UID);
604        }
605       
606        function getBody($msg_number){
607                $header = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number), 80, 255);
608                $body = imap_body($this->mbox_stream, $msg_number, FT_UID);
609                if(($header->Unseen == 'U') || ($header->Recent == 'N')){
610                        imap_clearflag_full($this->mbox_stream, $msg_number, "\\Seen", ST_UID);
611                }
612                return $body;
613        }
614
615        function decode_subject($string){
616                if ((strpos(strtolower($string), '=?iso-8859-1') !== false)
617                        || (strpos(strtolower($string), '=?windows-1252') !== false)){
618                        $elements = imap_mime_header_decode($string);
619                        foreach ($elements as $el)
620                                $return .= $el->text;
621                }
622                else if (strpos(strtolower($string), '=?utf-8') !== false) {
623                        $elements = imap_mime_header_decode($string);
624                        foreach ($elements as $el){
625                                $charset = $el->charset;
626                                $text    = $el->text;
627                                if(!strcasecmp($charset, "utf-8") ||
628                                !strcasecmp($charset, "utf-7")) {
629                                $text = iconv($charset, "ISO-8859-1", $text);
630                        }
631                        $return .= $text;
632                        }
633                }
634                else
635                        $return = $string;
636
637                return $this->remove_accents($return);         
638        }
639}
640// END CLASS
641?>
Note: See TracBrowser for help on using the repository browser.