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

Revision 4457, 22.7 KB checked in by airton, 13 years ago (diff)

Ticket #1991 - Parametrizacao das buscas LDAP no ExpressoMail?

  • 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[0]);
203                                $fileName=$this->CreateFileEml($sEMLData, $tempDir,'',$array_subjects[0],"offline");
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' ].".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                $file = "source_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]."_".time().".php"; //source_[sessao]_[timestamp].php
342                $f = fopen($tempDir . '/'.$file,"w");
343                fputs($f,utf8_encode($header) ."\r\n\r\n". utf8_encode($body));
344                fclose($f);
345                                 
346                imap_close($this->mbox_stream);
347                return "inc/gotodownload.php?idx_file=".$tempDir . '/'.$file."&newfilename=fonte_da_mensagem.txt";
348                                 
349        }
350
351        function get_attachments_in_array($params) {
352                $return_attachments = array();
353
354                $id_number = $params['num_msg'];               
355                $attachments =unserialize(rawurldecode($params['s_attachments']));
356               
357                $tempDir = dirname( __FILE__ ) . '/../tmpLclAtt';
358                $tempSubDir = md5(microtime());
359                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
360               
361                $this-> folder = $params['folder'];
362                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
363                $this->connectImap();
364
365                include_once("class.imap_attachment.inc.php");
366
367                $imap_attachment = new imap_attachment();
368                $attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
369                foreach($attachments as $i => $attachment){
370                        if($i && $i == 'names')
371                                continue;
372                        $fileNameReal = $this->remove_accents($attachment['name']);
373                        $ContentType = $this->getFileType($fileNameReal);
374                        $fileName = $fileNameReal . ".php";
375                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
376                        if(!$f)
377                                return $tempDir . '/'.$tempSubDir.'/'.$fileName;                       
378
379                        $fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachment['pid'], FT_UID);
380                        $urlPath = 'tmpLclAtt/'.$tempSubDir.'/'.$fileName;
381                       
382                        $headers = "<?php header('Content-Type: ".$ContentType."');
383                                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
384                                header('Pragma: public');
385                                header('Expires: 0'); // set expiration time
386                                header('Content-Disposition: attachment; filename=\"". addslashes($fileNameReal) ."\"');\n echo ";
387                       
388                        if($attachment['encoding'] == 'base64') {
389                                $headers.=" imap_base64('".$fileContent."');?>";
390                        }
391                        else if($attachment['encoding'] == 'quoted_printable_decode') {
392                                $headers.=" quoted_printable_decode('".$fileContent."');?>";
393                        }
394                        else {
395                                $headers.=" '".$fileContent."';?>";
396                        }
397                       
398                        fputs($f,$headers);
399
400                        array_push($return_attachments,array('name' => $fileName,'url' => $urlPath,'pid' =>$attachment['pid']));
401                        fclose($f);
402                }
403                imap_close($this->mbox_stream);
404                return $return_attachments;
405        }
406
407
408        function remove_accents($string) {
409                /*
410                        $array1 = array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç" , "?", "\"", "!", "@", "#", "$", "%", "š", "&", "*", "(", ")", "-", "=", "+", "Ž", "`", "[", "]", "{", "}", "~", "^", ",", "<", ">", ";", ":", "/", "?", "\\", "|", "¹", "²", "³", "£", "¢", "¬", "§", "ª", "º", "°", "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");
411                        $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");
412                        return str_replace( $array1, $array2, $string );
413                */
414                return strtr($string,
415                        "áàâãäéèêëíìîïóòôõöúùûüç?\"'!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº°ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ",
416                        "aaaaaeeeeiiiiooooouuuuc___________________________________________AAAAAEEEEIIIIOOOOOUUUUC");
417        }
418       
419
420        private function getFileType($nameFile) {
421                $strFileType = strrev(substr(strrev(strtolower($nameFile)),0,4));
422                $ContentType = "application/octet-stream";
423                if ($strFileType == ".asf")
424                        $ContentType = "video/x-ms-asf";
425                if ($strFileType == ".avi")
426                        $ContentType = "video/avi";
427                if ($strFileType == ".doc")
428                        $ContentType = "application/msword";
429                if ($strFileType == ".zip")
430                        $ContentType = "application/zip";
431                if ($strFileType == ".xls")
432                        $ContentType = "application/vnd.ms-excel";
433                if ($strFileType == ".gif")
434                        $ContentType = "image/gif";
435                if ($strFileType == ".png")
436                        $ContentType = "image/png";
437                if ($strFileType == ".jpg" || $strFileType == "jpeg")
438                        $ContentType = "image/jpeg";
439                if ($strFileType == ".wav")
440                        $ContentType = "audio/wav";
441                if ($strFileType == ".mp3")
442                        $ContentType = "audio/mpeg3";
443                if ($strFileType == ".mpg" || $strFileType == "mpeg")
444                        $ContentType = "video/mpeg";
445                if ($strFileType == ".rtf")
446                        $ContentType = "application/rtf";
447                if ($strFileType == ".htm" || $strFileType == "html")
448                        $ContentType = "text/html";
449                if ($strFileType == ".xml")
450                        $ContentType = "text/xml";
451                if ($strFileType == ".xsl")
452                        $ContentType = "text/xsl";
453                if ($strFileType == ".css")
454                        $ContentType = "text/css";
455                if ($strFileType == ".php")
456                        $ContentType = "text/php";
457                if ($strFileType == ".asp")
458                        $ContentType = "text/asp";
459                if ($strFileType == ".pdf")
460                        $ContentType = "application/pdf";
461                if ($strFileType == ".txt")
462                        $ContentType = "text/plain";
463                if ($strFileType == ".log")
464                        $ContentType = "text/plain";
465                if ($strFileType == ".wmv")
466                        $ContentType = "video/x-ms-wmv";
467                if ($strFileType == ".sxc")
468                        $ContentType = "application/vnd.sun.xml.calc";
469                if ($strFileType == ".odt")
470                        $ContentType = "application/vnd.oasis.opendocument.text";
471                if ($strFileType == ".stc")
472                        $ContentType = "application/vnd.sun.xml.calc.template";
473                if ($strFileType == ".sxd")
474                        $ContentType = "application/vnd.sun.xml.draw";
475                if ($strFileType == ".std")
476                        $ContentType = "application/vnd.sun.xml.draw.template";
477                if ($strFileType == ".sxi")
478                        $ContentType = "application/vnd.sun.xml.impress";
479                if ($strFileType == ".sti")
480                        $ContentType = "application/vnd.sun.xml.impress.template";
481                if ($strFileType == ".sxm")
482                        $ContentType = "application/vnd.sun.xml.math";
483                if ($strFileType == ".sxw")
484                        $ContentType = "application/vnd.sun.xml.writer";
485                if ($strFileType == ".sxq")
486                        $ContentType = "application/vnd.sun.xml.writer.global";
487                if ($strFileType == ".stw")
488                        $ContentType = "application/vnd.sun.xml.writer.template";
489                if ($strFileType == ".ps")
490                        $ContentType = "application/postscript";
491                if ($strFileType == ".pps")
492                        $ContentType = "application/vnd.ms-powerpoint";
493                if ($strFileType == ".odt")
494                        $ContentType = "application/vnd.oasis.opendocument.text";
495                if ($strFileType == ".ott")
496                        $ContentType = "application/vnd.oasis.opendocument.text-template";
497                if ($strFileType == ".oth")
498                        $ContentType = "application/vnd.oasis.opendocument.text-web";
499                if ($strFileType == ".odm")
500                        $ContentType = "application/vnd.oasis.opendocument.text-master";
501                if ($strFileType == ".odg")
502                        $ContentType = "application/vnd.oasis.opendocument.graphics";
503                if ($strFileType == ".otg")
504                        $ContentType = "application/vnd.oasis.opendocument.graphics-template";
505                if ($strFileType == ".odp")
506                        $ContentType = "application/vnd.oasis.opendocument.presentation";
507                if ($strFileType == ".otp")
508                        $ContentType = "application/vnd.oasis.opendocument.presentation-template";
509                if ($strFileType == ".ods")
510                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet";
511                if ($strFileType == ".ots")
512                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet-template";
513                if ($strFileType == ".odc")
514                        $ContentType = "application/vnd.oasis.opendocument.chart";
515                if ($strFileType == ".odf")
516                        $ContentType = "application/vnd.oasis.opendocument.formula";
517                if ($strFileType == ".odi")
518                        $ContentType = "application/vnd.oasis.opendocument.image";
519                if ($strFileType == ".ndl")
520                        $ContentType = "application/vnd.lotus-notes";
521                if ($strFileType == ".eml")
522                        $ContentType = "text/plain";
523                return $ContentType;
524        }
525       
526        function download_all_attachments($params) {
527               
528                $id_number = $params['num_msg'];               
529                $attachments =unserialize(rawurldecode($params['s_attachments']));
530               
531                $tempDir = $this->tempDir;
532                $tempSubDir = $_SESSION['phpgw_session']['session_id'];
533                $fileNames = '';
534                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
535                $this-> folder = $params['folder'];
536                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
537                $this->connectImap();
538                include("class.imap_attachment.inc.php");
539                $imap_attachment = new imap_attachment();
540                $attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
541               
542                $fileNames = Array();
543                       
544                for ($i = 0; $i < count($attachments); $i++)
545                {
546                   $attachments[$i]['name'] = $this->remove_accents($attachments[$i]['name']);
547                   $fileNames[$i] = $attachments[$i]['name'];
548                }
549
550                for ($i = 0; $i < count($attachments); $i++)
551                {
552                        $fileName = $attachments[$i]['name'];
553                        $result = array_keys($fileNames, $fileName);
554
555                        // Detecta duplicatas
556                        if (count($result) > 1)
557                        {
558                            for ($j = 1; $j < count($result); $j++)
559                            {
560                                $replacement = '('.$j.')$0';
561                                if (preg_match('/\.\w{2,4}$/', $fileName))
562                                {
563                                    $fileNames[$result[$j]] = preg_replace('/\.\w{2,4}$/', $replacement, $fileName);
564                                }
565                                else
566                                {
567                                    $fileNames[$result[$j]] .= "($j)";
568                                }
569                                $attachments[$result[$j]]['name'] = $fileNames[$result[$j]];
570                            }
571                        }
572                        // Fim detecta duplicatas
573
574                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
575                        if(!$f)
576                                return False;                   
577                                               
578                        $fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachments[$i]['pid'], FT_UID);
579                        if($attachments[$i]['encoding'] == 'base64')
580                                fputs($f,imap_base64($fileContent));
581                        else           
582                                fputs($f,$fileContent);
583                               
584                        fclose($f);
585               
586                }
587                imap_close($this->mbox_stream);
588                $nameFileZip = '';
589               
590                if(!empty($fileNames)) {
591                        $nameFileZip = $this -> createFileZip($fileNames, $tempDir . '/'.$tempSubDir);                                         
592                        if($nameFileZip)
593                                $file =  $tempDir . '/'.$tempSubDir.'/'.$nameFileZip;
594                        else {
595                                $file = false;
596                        }
597                }
598                else
599                        $file = false; 
600                return $file;
601        }
602
603        function getHeader($msg_number){                       
604                return imap_fetchheader($this->mbox_stream, $msg_number, FT_UID);
605        }
606       
607        function getBody($msg_number){
608                $header = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number), 80, 255);
609                $body = imap_body($this->mbox_stream, $msg_number, FT_UID);
610                if(($header->Unseen == 'U') || ($header->Recent == 'N')){
611                        imap_clearflag_full($this->mbox_stream, $msg_number, "\\Seen", ST_UID);
612                }
613                return $body;
614        }
615
616        function decode_subject($string){
617                if ((strpos(strtolower($string), '=?iso-8859-1') !== false)
618                        || (strpos(strtolower($string), '=?windows-1252') !== false)){
619                        $elements = imap_mime_header_decode($string);
620                        foreach ($elements as $el)
621                                $return .= $el->text;
622                }
623                else if (strpos(strtolower($string), '=?utf-8') !== false) {
624                        $elements = imap_mime_header_decode($string);
625                        foreach ($elements as $el){
626                                $charset = $el->charset;
627                                $text    = $el->text;
628                                if(!strcasecmp($charset, "utf-8") ||
629                                !strcasecmp($charset, "utf-7")) {
630                                $text = iconv($charset, "ISO-8859-1", $text);
631                        }
632                        $return .= $text;
633                        }
634                }
635                else
636                        $return = $string;
637
638                return $this->remove_accents($return);         
639        }
640}
641// END CLASS
642?>
Note: See TracBrowser for help on using the repository browser.