summaryrefslogtreecommitdiff
path: root/apps/mm/ext/MimeMailParser.class.php
blob: 008019999cf4f7452de5e2d1ae0ea3fe74b795ec (plain)
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
<?php

require_once('MimeMailParser_attachment.class.php');

/**
 * Fast Mime Mail parser Class using PHP's MailParse Extension
 * @author gabe@fijiwebdesign.com
 * @url http://www.fijiwebdesign.com/
 * @license http://creativecommons.org/licenses/by-sa/3.0/us/
 * @version $Id$
 */
class MimeMailParser {
	
	/**
	 * PHP MimeParser Resource ID
	 */
	public $resource;
	
	/**
	 * A file pointer to email
	 */
	public $stream;
	
	/**
	 * A text of an email
	 */
	public $data;
	
	/**
	 * Stream Resources for Attachments
	 */
	public $attachment_streams;
	
	/**
	 * Inialize some stuff
	 * @return 
	 */
	public function __construct() {
		$this->attachment_streams = array();
	}
	
	/**
	 * Free the held resouces
	 * @return void
	 */
	public function __destruct() {
		// clear the email file resource
		if (is_resource($this->stream)) {
			fclose($this->stream);
		}
		// clear the MailParse resource
		if (is_resource($this->resource)) {
			mailparse_msg_free($this->resource);
		}
		// remove attachment resources
		foreach($this->attachment_streams as $stream) {
			fclose($stream);
		}
	}
	
	/**
	 * Set the file path we use to get the email text
	 * @return Object MimeMailParser Instance
	 * @param $mail_path Object
	 */
	public function setPath($path) {
		// should parse message incrementally from file
		$this->resource = mailparse_msg_parse_file($path);
		$this->stream = fopen($path, 'r');
		$this->parse();
		return $this;
	}
	
	/**
	 * Set the Stream resource we use to get the email text
	 * @return Object MimeMailParser Instance
	 * @param $stream Resource
	 */
	public function setStream($stream) {

		// streams have to be cached to file first
		if (get_resource_type($stream) == 'stream') {
			$tmp_fp = tmpfile();
			if ($tmp_fp) {
				while(!feof($stream)) {
					fwrite($tmp_fp, fread($stream, 2028));
				}
				fseek($tmp_fp, 0);
				$this->stream =& $tmp_fp;
			} else {
				throw new Exception('Could not create temporary files for attachments. Your tmp directory may be unwritable by PHP.');
				return false;
			}
			fclose($stream);
		} else {
			$this->stream = $stream;
		}
		
		$this->resource = mailparse_msg_create();
		// parses the message incrementally low memory usage but slower
		while(!feof($this->stream)) {
			mailparse_msg_parse($this->resource, fread($this->stream, 2082));
		}
		$this->parse();
		return $this;
	}
	
	/**
	 * Set the email text
	 * @return Object MimeMailParser Instance 
	 * @param $data String
	 */
	public function setText($data) {
		$this->resource = mailparse_msg_create();
		// does not parse incrementally, fast memory hog might explode
		mailparse_msg_parse($this->resource, $data);
		$this->data = $data;
		$this->parse();
		return $this;
	}
	
	/**
	 * Parse the Message into parts
	 * @return void
	 * @private
	 */
	private function parse() {
		$structure = mailparse_msg_get_structure($this->resource);
		$this->parts = array();
		foreach($structure as $part_id) {
			$part = mailparse_msg_get_part($this->resource, $part_id);
			$this->parts[$part_id] = mailparse_msg_get_part_data($part);
		}
	}
	
	/**
	 * Retrieve the Email Headers
	 * @return Array
	 */
	public function getHeaders() {
		if (isset($this->parts[1])) {
			return $this->getPartHeaders($this->parts[1]);
		} else {
			throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.');
		}
		return false;
	}
	/**
	 * Retrieve the raw Email Headers
	 * @return string
	 */
	public function getHeadersRaw() {
		if (isset($this->parts[1])) {
			return $this->getPartHeaderRaw($this->parts[1]);
		} else {
			throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.');
		}
		return false;
	}

	/**
	 * Retrieve a specific Email Header
	 * @return String
	 * @param $name String Header name
	 */
	public function getHeader($name) {
		if (isset($this->parts[1])) {
			$headers = $this->getPartHeaders($this->parts[1]);
			if (isset($headers[$name])) {
				return $headers[$name];
			}
		} else {
			throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.');
		}
		return false;
	}

	/**
	 * Returns the part for the message body in the specified format
	 * @return Part or False if not found
	 * @param $type String[optional]
	 */
	public function getMessageBodyPart($type = 'text') {
		$mime_types = array(
			'text'=> 'text/plain',
			'html'=> 'text/html'
		);
		$attachment_dispositions = array("attachment","inline");
		if (in_array($type, array_keys($mime_types))) {
			foreach($this->parts as $part) {
				$disposition = $this->getPartContentDisposition($part);
				$mime_type = $this->getPartContentType($part);
				if ( (!in_array($disposition, $attachment_dispositions)) &&
				     ($mime_type == $mime_types[$type]) ) {
					return $part;
				}
			}
		} else {
			throw new Exception('Invalid type specified for MimeMailParser::getMessageBodyPart. "type" can either be text or html.');
		}
		return false;
	}

	/**
	 * Returns the email message body in the specified format
	 * @return Mixed String Body or False if not found
	 * @param $type Object[optional]
	 */
	public function getMessageBody($type = 'text') {
		$body = false;
		$part = $this->getMessageBodyPart($type);
		if ($part!==false) {
			$headers = $this->getPartHeaders($part);
			$body = $this->decode($this->getPartBody($part), array_key_exists('content-transfer-encoding', $headers) ? $headers['content-transfer-encoding'] : '');
		}
		return $body;
	}

	/**
	 * get the headers for the message body part.
	 * @return Array
	 * @param $type Object[optional]
	 */
	public function getMessageBodyHeaders($type = 'text') {
		$headers = false;
		$part = $this->getMessageBodyPart($type);
		if ($part!==false) {
			$headers = $this->getPartHeaders($part);
		}
		return $headers;
	}

	
	/**
	 * Returns the attachments contents in order of appearance
	 * @return Array
	 * @param $type Object[optional]
	 */
	public function getAttachments() {
		$attachments = array();
		$dispositions = array("attachment","inline");
		foreach($this->parts as $part) {
			$disposition = $this->getPartContentDisposition($part);
			if (in_array($disposition, $dispositions)) {
				$headers = $this->getPartHeaders($part);
				$attachments[] = new MimeMailParser_attachment(
					$part['disposition-filename'], 
					$this->getPartContentType($part), 
					$this->getAttachmentStream($part),
					$disposition,
					$headers
				);
			}
		}
		return $attachments;
	}
	
	/**
	 * Return the Headers for a MIME part
	 * @return Array
	 * @param $part Array
	 */
	private function getPartHeaders($part) {
		if (isset($part['headers'])) {
			return $part['headers'];
		}
		return false;
	}
	
	/**
	 * Return a Specific Header for a MIME part
	 * @return Array
	 * @param $part Array
	 * @param $header String Header Name
	 */
	private function getPartHeader($part, $header) {
		if (isset($part['headers'][$header])) {
			return $part['headers'][$header];
		}
		return false;
	}
	
	/**
	 * Return the ContentType of the MIME part
	 * @return String
	 * @param $part Array
	 */
	private function getPartContentType($part) {
		if (isset($part['content-type'])) {
			return $part['content-type'];
		}
		return false;
	}
	
	/**
	 * Return the Content Disposition
	 * @return String
	 * @param $part Array
	 */
	private function getPartContentDisposition($part) {
		if (isset($part['content-disposition'])) {
			return $part['content-disposition'];
		}
		return false;
	}
	
	/**
	 * Retrieve the raw Header of a MIME part
	 * @return String
	 * @param $part Object
	 */
	private function getPartHeaderRaw(&$part) {
		$header = '';
		if ($this->stream) {
			$header = $this->getPartHeaderFromFile($part);
		} else if ($this->data) {
			$header = $this->getPartHeaderFromText($part);
		} else {
			throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email parts.');
		}
		return $header;
	}
	/**
	 * Retrieve the Body of a MIME part
	 * @return String
	 * @param $part Object
	 */
	private function getPartBody(&$part) {
		$body = '';
		if ($this->stream) {
			$body = $this->getPartBodyFromFile($part);
		} else if ($this->data) {
			$body = $this->getPartBodyFromText($part);
		} else {
			throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email parts.');
		}
		return $body;
	}
	
	/**
	 * Retrieve the Header from a MIME part from file
	 * @return String Mime Header Part
	 * @param $part Array
	 */
	private function getPartHeaderFromFile(&$part) {
		$start = $part['starting-pos'];
		$end = $part['starting-pos-body'];
		fseek($this->stream, $start, SEEK_SET);
		$header = fread($this->stream, $end-$start);
		return $header;
	}
	/**
	 * Retrieve the Body from a MIME part from file
	 * @return String Mime Body Part
	 * @param $part Array
	 */
	private function getPartBodyFromFile(&$part) {
		$start = $part['starting-pos-body'];
		$end = $part['ending-pos-body'];
		fseek($this->stream, $start, SEEK_SET);
		$body = fread($this->stream, $end-$start);
		return $body;
	}
	
	/**
	 * Retrieve the Header from a MIME part from text
	 * @return String Mime Header Part
	 * @param $part Array
	 */
	private function getPartHeaderFromText(&$part) {
		$start = $part['starting-pos'];
		$end = $part['starting-pos-body'];
		$header = substr($this->data, $start, $end-$start);
		return $header;
	}
	/**
	 * Retrieve the Body from a MIME part from text
	 * @return String Mime Body Part
	 * @param $part Array
	 */
	private function getPartBodyFromText(&$part) {
		$start = $part['starting-pos-body'];
		$end = $part['ending-pos-body'];
		$body = substr($this->data, $start, $end-$start);
		return $body;
	}
	
	/**
	 * Read the attachment Body and save temporary file resource
	 * @return String Mime Body Part
	 * @param $part Array
	 */
	private function getAttachmentStream(&$part) {
		$temp_fp = tmpfile();   

        array_key_exists('content-transfer-encoding', $part['headers']) ? $encoding = $part['headers']['content-transfer-encoding'] : $encoding = '';

		if ($temp_fp) {
			if ($this->stream) {
				$start = $part['starting-pos-body'];
				$end = $part['ending-pos-body'];
				fseek($this->stream, $start, SEEK_SET);
				$len = $end-$start;
				$written = 0;
				$write = 2028;
				$body = '';
				while($written < $len) {
					if (($written+$write < $len )) {
						$write = $len - $written;
					}
					$part = fread($this->stream, $write);
					fwrite($temp_fp, $this->decode($part, $encoding));
					$written += $write;
				}
			} else if ($this->data) {
				$attachment = $this->decode($this->getPartBodyFromText($part), $encoding);
				fwrite($temp_fp, $attachment, strlen($attachment));
			}
			fseek($temp_fp, 0, SEEK_SET);
		} else {
			throw new Exception('Could not create temporary files for attachments. Your tmp directory may be unwritable by PHP.');
			return false;
		}
		return $temp_fp;
	}

    
    /**
     * Decode the string depending on encoding type.
     * @return String the decoded string.
     * @param $encodedString    The string in its original encoded state.
     * @param $encodingType     The encoding type from the Content-Transfer-Encoding header of the part.
     */
    private function decode($encodedString, $encodingType) {
        if (strtolower($encodingType) == 'base64') {
        	return base64_decode($encodedString);
        } else if (strtolower($encodingType) == 'quoted-printable') {
        	 return quoted_printable_decode($encodedString);
        } else {
        	return $encodedString;
        }
    }

}


?>