source: branches/2.2/expressoMail1_2/inc/class.exporteml.inc.php @ 3273

Revision 3273, 18.8 KB checked in by brunocosta, 14 years ago (diff)

Ticket #1286 - A conversão de charsets correta foi colocada em algumas nas funções.

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