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

Revision 1000, 18.5 KB checked in by rafaelraymundo, 15 years ago (diff)

Ticket #550 - Unificação de funcionalidade do SERPRO referentes ao arquivamento local.

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