source: companies/serpro/expressoMail1_2/inc/class.exporteml.inc.php @ 903

Revision 903, 18.0 KB checked in by niltonneto, 15 years ago (diff)

Importacao inicial do Expresso do Serpro

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