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

Revision 5079, 22.9 KB checked in by airton, 13 years ago (diff)

Ticket #2266 - Atualizar documentacao dos arquivos PHP

  • 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       
20        /**
21        * Construtor da classe ExportEml
22        *
23        * @license    http://www.gnu.org/copyleft/gpl.html GPL
24        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
25        * @sponsor    Caixa Econômica Federal
26        */
27        function ExportEml() {
28           
29                //TODO: modificar o caminho hardcodificado '/tmp' para o definido na configuracao do expresso
30                //$this->tempDir = $GLOBALS['phpgw_info']['server']['temp_dir'];
31                $this->tempDir = '/tmp';
32        }
33       
34        function connectImap(){
35       
36                $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
37                $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
38                $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
39                $imap_port      = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
40               
41                if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
42                {
43                        $imap_options = '/tls/novalidate-cert';
44                }
45                else
46                {
47                        $imap_options = '/notls/novalidate-cert';
48                }
49                $this->mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$this->folder, $username, $password);
50        }
51       
52        //export message to EML Format
53        function parseEml($header, $body)       
54        {               
55                $sEmailHeader = $header;
56                $sEmailBody = $body;
57                $sEMail = $sEmailHeader . "\r\n\r\n" . $sEmailBody;             
58                return $sEMail;
59        }
60       
61        // create EML File.
62        // Funcao alterada para tratar a exportacao
63        // de mensagens arquivadas localmente.
64        // Rommel Cysne (rommel.cysne@serpro.gov.br)
65        // em 17/12/2008.
66        function createFileEml($sEMLData, $tempDir, $id, $subject=false, $i=false)
67    {
68        if($id)
69        {
70            $header    = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $id), 80, 255);
71            $subject = $this->decode_subject($header->fetchsubject);
72           
73            if (strlen($subject) > 60)
74                $subject = substr($subject, 0, 59);
75 
76                        //$subject = ereg_replace('/', '\'', $subject);
77                        $from = "áàâãäéèêëíìîïóòôõöúùûüç?\"!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº° .ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ";
78                        $to =   "aaaaaeeeeiiiiooooouuuuc______________________________________________AAAAAEEEEIIIIOOOOOUUUUC";
79                        $subject = strtr($subject,$from,$to);
80
81                        $subject = eregi_replace("[^a-zA-Z0-9_]", "_", $subject);
82                        $file = $subject."_".$id.".eml";
83                } else{
84                        // Se mensagem for arquivada localmente, $subject (assunto da mensagem)
85                        // sera passado para compor o nome do arquivo .eml;
86
87                        if($subject && $i){
88                                $from = "áàâãäéèêëíìîïóòôõöúùûüç?\"!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº° .ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ";
89                                $to =   "aaaaaeeeeiiiiooooouuuuc______________________________________________AAAAAEEEEIIIIOOOOOUUUUC";
90                                $subject = strtr($subject,$from,$to);
91
92                                $subject = eregi_replace("[^a-zA-Z0-9_]", "_", $subject);
93
94                                // é necessário que a sessão faça parte do nome do arquivo para que o mesmo não venha vazio o.O
95                                $file = $subject."_".$i."_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".eml"; 
96                        } else{
97                                $file = "email_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".eml";
98                }   
99        }
100       
101        $f = fopen($tempDir.'/'.$file,"w");
102        if(!$f)
103            return False;
104       
105        fputs($f,$sEMLData);
106        fclose($f);
107       
108        return $file;
109    }
110
111        function createFileZip($files, $tempDir){               
112                $tmp_zip_filename = "email_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".zip";
113               
114                if (!empty($files))
115                {
116                    if (is_array($files))
117                    {
118                        for ($i=0; $i < count($files); $i++)
119                        {
120                            $files[$i] = escapeshellarg($files[$i]);
121                        }
122                        $files = implode(' ', $files);
123                    }
124                    else
125                    {
126                        $files = escapeshellcmd($files);
127                    }
128                }
129               
130                $command = "cd " . escapeshellarg($tempDir) . " && nice zip -m9 " . escapeshellarg($tmp_zip_filename) . " " .  $files;
131                if(!exec($command)) {
132                        $command = "cd " .  escapeshellarg($tempDir) . " && rm ".$files." ". escapeshellarg($tmp_zip_filename);
133                        exec($command);
134                        return null;
135                }
136               
137                return $tmp_zip_filename;
138                               
139        }
140
141        function export_all($params){
142               
143                $this->folder = $params['folder'];
144                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
145                $fileNames = "";
146                $tempDir = $this->tempDir;
147                $this->connectImap();
148               
149                $msgs = imap_search($this->mbox_stream,"ALL",SE_UID);
150                if($msgs){
151                        foreach($msgs as $nMsgs){
152                                $header         = $this-> getHeader($nMsgs);                                                                   
153                                $body           = $this-> getBody($nMsgs);                     
154                                $sEMLData       = $this -> parseEml($header, $body);
155                                $fileName       = $this -> CreateFileEml($sEMLData, $tempDir,$nMsgs);
156                                if(!$fileName)  {
157                                        $error = True;                                 
158                                        break;
159                                }
160                                else
161                                        $fileNames .= "\"".$fileName."\" ";                     
162                               
163                        }
164                       
165                        imap_close($this->mbox_stream);
166                       
167                        $nameFileZip = 'False';                 
168                        if($fileNames && !$error) {                     
169                                $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
170                                if($nameFileZip)                       
171                                        $file = $tempDir.'/'.$nameFileZip;
172                                else {
173                                        $file = false;
174                                }                                                               
175                        }
176                        else
177                                $file = false;
178                }else{
179                        $file["empty_folder"] = true;
180                }
181                return $file;
182               
183        }
184
185        // Funcao alterada para tratar a exportacao
186        // de mensagens arquivadas localmente.
187        // Rommel Cysne (rommel.cysne@serpro.gov.br)
188        // em 17/12/2008.
189        // 
190        // Funcao alterada para que, quando houver 
191        // apenas um arquivo a ser exportado,
192        // não seja criado em zip
193        function makeAll($params) {
194                // Exportacao de mensagens arquivadas localmente
195                if($params['l_msg'] == "t")
196                {
197                // Recebe todos os subjects e bodies das mensagens locais selecionadas para exportacao
198                // e gera arrays com os conteudos separados;
199                $array_mesgs = explode('@@',$params['mesgs']);
200                $array_subjects = explode('@@',$params['subjects']);
201            $array_ids = explode(',', $params['msgs_to_export']);
202                        $tempDir = $this->tempDir;
203                       
204                        include_once("class.imap_functions.inc.php");
205                        $imapf = new imap_functions();
206
207                        // quando houver apenas um arquivo, exporta o .eml sem coloca-lo em zip
208                        if (count($array_ids)==1)
209                        {
210                                $sEMLData=$imapf->treat_base64_from_post($array_mesgs[0]);
211                                $fileName=$this->CreateFileEml($sEMLData, $tempDir,'',$array_subjects[0],"offline");
212                                return $tempDir.'/'.$fileName;
213                        }
214
215                        // Para cada mensagem selecionada sera gerado um arquivo .eml cujo titulo sera o assunto (subject) da mesma;
216                foreach($array_ids as $i=>$id) {
217                                $sEMLData=$imapf->treat_base64_from_post($array_mesgs[$i]);
218                                $fileName=$this->CreateFileEml($sEMLData, $tempDir,'',$array_subjects[$i],$i);
219                                if(!$fileName){
220                                        $error = True;
221                                        break;
222                                } else{
223                                        $fileNames .= "\"".$fileName."\" ";
224                                }
225                        }
226                        $nameFileZip = 'False';
227                        if($fileNames && !$error) {
228                                $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
229                                if($nameFileZip){
230                                        $file = $tempDir.'/'.$nameFileZip;
231                                } else{
232                                        $file = false;
233                                }
234
235                        } else{
236                                $file = false;
237                        }
238
239            return $file;
240               
241                } else
242                // Exportacao de mensagens da caixa de entrada (imap) - processo original do Expresso
243                {
244                        $this-> folder = $params['folder'];
245                        $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
246                        $array_ids = explode(',', $params['msgs_to_export']);
247                        $error = False;
248                        $fileNames = "";
249                        $tempDir = $this->tempDir;
250                        $this->connectImap();
251
252                        // quando houver apenas um arquivo, exporta o .eml sem coloca-lo em zip
253                        if (count($array_ids)==1)
254                        {
255                                $header         = $this->getHeader($array_ids[0]);                                                                                     
256                                $body           = $this->getBody($array_ids[0]);                       
257                                $sEMLData       = $this->parseEml($header, $body);                     
258                                $fileName       = $this->CreateFileEml($sEMLData, $tempDir, $array_ids[0]."_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]);
259
260                                imap_close($this->mbox_stream);
261                                if (!$fileName) {
262                                        return false;
263                                } else {
264                                        return $tempDir.'/'.$fileName;
265                                }
266                        }
267
268                        for($i = 0; $i < count($array_ids); $i++)
269                        {
270                                $header         = $this-> getHeader($array_ids[$i]);                                                                                   
271                                $body           = $this-> getBody($array_ids[$i]);                     
272                                $sEMLData       = $this -> parseEml($header, $body);                   
273                                $fileName       = $this -> CreateFileEml($sEMLData, $tempDir, $array_ids[$i]);
274
275                                if(!$fileName)
276                                {
277                                        $error = True;                                 
278                                        break;
279                                } else {
280                                        $fileNames .= "\"".$fileName."\" ";                     
281                                }
282                        }
283                        imap_close($this->mbox_stream);
284
285                        $nameFileZip = 'False';                 
286                        if($fileNames && !$error)
287                        {
288                                $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
289                                if($nameFileZip)
290                                {               
291                                        $file = $tempDir.'/'.$nameFileZip;
292                                } else {
293                                        $file = false;
294                                }                                                               
295                        }
296                        else
297                        {
298                                $file = false;
299                        }
300
301                        return $file;
302                }
303    }
304
305        function export_msg($params) {
306                $this-> folder = $params['folder'];
307                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
308                $id_number = $params['msgs_to_export'];
309                $tempDir = $this->tempDir;
310                $this->connectImap();
311                $header         = $this-> getHeader($id_number);
312                $body           = $this-> getBody($id_number);
313               
314                $file = "source_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".php";
315                $f = fopen($tempDir.'/'.$file,"w");
316                fputs($f,$header ."\r\n\r\n". $body);
317                fclose($f);
318               
319                imap_close($this->mbox_stream);
320                return $tempDir.'/'.$file;
321        }
322
323    function export_msg_data($id_msg,$folder) {
324                $this->folder = $folder;
325                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
326
327                $this->connectImap();
328                $header         = $this-> getHeader($id_msg);
329                $body           = $this-> getBody($id_msg);
330
331                $msg_data = $header ."\r\n\r\n". $body;
332
333                imap_close($this->mbox_stream);
334                return $msg_data;
335        }
336
337                function export_to_archive($id_msg,$folder) {
338                $this-> folder = $folder;
339                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
340                   
341                $tempDir = $this->tempDir;
342                                 
343                $this->connectImap();
344                $header         = $this-> getHeader($id_msg);
345                $body           = $this-> getBody($id_msg);
346                $name = md5($_SESSION[ 'phpgw_session' ][ 'session_id' ].microtime());
347               
348                //$file = $_SESSION[ 'phpgw_session' ][ 'session_id' ].$name;
349                $file = "source_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]."_".time().".php"; //source_[sessao]_[timestamp].php
350                $f = fopen($tempDir . '/'.$file,"w");
351                fputs($f,utf8_encode($header) ."\r\n\r\n". utf8_encode($body));
352                fclose($f);
353                                 
354                imap_close($this->mbox_stream);
355                return "inc/gotodownload.php?idx_file=".$tempDir . '/'.$file."&newfilename=fonte_da_mensagem.txt";
356                                 
357        }
358
359        function get_attachments_in_array($params) {
360                $return_attachments = array();
361
362                $id_number = $params['num_msg'];               
363                $attachments =unserialize(rawurldecode($params['s_attachments']));
364               
365                $tempDir = dirname( __FILE__ ) . '/../tmpLclAtt';
366                $tempSubDir = md5(microtime());
367                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
368               
369                $this-> folder = $params['folder'];
370                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
371                $this->connectImap();
372
373                include_once("class.imap_attachment.inc.php");
374
375                $imap_attachment = new imap_attachment();
376                $attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
377                foreach($attachments as $i => $attachment){
378                        if($i && $i == 'names')
379                                continue;
380                        $fileNameReal = $this->remove_accents($attachment['name']);
381                        $ContentType = $this->getFileType($fileNameReal);
382                        $fileName = $fileNameReal . ".php";
383                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
384                        if(!$f)
385                                return $tempDir . '/'.$tempSubDir.'/'.$fileName;                       
386
387                        $fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachment['pid'], FT_UID);
388                        $urlPath = 'tmpLclAtt/'.$tempSubDir.'/'.$fileName;
389                       
390                        $headers = "<?php header('Content-Type: ".$ContentType."');
391                                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
392                                header('Pragma: public');
393                                header('Expires: 0'); // set expiration time
394                                header('Content-Disposition: attachment; filename=\"". addslashes($fileNameReal) ."\"');\n echo ";
395                       
396                        if($attachment['encoding'] == 'base64') {
397                                $headers.=" imap_base64('".$fileContent."');?>";
398                        }
399                        else if($attachment['encoding'] == 'quoted_printable_decode') {
400                                $headers.=" quoted_printable_decode('".$fileContent."');?>";
401                        }
402                        else {
403                                $headers.=" '".$fileContent."';?>";
404                        }
405                       
406                        fputs($f,$headers);
407
408                        array_push($return_attachments,array('name' => $fileName,'url' => $urlPath,'pid' =>$attachment['pid']));
409                        fclose($f);
410                }
411                imap_close($this->mbox_stream);
412                return $return_attachments;
413        }
414
415
416        function remove_accents($string) {
417                /*
418                        $array1 = array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç" , "?", "\"", "!", "@", "#", "$", "%", "š", "&", "*", "(", ")", "-", "=", "+", "Ž", "`", "[", "]", "{", "}", "~", "^", ",", "<", ">", ";", ":", "/", "?", "\\", "|", "¹", "²", "³", "£", "¢", "¬", "§", "ª", "º", "°", "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");
419                        $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");
420                        return str_replace( $array1, $array2, $string );
421                */
422                return strtr($string,
423                        "áàâãäéèêëíìîïóòôõöúùûüç?\"'!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº°ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ",
424                        "aaaaaeeeeiiiiooooouuuuc___________________________________________AAAAAEEEEIIIIOOOOOUUUUC");
425        }
426       
427
428        private function getFileType($nameFile) {
429                $strFileType = strrev(substr(strrev(strtolower($nameFile)),0,4));
430                $ContentType = "application/octet-stream";
431                if ($strFileType == ".asf")
432                        $ContentType = "video/x-ms-asf";
433                if ($strFileType == ".avi")
434                        $ContentType = "video/avi";
435                if ($strFileType == ".doc")
436                        $ContentType = "application/msword";
437                if ($strFileType == ".zip")
438                        $ContentType = "application/zip";
439                if ($strFileType == ".xls")
440                        $ContentType = "application/vnd.ms-excel";
441                if ($strFileType == ".gif")
442                        $ContentType = "image/gif";
443                if ($strFileType == ".png")
444                        $ContentType = "image/png";
445                if ($strFileType == ".jpg" || $strFileType == "jpeg")
446                        $ContentType = "image/jpeg";
447                if ($strFileType == ".wav")
448                        $ContentType = "audio/wav";
449                if ($strFileType == ".mp3")
450                        $ContentType = "audio/mpeg3";
451                if ($strFileType == ".mpg" || $strFileType == "mpeg")
452                        $ContentType = "video/mpeg";
453                if ($strFileType == ".rtf")
454                        $ContentType = "application/rtf";
455                if ($strFileType == ".htm" || $strFileType == "html")
456                        $ContentType = "text/html";
457                if ($strFileType == ".xml")
458                        $ContentType = "text/xml";
459                if ($strFileType == ".xsl")
460                        $ContentType = "text/xsl";
461                if ($strFileType == ".css")
462                        $ContentType = "text/css";
463                if ($strFileType == ".php")
464                        $ContentType = "text/php";
465                if ($strFileType == ".asp")
466                        $ContentType = "text/asp";
467                if ($strFileType == ".pdf")
468                        $ContentType = "application/pdf";
469                if ($strFileType == ".txt")
470                        $ContentType = "text/plain";
471                if ($strFileType == ".log")
472                        $ContentType = "text/plain";
473                if ($strFileType == ".wmv")
474                        $ContentType = "video/x-ms-wmv";
475                if ($strFileType == ".sxc")
476                        $ContentType = "application/vnd.sun.xml.calc";
477                if ($strFileType == ".odt")
478                        $ContentType = "application/vnd.oasis.opendocument.text";
479                if ($strFileType == ".stc")
480                        $ContentType = "application/vnd.sun.xml.calc.template";
481                if ($strFileType == ".sxd")
482                        $ContentType = "application/vnd.sun.xml.draw";
483                if ($strFileType == ".std")
484                        $ContentType = "application/vnd.sun.xml.draw.template";
485                if ($strFileType == ".sxi")
486                        $ContentType = "application/vnd.sun.xml.impress";
487                if ($strFileType == ".sti")
488                        $ContentType = "application/vnd.sun.xml.impress.template";
489                if ($strFileType == ".sxm")
490                        $ContentType = "application/vnd.sun.xml.math";
491                if ($strFileType == ".sxw")
492                        $ContentType = "application/vnd.sun.xml.writer";
493                if ($strFileType == ".sxq")
494                        $ContentType = "application/vnd.sun.xml.writer.global";
495                if ($strFileType == ".stw")
496                        $ContentType = "application/vnd.sun.xml.writer.template";
497                if ($strFileType == ".ps")
498                        $ContentType = "application/postscript";
499                if ($strFileType == ".pps")
500                        $ContentType = "application/vnd.ms-powerpoint";
501                if ($strFileType == ".odt")
502                        $ContentType = "application/vnd.oasis.opendocument.text";
503                if ($strFileType == ".ott")
504                        $ContentType = "application/vnd.oasis.opendocument.text-template";
505                if ($strFileType == ".oth")
506                        $ContentType = "application/vnd.oasis.opendocument.text-web";
507                if ($strFileType == ".odm")
508                        $ContentType = "application/vnd.oasis.opendocument.text-master";
509                if ($strFileType == ".odg")
510                        $ContentType = "application/vnd.oasis.opendocument.graphics";
511                if ($strFileType == ".otg")
512                        $ContentType = "application/vnd.oasis.opendocument.graphics-template";
513                if ($strFileType == ".odp")
514                        $ContentType = "application/vnd.oasis.opendocument.presentation";
515                if ($strFileType == ".otp")
516                        $ContentType = "application/vnd.oasis.opendocument.presentation-template";
517                if ($strFileType == ".ods")
518                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet";
519                if ($strFileType == ".ots")
520                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet-template";
521                if ($strFileType == ".odc")
522                        $ContentType = "application/vnd.oasis.opendocument.chart";
523                if ($strFileType == ".odf")
524                        $ContentType = "application/vnd.oasis.opendocument.formula";
525                if ($strFileType == ".odi")
526                        $ContentType = "application/vnd.oasis.opendocument.image";
527                if ($strFileType == ".ndl")
528                        $ContentType = "application/vnd.lotus-notes";
529                if ($strFileType == ".eml")
530                        $ContentType = "text/plain";
531                return $ContentType;
532        }
533       
534        function download_all_attachments($params) {
535               
536                $id_number = $params['num_msg'];               
537                $attachments =unserialize(rawurldecode($params['s_attachments']));
538               
539                $tempDir = $this->tempDir;
540                $tempSubDir = $_SESSION['phpgw_session']['session_id'];
541                $fileNames = '';
542                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
543                $this-> folder = $params['folder'];
544                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
545                $this->connectImap();
546                include("class.imap_attachment.inc.php");
547                $imap_attachment = new imap_attachment();
548                $attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
549               
550                $fileNames = Array();
551                       
552                for ($i = 0; $i < count($attachments); $i++)
553                {
554                   $attachments[$i]['name'] = $this->remove_accents($attachments[$i]['name']);
555                   $fileNames[$i] = $attachments[$i]['name'];
556                }
557
558                for ($i = 0; $i < count($attachments); $i++)
559                {
560                        $fileName = $attachments[$i]['name'];
561                        $result = array_keys($fileNames, $fileName);
562
563                        // Detecta duplicatas
564                        if (count($result) > 1)
565                        {
566                            for ($j = 1; $j < count($result); $j++)
567                            {
568                                $replacement = '('.$j.')$0';
569                                if (preg_match('/\.\w{2,4}$/', $fileName))
570                                {
571                                    $fileNames[$result[$j]] = preg_replace('/\.\w{2,4}$/', $replacement, $fileName);
572                                }
573                                else
574                                {
575                                    $fileNames[$result[$j]] .= "($j)";
576                                }
577                                $attachments[$result[$j]]['name'] = $fileNames[$result[$j]];
578                            }
579                        }
580                        // Fim detecta duplicatas
581
582                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
583                        if(!$f)
584                                return False;                   
585                                               
586                        $fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachments[$i]['pid'], FT_UID);
587                        if($attachments[$i]['encoding'] == 'base64')
588                                fputs($f,imap_base64($fileContent));
589                        else           
590                                fputs($f,$fileContent);
591                               
592                        fclose($f);
593               
594                }
595                imap_close($this->mbox_stream);
596                $nameFileZip = '';
597               
598                if(!empty($fileNames)) {
599                        $nameFileZip = $this -> createFileZip($fileNames, $tempDir . '/'.$tempSubDir);                                         
600                        if($nameFileZip)
601                                $file =  $tempDir . '/'.$tempSubDir.'/'.$nameFileZip;
602                        else {
603                                $file = false;
604                        }
605                }
606                else
607                        $file = false; 
608                return $file;
609        }
610
611        function getHeader($msg_number){                       
612                return imap_fetchheader($this->mbox_stream, $msg_number, FT_UID);
613        }
614       
615        function getBody($msg_number){
616                $header = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number), 80, 255);
617                $body = imap_body($this->mbox_stream, $msg_number, FT_UID);
618                if(($header->Unseen == 'U') || ($header->Recent == 'N')){
619                        imap_clearflag_full($this->mbox_stream, $msg_number, "\\Seen", ST_UID);
620                }
621                return $body;
622        }
623
624        function decode_subject($string){
625                if ((strpos(strtolower($string), '=?iso-8859-1') !== false)
626                        || (strpos(strtolower($string), '=?windows-1252') !== false)){
627                        $elements = imap_mime_header_decode($string);
628                        foreach ($elements as $el)
629                                $return .= $el->text;
630                }
631                else if (strpos(strtolower($string), '=?utf-8') !== false) {
632                        $elements = imap_mime_header_decode($string);
633                        foreach ($elements as $el){
634                                $charset = $el->charset;
635                                $text    = $el->text;
636                                if(!strcasecmp($charset, "utf-8") ||
637                                !strcasecmp($charset, "utf-7")) {
638                                $text = iconv($charset, "ISO-8859-1", $text);
639                        }
640                        $return .= $text;
641                        }
642                }
643                else
644                        $return = $string;
645
646                return $this->remove_accents($return);         
647        }
648}
649// END CLASS
650?>
Note: See TracBrowser for help on using the repository browser.