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

Revision 1035, 18.9 KB checked in by rafaelraymundo, 15 years ago (diff)

Ticket #558 - Adicionada funcionalidade de assinatura e criptografia de e-mails.

  • 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_msg_data($id_msg,$folder) {
247                $this->folder = $folder;
248                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
249
250                $this->connectImap();
251                $header         = $this-> getHeader($id_msg);
252                $body           = $this-> getBody($id_msg);
253
254                $msg_data = $header ."\r\n\r\n". $body;
255
256                imap_close($this->mbox_stream);
257                return $msg_data;
258        }
259
260        function export_to_archive($id_msg,$folder) {
261                $this->folder = $folder;
262                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
263                $tempDir = dirname( __FILE__ ) . '/../tmpLclAtt';
264               
265                $phpheader = "<?php header('Content-Type: text/plain');
266                                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
267                                header('Pragma: public');
268                                header('Expires: 0'); // set expiration time
269                                header('Content-Disposition: attachment; filename=\"fonte_da_mensagem.txt\"');?>";
270               
271                $this->connectImap();
272                $header         = $this-> getHeader($id_msg);
273                $body           = $this-> getBody($id_msg);
274               
275                $file = "source_".md5(microtime()).".php";
276                $f = fopen($tempDir.'/'.$file,"w");
277                fputs($f,$phpheader.$header ."\r\n\r\n". $body);
278                fclose($f);
279                $urlPath = 'tmpLclAtt/'.$file;
280               
281                imap_close($this->mbox_stream);
282                return $urlPath;
283        }
284
285        function remove_accents($string) {
286                /*
287                        $array1 = array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç" , "?", "\"", "!", "@", "#", "$", "%", "š", "&", "*", "(", ")", "-", "=", "+", "Ž", "`", "[", "]", "{", "}", "~", "^", ",", "<", ">", ";", ":", "/", "?", "\\", "|", "¹", "²", "³", "£", "¢", "¬", "§", "ª", "º", "°", "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");
288                        $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");
289                        return str_replace( $array1, $array2, $string );
290                */
291                return strtr($string,
292                        "áàâãäéèêëíìîïóòôõöúùûüç?\"!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº°ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ",
293                        "aaaaaeeeeiiiiooooouuuuc__________________________________________AAAAAEEEEIIIIOOOOOUUUUC");
294        }
295       
296        function get_attachments_in_array($params) {
297                $return_attachments = array();
298
299                $id_number = $params['num_msg'];               
300                $attachments =unserialize(rawurldecode($params['s_attachments']));
301               
302                $tempDir = dirname( __FILE__ ) . '/../tmpLclAtt';
303//              $tempDir = $_SERVER["DOCUMENT_ROOT"]."tmpLclAtt";
304                $tempSubDir = md5(microtime());
305                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
306               
307                $this-> folder = $params['folder'];
308                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
309                $this->connectImap();
310
311                include_once("class.imap_attachment.inc.php");
312
313                $imap_attachment = new imap_attachment();
314                $attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
315                foreach($attachments as $i => $attachment){
316                        if($i && $i == 'names')
317                                continue;
318                        $fileNameReal = $this->remove_accents($attachment['name']);
319                        $ContentType = $this->getFileType($fileNameReal);
320                        $fileName = $fileNameReal . ".php";
321                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
322                        if(!$f)
323                                return $tempDir . '/'.$tempSubDir.'/'.$fileName;                       
324
325                        $fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachment['pid'], FT_UID);
326                        $urlPath = 'tmpLclAtt/'.$tempSubDir.'/'.$fileName;
327                       
328                        $headers = "<?php header('Content-Type: ".$ContentType."');
329                                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
330                                header('Pragma: public');
331                                header('Expires: 0'); // set expiration time
332                                header('Content-Disposition: attachment; filename=\"". addslashes($fileNameReal) ."\"');\n echo ";
333                       
334                        if($attachment['encoding'] == 'base64') {
335                                $headers.=" imap_base64('".$fileContent."');?>";
336                        }
337                        else if($attachment['encoding'] == 'quoted_printable_decode') {
338                                $headers.=" quoted_printable_decode('".$fileContent."');?>";
339                        }
340                        else {
341                                $headers.=" '".$fileContent."';?>";
342                        }
343                       
344                        fputs($f,$headers);
345
346                        array_push($return_attachments,array('name' => $fileName,'url' => $urlPath,'pid' =>$attachment['pid']));
347                        fclose($f);
348                }
349                imap_close($this->mbox_stream);
350                return $return_attachments;
351        }
352       
353        private function getFileType($nameFile) {
354                $strFileType = strrev(substr(strrev(strtolower($nameFile)),0,4));
355                $ContentType = "application/octet-stream";
356                if ($strFileType == ".asf")
357                        $ContentType = "video/x-ms-asf";
358                if ($strFileType == ".avi")
359                        $ContentType = "video/avi";
360                if ($strFileType == ".doc")
361                        $ContentType = "application/msword";
362                if ($strFileType == ".zip")
363                        $ContentType = "application/zip";
364                if ($strFileType == ".xls")
365                        $ContentType = "application/vnd.ms-excel";
366                if ($strFileType == ".gif")
367                        $ContentType = "image/gif";
368                if ($strFileType == ".jpg" || $strFileType == "jpeg")
369                        $ContentType = "image/jpeg";
370                if ($strFileType == ".wav")
371                        $ContentType = "audio/wav";
372                if ($strFileType == ".mp3")
373                        $ContentType = "audio/mpeg3";
374                if ($strFileType == ".mpg" || $strFileType == "mpeg")
375                        $ContentType = "video/mpeg";
376                if ($strFileType == ".rtf")
377                        $ContentType = "application/rtf";
378                if ($strFileType == ".htm" || $strFileType == "html")
379                        $ContentType = "text/html";
380                if ($strFileType == ".xml")
381                        $ContentType = "text/xml";
382                if ($strFileType == ".xsl")
383                        $ContentType = "text/xsl";
384                if ($strFileType == ".css")
385                        $ContentType = "text/css";
386                if ($strFileType == ".php")
387                        $ContentType = "text/php";
388                if ($strFileType == ".asp")
389                        $ContentType = "text/asp";
390                if ($strFileType == ".pdf")
391                        $ContentType = "application/pdf";
392                if ($strFileType == ".txt")
393                        $ContentType = "text/plain";
394                if ($strFileType == ".log")
395                        $ContentType = "text/plain";
396                if ($strFileType == ".wmv")
397                        $ContentType = "video/x-ms-wmv";
398                if ($strFileType == ".sxc")
399                        $ContentType = "application/vnd.sun.xml.calc";
400                if ($strFileType == ".odt")
401                        $ContentType = "application/vnd.oasis.opendocument.text";
402                if ($strFileType == ".stc")
403                        $ContentType = "application/vnd.sun.xml.calc.template";
404                if ($strFileType == ".sxd")
405                        $ContentType = "application/vnd.sun.xml.draw";
406                if ($strFileType == ".std")
407                        $ContentType = "application/vnd.sun.xml.draw.template";
408                if ($strFileType == ".sxi")
409                        $ContentType = "application/vnd.sun.xml.impress";
410                if ($strFileType == ".sti")
411                        $ContentType = "application/vnd.sun.xml.impress.template";
412                if ($strFileType == ".sxm")
413                        $ContentType = "application/vnd.sun.xml.math";
414                if ($strFileType == ".sxw")
415                        $ContentType = "application/vnd.sun.xml.writer";
416                if ($strFileType == ".sxq")
417                        $ContentType = "application/vnd.sun.xml.writer.global";
418                if ($strFileType == ".stw")
419                        $ContentType = "application/vnd.sun.xml.writer.template";
420                if ($strFileType == ".ps")
421                        $ContentType = "application/postscript";
422                if ($strFileType == ".pps")
423                        $ContentType = "application/vnd.ms-powerpoint";
424                if ($strFileType == ".odt")
425                        $ContentType = "application/vnd.oasis.opendocument.text";
426                if ($strFileType == ".ott")
427                        $ContentType = "application/vnd.oasis.opendocument.text-template";
428                if ($strFileType == ".oth")
429                        $ContentType = "application/vnd.oasis.opendocument.text-web";
430                if ($strFileType == ".odm")
431                        $ContentType = "application/vnd.oasis.opendocument.text-master";
432                if ($strFileType == ".odg")
433                        $ContentType = "application/vnd.oasis.opendocument.graphics";
434                if ($strFileType == ".otg")
435                        $ContentType = "application/vnd.oasis.opendocument.graphics-template";
436                if ($strFileType == ".odp")
437                        $ContentType = "application/vnd.oasis.opendocument.presentation";
438                if ($strFileType == ".otp")
439                        $ContentType = "application/vnd.oasis.opendocument.presentation-template";
440                if ($strFileType == ".ods")
441                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet";
442                if ($strFileType == ".ots")
443                        $ContentType = "application/vnd.oasis.opendocument.spreadsheet-template";
444                if ($strFileType == ".odc")
445                        $ContentType = "application/vnd.oasis.opendocument.chart";
446                if ($strFileType == ".odf")
447                        $ContentType = "application/vnd.oasis.opendocument.formula";
448                if ($strFileType == ".odi")
449                        $ContentType = "application/vnd.oasis.opendocument.image";
450                if ($strFileType == ".ndl")
451                        $ContentType = "application/vnd.lotus-notes";
452                return $ContentType;
453        }
454       
455        function download_all_attachments($params) {
456               
457                $id_number = $params['num_msg'];               
458                $attachments =unserialize(rawurldecode($params['s_attachments']));
459               
460                $tempDir = ini_get("session.save_path");
461                $tempSubDir = md5(microtime());
462                $fileNames = '';
463                exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
464                $this-> folder = $params['folder'];
465                $this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
466                $this->connectImap();
467                include("class.imap_attachment.inc.php");
468                $imap_attachment = new imap_attachment();
469                $attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
470               
471                foreach($attachments as $i => $attachment){
472                        if($i && $i == 'names')
473                                continue;
474                                                                                                                                               
475                       
476                        $fileName = $this->remove_accents($attachment['name']);
477                        $f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
478                        if(!$f)
479                                return False;                   
480                                               
481                        $fileNames .= "'".$fileName."' ";
482                        $fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachment['pid'], FT_UID);
483                        if($attachment['encoding'] == 'base64')
484                                fputs($f,imap_base64($fileContent));
485                        else           
486                                fputs($f,$fileContent);
487                               
488                        fclose($f);
489               
490                }
491                imap_close($this->mbox_stream);
492                $nameFileZip = '';
493               
494                if($fileNames) {
495                        $nameFileZip = $this -> createFileZip($fileNames, $tempDir . '/'.$tempSubDir);                                         
496                        if($nameFileZip)
497                                $file =  $tempDir . '/'.$tempSubDir.'/'.$nameFileZip;
498                        else {
499                                $file = false;
500                        }
501                }
502                else
503                        $file = false;
504                               
505                return $file;
506        }
507
508        function getHeader($msg_number){                       
509                return imap_fetchheader($this->mbox_stream, $msg_number, FT_UID);
510        }
511       
512        function getBody($msg_number){
513                $header = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number), 80, 255);
514                $body = imap_body($this->mbox_stream, $msg_number, FT_UID);
515                if(($header->Unseen == 'U') || ($header->Recent == 'N')){
516                        imap_clearflag_full($this->mbox_stream, $msg_number, "\\Seen", ST_UID);
517                }
518                return $body;
519        }
520
521        function decode_subject($string){
522                if ((strpos(strtolower($string), '=?iso-8859-1') !== false)
523                        || (strpos(strtolower($string), '=?windows-1252') !== false)){
524                        $elements = imap_mime_header_decode($string);
525                        foreach ($elements as $el)
526                                $return .= $el->text;
527                }
528                else if (strpos(strtolower($string), '=?utf-8') !== false) {
529                        $elements = imap_mime_header_decode($string);
530                        foreach ($elements as $el){
531                                $charset = $el->charset;
532                                $text    = $el->text;
533                                if(!strcasecmp($charset, "utf-8") ||
534                                !strcasecmp($charset, "utf-7")) {
535                                $text = iconv($charset, "ISO-8859-1", $text);
536                        }
537                        $return .= $text;
538                        }
539                }
540                else
541                        $return = $string;
542
543                return $this->remove_accents($return);         
544        }
545}
546// END CLASS
547?>
Note: See TracBrowser for help on using the repository browser.