-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstlBridalProsMailReader.php
350 lines (304 loc) · 12.1 KB
/
stlBridalProsMailReader.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
<?php
require_once('/home/dvaqpvvw/php/Mail/mimeDecode.php');
/*
* @class mailReader.php
*
* @brief Recieve mail and attachments with PHP
*
* Support:
* http://stuporglue.org/mailreader-php-parse-e-mail-and-save-attachments-php-version-2/
*
* Code:
* https://github.com/stuporglue/mailreader
*
* See the README.md for the license, and other information
*/
class mailReader {
var $saved_files = Array();
var $send_email = FALSE; // Send confirmation e-mail back to sender?
var $save_msg_to_db = FALSE; // Save e-mail message and file list to DB?
var $save_directory; // A safe place for files. Malicious users could upload a php or executable file, so keep this out of your web root
var $allowed_senders = Array('all'); // Allowed senders is just the email part of the sender (no name part)
var $allowed_mime_types = Array(
// 'audio/wave',
// 'application/pdf',
// 'application/zip',
// 'application/octet-stream',
'image/jpeg',
'image/png',
'image/gif'
);
var $debug = FALSE;
var $raw = '';
var $decoded;
var $from;
var $subject;
var $body;
var $newFileName = '';
/**
* @param $save_directory (required) A path to a directory where files will be saved
* @param $allowed_senders (required) An array of email addresses allowed to send through this script
* @param $pdo (optional) A PDO connection to a database for saving emails
*/
public function __construct($save_directory,$allowed_senders = 'all',$pdo = NULL){
if(!preg_match('|/$|',$save_directory)){ $save_directory .= '/'; } // add trailing slash if needed
$this->save_directory = $save_directory;
if (is_array($allowed_senders))
$this->allowed_senders = $allowed_senders;
$this->pdo = $pdo;
}
/**
* @brief Read an email message
*
* @param $src (optional) Which file to read the email from. Default is php://stdin for use as a pipe email handler
*
* @return An associative array of files saved. The key is the file name, the value is an associative array with size and mime type as keys.
*/
public function readEmail($src = 'php://stdin'){
// Process the e-mail from stdin
$fd = fopen($src,'r');
while(!feof($fd)){ $this->raw .= fread($fd,1024); }
// Now decode it!
// http://pear.php.net/manual/en/package.mail.mail-mimedecode.decode.php
$decoder = new Mail_mimeDecode($this->raw);
$this->decoded = $decoder->decode(
Array(
'decode_headers' => TRUE,
'include_bodies' => TRUE,
'decode_bodies' => TRUE,
)
);
// Set $this->from_email and check if it's allowed
$this->from = $this->decoded->headers['from'];
$this->from_email = preg_replace('/.*<(.*)>.*/',"$1",$this->from);
if(!(in_array('all',$this->allowed_senders) || (in_array($this->from_email,$this->allowed_senders)))){
die("$this->from_email not an allowed sender");
}
// Set the $this->subject
$this->subject = $this->decoded->headers['subject'];
$subjectParts = explode(' ',$this->subject);
if (is_array($subjectParts) && (count($subjectParts) == 3)){
if (strpos($subjectParts[0],'uid:') !== false)
$this->newFileName = str_replace('uid:','',$subjectParts[0]);
if (strpos($subjectParts[1],'dir:') !== false)
$this->newFileName .= '_'.str_replace('dir:','',$subjectParts[1]);
if (strpos($subjectParts[2],'maxSize:') !== false)
$this->newFileName .= '_'.str_replace('maxSize:','',$subjectParts[2]);
}
// Find the email body, and any attachments
// $body_part->ctype_primary and $body_part->ctype_secondary make up the mime type eg. text/plain or text/html
if(isset($this->decoded->parts) && is_array($this->decoded->parts)){
foreach($this->decoded->parts as $idx => $body_part){
$this->decodePart($body_part);
}
}
if(isset($this->decoded->disposition) && $this->decoded->disposition == 'inline'){
$mimeType = "{$this->decoded->ctype_primary}/{$this->decoded->ctype_secondary}";
if(isset($this->decoded->d_parameters) && array_key_exists('filename',$this->decoded->d_parameters)){
$filename = $this->decoded->d_parameters['filename'];
}else{
$filename = 'file';
}
$this->saveFile($filename,$this->decoded->body,$mimeType);
$this->body = "Body was a binary";
}
// We might also have uuencoded files. Check for those.
if(!isset($this->body)){
if(isset($this->decoded->body)){
$this->body = $this->decoded->body;
}else{
$this->body = "No plain text body found";
}
}
if(preg_match("/begin ([0-7]{3}) (.+)\r?\n(.+)\r?\nend/Us", $this->body) > 0){
foreach($decoder->uudecode($this->body) as $file){
// file = Array('filename' => $filename, 'fileperm' => $fileperm, 'filedata' => $filedata)
$this->saveFile($file['filename'],$file['filedata']);
}
// Strip out all the uuencoded attachments from the body
while(preg_match("/begin ([0-7]{3}) (.+)\r?\n(.+)\r?\nend/Us", $this->body) > 0){
$this->body = preg_replace("/begin ([0-7]{3}) (.+)\r?\n(.+)\r?\nend/Us", "\n",$this->body);
}
}
// Put the results in the database if needed
if($this->save_msg_to_db && !is_null($this->pdo)){
$this->saveToDb();
}
// Send response e-mail if needed
if($this->send_email && $this->from_email != ""){
$this->sendEmail();
}
// Print messages
if($this->debug){
$this->debugMsg();
}
return $this->saved_files;
}
/**
* @brief Decode a single body part of an email message
*
* @note Recursive if nested body parts are found
*
* @note This is the meat of the script.
*
* @param $body_part (required) The body part of the email message, as parsed by Mail_mimeDecode
*/
private function decodePart($body_part){
if (array_key_exists('d_parameters',$body_part)){
if (array_key_exists('filename',$body_part->d_parameters)){
$filename = $body_part->d_parameters['filename'];
}else{
$filename = "file";
}
}else{
if (array_key_exists('ctype_parameters',$body_part)){
if (array_key_exists('name',$body_part->ctype_parameters)){
$filename = $body_part->ctype_parameters['name'];
}else{
$filename = "file";
}
}
}
/* if(array_key_exists('name',$body_part->ctype_parameters)){ // everyone else I've tried
$filename = $body_part->ctype_parameters['name'];
}else if($body_part->ctype_parameters && array_key_exists('filename',$body_part->ctype_parameters)){ // hotmail
$filename = $body_part->ctype_parameters['filename'];
}else{
$filename = "file";
} */
$mimeType = "{$body_part->ctype_primary}/{$body_part->ctype_secondary}";
if($this->debug){
print "Found body part type $mimeType\n";
}
if($body_part->ctype_primary == 'multipart') {
if(is_array($body_part->parts)){
foreach($body_part->parts as $ix => $sub_part){
$this->decodePart($sub_part);
}
}
} else if($mimeType == 'text/plain'){
if(!isset($body_part->disposition)){
$this->body .= $body_part->body . "\n"; // Gather all plain/text which doesn't have an inline or attachment disposition
}
} else if(in_array($mimeType,$this->allowed_mime_types)){
$this->saveFile($filename,$body_part->body,$mimeType);
}
}
/**
* @brief Save off a single file
*
* @param $filename (required) The filename to use for this file
* @param $contents (required) The contents of the file we will save
* @param $mimeType (required) The mime-type of the file
*/
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
while(!$unlocked_and_unique){
/* // Find unique
$name = time() . "_" . $filename;
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
} */
$extension = "";
switch ($mimeType){
case 'image/jpeg':
$extension = ".jpg";
break;
case 'image/png':
$extension = ".png";
break;
case 'image/gif':
$extension = ".gif";
break;
}
$this->newFileName .= $extension;
// Attempt to lock
$outfile = fopen($this->save_directory.$this->newFileName,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
// This is for readability for the return e-mail and in the DB
$this->saved_files[$newFileName] = Array(
'size' => $this->formatBytes(filesize($this->save_directory.$this->newFileName)),
'mime' => $mimeType
);
}
/**
* @brief Format Bytes into human-friendly sizes
*
* @return A string with the number of bytes in the largest applicable unit (eg. KB, MB, GB, TB)
*/
private function formatBytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
/**
* @brief Save the plain text, subject and sender of an email to the database
*/
private function saveToDb(){
$insert = $this->pdo->prepare("INSERT INTO emails (fromaddr,subject,body) VALUES (?,?,?)");
// Replace non UTF-8 characters with their UTF-8 equivalent, or drop them
if(!$insert->execute(Array(
mb_convert_encoding($this->from_email,'UTF-8','UTF-8'),
mb_convert_encoding($this->subject,'UTF-8','UTF-8'),
mb_convert_encoding($this->body,'UTF-8','UTF-8')
))){
if($this->debug){
print_r($insert->errorInfo());
}
die("INSERT INTO emails failed!");
}
$email_id = $this->pdo->lastInsertId();
foreach($this->saved_files as $f => $data){
$insertFile = $this->pdo->prepare("INSERT INTO files (email_id,filename,mailsize,mime) VALUES (:email_id,:filename,:size,:mime)");
$insertFile->bindParam(':email_id',$email_id);
$insertFile->bindParam(':filename',mb_convert_encoding($f,'UTF-8','UTF-8'));
$insertFile->bindParam(':size',$data['size']);
$insertFile->bindParam(':mime',$data['mime']);
if(!$insertFile->execute()){
if($this->debug){
print_r($insertFile->errorInfo());
}
die("Insert file info failed!");
}
}
}
/**
* @brief Send the sender a response email with a summary of what was saved
*/
private function sendEmail(){
$newmsg = "Thanks! I just uploaded the following ";
$newmsg .= "files to your storage:\n\n";
$newmsg .= "Filename -- Size\n";
foreach($this->saved_files as $f => $s){
$newmsg .= "$f -- ({$s['size']}) of type {$s['mime']}\n";
}
$newmsg .= "\nI hope everything looks right. If not,";
$newmsg .= "please send me an e-mail!\n";
mail($this->from_email,$this->subject,$newmsg);
}
/**
* @brief Print a summary of the most recent email read
*/
private function debugMsg(){
$msg = "From : $this->from_email\r\n";
$msg .= "Subject : $this->subject\r\n";
$msg .= "Body : $this->body\r\n";
// $msg .= "Saved Files : \r\n";
// $msg .= "\n\n--------\nDecoder:\n";
// $decoded = print_r($this->decoded,true);
// $msg .= $decoded;
file_put_contents('debug_vendorUploadMailInfo.txt',$msg);
}
}