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

Revision 711, 16.1 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #469

  • 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    function createFileEml($sEMLData, $tempDir, $id) 
47    {
48        if($id)
49        {
50            $header    = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $id), 80, 255);
51            $subject = $this->decode_subject($header->fetchsubject);
52           
53            if (strlen($subject) > 60)
54                $subject = substr($subject, 0, 59);
55 
56            $subject = ereg_replace('/', '\'', $subject);           
57            $file =    $subject."_".$id.".eml";
58        }   
59        else{
60            $file =    "email_".md5(microtime()).".eml";
61        }
62       
63        $f = fopen($tempDir.'/'.$file,"w");
64        if(!$f)
65            return False;
66       
67        fputs($f,$sEMLData);
68        fclose($f);
69       
70        return $file;
71    }
72
73        function createFileZip($files, $tempDir){               
74                $tmp_zip_filename =     "email_".md5(microtime()).".zip";
75                $command = "cd " . $tempDir . "; nice zip -m " . $tmp_zip_filename . " " . $files;                     
76                if(!exec($command)) {
77                        $command = 'cd ' . $tempDir . '; rm '.$files;
78                        exec($command);
79                        return null;
80                }
81               
82                return $tmp_zip_filename;
83                               
84        }
85
86        function export_all($params){
87               
88                $this->folder = $params['folder'];
89                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
90                $fileNames = "";
91                $tempDir = ini_get("session.save_path");
92                $this->connectImap();
93               
94                $msgs = imap_search($this->mbox_stream,"ALL",SE_UID);
95                foreach($msgs as $nMsgs){
96                        $header         = $this-> getHeader($nMsgs);                                                                   
97                        $body           = $this-> getBody($nMsgs);                     
98                        $sEMLData       = $this -> parseEml($header, $body);
99                        $fileName       = $this -> CreateFileEml($sEMLData, $tempDir,$nMsgs);
100                        if(!$fileName)  {
101                                $error = True;                                 
102                                break;
103                        }
104                        else
105                                $fileNames .= "\"".$fileName."\" ";                     
106                       
107                }
108                imap_close($this->mbox_stream);
109               
110                $nameFileZip = 'False';                 
111                if($fileNames && !$error) {                     
112                        $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
113                        if($nameFileZip)                       
114                                $file = $tempDir.'/'.$nameFileZip;
115                        else {
116                                $file = false;
117                        }                                                               
118                }
119                else
120                        $file = false;
121                       
122                return $file;
123               
124        }
125
126        function makeAll($params) {
127               
128                $this-> folder = $params['folder'];
129                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
130                $array_ids = explode(',', $params['msgs_to_export']);   
131                $error = False;         
132                $fileNames = "";
133                $tempDir = ini_get("session.save_path");
134                $this->connectImap();
135                               
136                for($i = 0; $i < count($array_ids); $i++) {
137                               
138                        $header         = $this-> getHeader($array_ids[$i]);                                                                                   
139                        $body           = $this-> getBody($array_ids[$i]);                     
140                        $sEMLData       = $this -> parseEml($header, $body);                   
141                        $fileName       = $this -> CreateFileEml($sEMLData, $tempDir, $array_ids[$i]);
142                       
143                        if(!$fileName)  {
144                                $error = True;                                 
145                                break;
146                        }
147                        else
148                                $fileNames .= "\"".$fileName."\" ";                     
149                       
150                }
151                imap_close($this->mbox_stream);
152               
153               
154                $nameFileZip = 'False';                 
155                if($fileNames && !$error) {                     
156                        $nameFileZip = $this -> createFileZip($fileNames, $tempDir);
157                        if($nameFileZip)                       
158                                $file = $tempDir.'/'.$nameFileZip;
159                        else {
160                                $file = false;
161                        }                                                               
162                }
163                else
164                        $file = false;
165                       
166                return $file;
167        }
168
169        function export_msg($params) {
170                $this-> folder = $params['folder'];
171                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
172                $id_number = $params['msgs_to_export'];
173                $tempDir = ini_get("session.save_path");
174               
175                $this->connectImap();
176                $header         = $this-> getHeader($id_number);
177                $body           = $this-> getBody($id_number);
178               
179                $file = "source_".md5(microtime()).".txt";
180                $f = fopen($tempDir.'/'.$file,"w");
181                fputs($f,$header ."\r\n\r\n". $body);
182                fclose($f);
183               
184                imap_close($this->mbox_stream);
185                return $tempDir.'/'.$file;
186        }
187
188        function export_to_archive($id_msg,$folder) {
189                $this->folder = $folder;
190                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
191                $tempDir = dirname( __FILE__ ) . '/../tmpLclAtt';
192               
193                $phpheader = "<?php header('Content-Type: text/plain');
194                                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
195                                header('Pragma: public');
196                                header('Expires: 0'); // set expiration time
197                                header('Content-Disposition: attachment; filename=\"fonte_da_mensagem.txt\"');?>";
198               
199                $this->connectImap();
200                $header         = $this-> getHeader($id_msg);
201                $body           = $this-> getBody($id_msg);
202               
203                $file = "source_".md5(microtime()).".php";
204                $f = fopen($tempDir.'/'.$file,"w");
205                fputs($f,$phpheader.$header ."\r\n\r\n". $body);
206                fclose($f);
207                $urlPath = 'tmpLclAtt/'.$file;
208               
209                imap_close($this->mbox_stream);
210                return $urlPath;
211        }
212
213        function remove_accents($string) {
214                /*
215                        $array1 = array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç" , "?", "\"", "!", "@", "#", "$", "%", "š", "&", "*", "(", ")", "-", "=", "+", "Ž", "`", "[", "]", "{", "}", "~", "^", ",", "<", ">", ";", ":", "/", "?", "\\", "|", "¹", "²", "³", "£", "¢", "¬", "§", "ª", "º", "°", "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");
216                        $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");
217                        return str_replace( $array1, $array2, $string );
218                */
219                return strtr($string,
220                        "áàâãäéèêëíìîïóòôõöúùûüç?\"!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº°ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ",
221                        "aaaaaeeeeiiiiooooouuuuc__________________________________________AAAAAEEEEIIIIOOOOOUUUUC");
222        }
223       
224        function get_attachments_in_array($params) {
225                $return_attachments = array();
226
227                $id_number = $params['num_msg'];               
228                $attachments =unserialize(rawurldecode($params['s_attachments']));
229               
230                $tempDir = dirname( __FILE__ ) . '/../tmpLclAtt';
231//              $tempDir = $_SERVER["DOCUMENT_ROOT"]."tmpLclAtt";
232                $tempSubDir = md5(microtime());
233                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
234               
235                $this-> folder = $params['folder'];
236                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
237                $this->connectImap();
238
239                include_once("class.imap_attachment.inc.php");
240
241                $imap_attachment = new imap_attachment();
242                $attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
243               
244
245               
246                foreach($attachments as $i => $attachment){
247                        if($i && $i == 'names')
248                                continue;
249                        $fileNameReal = $this->remove_accents($attachment['name']);
250                        $ContentType = $this->getFileType($fileNameReal);
251                        $fileName = $fileNameReal . ".php";
252                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
253                        if(!$f)
254                                return $tempDir . '/'.$tempSubDir.'/'.$fileName;                       
255
256                        $fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachment['pid'], FT_UID);
257                        $urlPath = 'tmpLclAtt/'.$tempSubDir.'/'.$fileName;
258                       
259                        $headers = "<?php header('Content-Type: ".$ContentType."');
260                                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
261                                header('Pragma: public');
262                                header('Expires: 0'); // set expiration time
263                                header('Content-Disposition: attachment; filename=\"". addslashes($fileNameReal) ."\"');\n echo ";
264                       
265                        if($attachment['encoding'] == 'base64') {
266                                $headers.=" imap_base64('".$fileContent."');?>";
267                        }
268                        else if($attachment['encoding'] == 'quoted_printable_decode') {
269                                $headers.=" quoted_printable_decode('".$fileContent."');?>";
270                        }
271                        else {
272                                $headers.=" '".$fileContent."';?>";
273                        }
274                       
275                        fputs($f,$headers);
276
277                        array_push($return_attachments,array('name' => $fileName,'url' => $urlPath,'pid' =>$attachment['pid']));
278                        fclose($f);
279                }
280                imap_close($this->mbox_stream);
281                return $return_attachments;
282        }
283       
284        private function getFileType($nameFile) {
285                $strFileType = strrev(substr(strrev(strtolower($nameFile)),0,4));
286                $ContentType = "application/octet-stream";
287                if ($strFileType == ".asf")
288                        $ContentType = "video/x-ms-asf";
289                if ($strFileType == ".avi")
290                        $ContentType = "video/avi";
291                if ($strFileType == ".doc")
292                        $ContentType = "application/msword";
293                if ($strFileType == ".zip")
294                        $ContentType = "application/zip";
295                if ($strFileType == ".xls")
296                        $ContentType = "application/vnd.ms-excel";
297                if ($strFileType == ".gif")
298                        $ContentType = "image/gif";
299                if ($strFileType == ".jpg" || $strFileType == "jpeg")
300                        $ContentType = "image/jpeg";
301                if ($strFileType == ".wav")
302                        $ContentType = "audio/wav";
303                if ($strFileType == ".mp3")
304                        $ContentType = "audio/mpeg3";
305                if ($strFileType == ".mpg" || $strFileType == "mpeg")
306                        $ContentType = "video/mpeg";
307                if ($strFileType == ".rtf")
308                        $ContentType = "application/rtf";
309                if ($strFileType == ".htm" || $strFileType == "html")
310                        $ContentType = "text/html";
311                if ($strFileType == ".xml")
312                        $ContentType = "text/xml";
313                if ($strFileType == ".xsl")
314                        $ContentType = "text/xsl";
315                if ($strFileType == ".css")
316                        $ContentType = "text/css";
317                if ($strFileType == ".php")
318                        $ContentType = "text/php";
319                if ($strFileType == ".asp")
320                        $ContentType = "text/asp";
321                if ($strFileType == ".pdf")
322                        $ContentType = "application/pdf";
323                if ($strFileType == ".txt")
324                        $ContentType = "text/plain";
325                if ($strFileType == ".log")
326                        $ContentType = "text/plain";
327                if ($strFileType == ".wmv")
328                        $ContentType = "video/x-ms-wmv";
329                if ($strFileType == ".sxc")
330                        $ContentType = "application/vnd.sun.xml.calc";
331                if ($strFileType == ".odt")
332                        $ContentType = "application/vnd.oasis.opendocument.text";
333                if ($strFileType == ".stc")
334                        $ContentType = "application/vnd.sun.xml.calc.template";
335                if ($strFileType == ".sxd")
336                        $ContentType = "application/vnd.sun.xml.draw";
337                if ($strFileType == ".std")
338                        $ContentType = "application/vnd.sun.xml.draw.template";
339                if ($strFileType == ".sxi")
340                        $ContentType = "application/vnd.sun.xml.impress";
341                if ($strFileType == ".sti")
342                        $ContentType = "application/vnd.sun.xml.impress.template";
343                if ($strFileType == ".sxm")
344                        $ContentType = "application/vnd.sun.xml.math";
345                if ($strFileType == ".sxw")
346                        $ContentType = "application/vnd.sun.xml.writer";
347                if ($strFileType == ".sxq")
348                        $ContentType = "application/vnd.sun.xml.writer.global";
349                if ($strFileType == ".stw")
350                        $ContentType = "application/vnd.sun.xml.writer.template";
351                if ($strFileType == ".ps")
352                        $ContentType = "application/postscript";
353                if ($strFileType == ".pps")
354                        $ContentType = "application/vnd.ms-powerpoint";
355                if ($strFileType == ".odt")
356                        $ContentType = "application/vnd.oasis.opendocument.text";
357                if ($strFileType == ".ott")
358                        $ContentType = "application/vnd.oasis.opendocument.text-template";
359                if ($strFileType == ".oth")
360                        $ContentType = "application/vnd.oasis.opendocument.text-web";
361                if ($strFileType == ".odm")
362                        $ContentType = "application/vnd.oasis.opendocument.text-master";
363                if ($strFileType == ".odg")
364                        $ContentType = "application/vnd.oasis.opendocument.graphics";
365                if ($strFileType == ".otg")
366                        $ContentType = "application/vnd.oasis.opendocument.graphics-template";
367                if ($strFileType == ".odp")
368                        $ContentType = "application/vnd.oasis.opendocument.presentation";
369                if ($strFileType == ".otp")
370                        $ContentType = "application/vnd.oasis.opendocument.presentation-template";
371                if ($strFileType == ".ods")
372                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet";
373                if ($strFileType == ".ots")
374                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet-template";
375                if ($strFileType == ".odc")
376                        $ContentType = "application/vnd.oasis.opendocument.chart";
377                if ($strFileType == ".odf")
378                        $ContentType = "application/vnd.oasis.opendocument.formula";
379                if ($strFileType == ".odi")
380                        $ContentType = "application/vnd.oasis.opendocument.image";
381                if ($strFileType == ".ndl")
382                        $ContentType = "application/vnd.lotus-notes";
383                return $ContentType;
384        }
385       
386        function download_all_attachments($params) {
387               
388                $id_number = $params['num_msg'];               
389                $attachments =unserialize(rawurldecode($params['s_attachments']));
390               
391                $tempDir = ini_get("session.save_path");
392                $tempSubDir = md5(microtime());
393                $fileNames = '';
394                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
395                $this-> folder = $params['folder'];
396                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
397                $this->connectImap();
398                include("class.imap_attachment.inc.php");
399                $imap_attachment = new imap_attachment();
400                $attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
401               
402                foreach($attachments as $i => $attachment){
403                        if($i && $i == 'names')
404                                continue;
405                                                                                                                                               
406                       
407                        $fileName = $this->remove_accents($attachment['name']);
408                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
409                        if(!$f)
410                                return False;                   
411                                               
412                        $fileNames .= "'".$fileName."' ";
413                        $fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachment['pid'], FT_UID);
414                        if($attachment['encoding'] == 'base64')
415                                fputs($f,imap_base64($fileContent));
416                        else           
417                                fputs($f,$fileContent);
418                               
419                        fclose($f);
420               
421                }
422                imap_close($this->mbox_stream);
423                $nameFileZip = '';
424               
425                if($fileNames) {
426                        $nameFileZip = $this -> createFileZip($fileNames, $tempDir . '/'.$tempSubDir);                                         
427                        if($nameFileZip)
428                                $file =  $tempDir . '/'.$tempSubDir.'/'.$nameFileZip;
429                        else {
430                                $file = false;
431                        }
432                }
433                else
434                        $file = false;
435                               
436                return $file;
437        }
438
439        function getHeader($msg_number){                       
440                return imap_fetchheader($this->mbox_stream, $msg_number, FT_UID);
441        }
442       
443        function getBody($msg_number){
444                $header = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number), 80, 255);
445                $body = imap_body($this->mbox_stream, $msg_number, FT_UID);
446                if(($header->Unseen == 'U') || ($header->Recent == 'N')){
447                        imap_clearflag_full($this->mbox_stream, $msg_number, "\\Seen", ST_UID);
448                }
449                return $body;
450        }
451
452        function decode_subject($string){
453                if ((strpos(strtolower($string), '=?iso-8859-1') !== false)
454                        || (strpos(strtolower($string), '=?windows-1252') !== false)){
455                        $elements = imap_mime_header_decode($string);
456                        foreach ($elements as $el)
457                                $return .= $el->text;
458                }
459                else if (strpos(strtolower($string), '=?utf-8') !== false) {
460                        $elements = imap_mime_header_decode($string);
461                        foreach ($elements as $el){
462                                $charset = $el->charset;
463                                $text    = $el->text;
464                                if(!strcasecmp($charset, "utf-8") ||
465                                !strcasecmp($charset, "utf-7")) {
466                                $text = iconv($charset, "ISO-8859-1", $text);
467                        }
468                        $return .= $text;
469                        }
470                }
471                else
472                        $return = $string;
473
474                return $this->remove_accents($return);         
475        }
476}
477// END CLASS
478?>
Note: See TracBrowser for help on using the repository browser.