comment fixes
[civicrm-core.git] / CRM / Utils / Mail / Incoming.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 */
33 class CRM_Utils_Mail_Incoming {
34 const
35 EMAILPROCESSOR_CREATE_INDIVIDUAL = 1,
36 EMAILPROCESSOR_OVERRIDE = 2,
37 EMAILPROCESSOR_IGNORE = 3;
38
39 /**
40 * @param $mail
41 * @param $attachments
42 *
43 * @return string
44 */
45 public function formatMail($mail, &$attachments) {
46 $t = '';
47 $t .= "From: " . self::formatAddress($mail->from) . "\n";
48 $t .= "To: " . self::formatAddresses($mail->to) . "\n";
49 $t .= "Cc: " . self::formatAddresses($mail->cc) . "\n";
50 $t .= "Bcc: " . self::formatAddresses($mail->bcc) . "\n";
51 $t .= 'Date: ' . date(DATE_RFC822, $mail->timestamp) . "\n";
52 $t .= 'Subject: ' . $mail->subject . "\n";
53 $t .= "MessageId: " . $mail->messageId . "\n";
54 $t .= "\n";
55 $t .= self::formatMailPart($mail->body, $attachments);
56 return $t;
57 }
58
59 /**
60 * @param $part
61 * @param $attachments
62 *
63 * @throws Exception
64 */
65 public static function formatMailPart($part, &$attachments) {
66 if ($part instanceof ezcMail) {
67 return self::formatMail($part, $attachments);
68 }
69
70 if ($part instanceof ezcMailText) {
71 return self::formatMailText($part, $attachments);
72 }
73
74 if ($part instanceof ezcMailFile) {
75 return self::formatMailFile($part, $attachments);
76 }
77
78 if ($part instanceof ezcMailRfc822Digest) {
79 return self::formatMailRfc822Digest($part, $attachments);
80 }
81
82 if ($part instanceof ezcMailMultiPart) {
83 return self::formatMailMultipart($part, $attachments);
84 }
85
86 CRM_Core_Error::fatal(ts("No clue about the %1", array(1 => get_class($part))));
87 }
88
89 /**
90 * @param $part
91 * @param $attachments
92 *
93 * @throws Exception
94 */
95 public function formatMailMultipart($part, &$attachments) {
96 if ($part instanceof ezcMailMultiPartAlternative) {
97 return self::formatMailMultipartAlternative($part, $attachments);
98 }
99
100 if ($part instanceof ezcMailMultiPartDigest) {
101 return self::formatMailMultipartDigest($part, $attachments);
102 }
103
104 if ($part instanceof ezcMailMultiPartRelated) {
105 return self::formatMailMultipartRelated($part, $attachments);
106 }
107
108 if ($part instanceof ezcMailMultiPartMixed) {
109 return self::formatMailMultipartMixed($part, $attachments);
110 }
111
112 if ($part instanceof ezcMailMultipartReport) {
113 return self::formatMailMultipartReport($part, $attachments);
114 }
115
116 CRM_Core_Error::fatal(ts("No clue about the %1", array(1 => get_class($part))));
117 }
118
119 /**
120 * @param $part
121 * @param $attachments
122 *
123 * @return string
124 */
125 public function formatMailMultipartMixed($part, &$attachments) {
126 $t = '';
127 foreach ($part->getParts() as $key => $alternativePart) {
128 $t .= self::formatMailPart($alternativePart, $attachments);
129 }
130 return $t;
131 }
132
133 /**
134 * @param $part
135 * @param $attachments
136 *
137 * @return string
138 */
139 public function formatMailMultipartRelated($part, &$attachments) {
140 $t = '';
141 $t .= "-RELATED MAIN PART-\n";
142 $t .= self::formatMailPart($part->getMainPart(), $attachments);
143 foreach ($part->getRelatedParts() as $key => $alternativePart) {
144 $t .= "-RELATED PART $key-\n";
145 $t .= self::formatMailPart($alternativePart, $attachments);
146 }
147 $t .= "-RELATED END-\n";
148 return $t;
149 }
150
151 /**
152 * @param $part
153 * @param $attachments
154 *
155 * @return string
156 */
157 public function formatMailMultipartDigest($part, &$attachments) {
158 $t = '';
159 foreach ($part->getParts() as $key => $alternativePart) {
160 $t .= "-DIGEST-$key-\n";
161 $t .= self::formatMailPart($alternativePart, $attachments);
162 }
163 $t .= "-DIGEST END---\n";
164 return $t;
165 }
166
167 /**
168 * @param $part
169 * @param $attachments
170 *
171 * @return string
172 */
173 public function formatMailRfc822Digest($part, &$attachments) {
174 $t = '';
175 $t .= "-DIGEST-ITEM-\n";
176 $t .= "Item:\n\n";
177 $t .= self::formatMailpart($part->mail, $attachments);
178 $t .= "-DIGEST ITEM END-\n";
179 return $t;
180 }
181
182 /**
183 * @param $part
184 * @param $attachments
185 *
186 * @return string
187 */
188 public function formatMailMultipartAlternative($part, &$attachments) {
189 $t = '';
190 foreach ($part->getParts() as $key => $alternativePart) {
191 $t .= "-ALTERNATIVE ITEM $key-\n";
192 $t .= self::formatMailPart($alternativePart, $attachments);
193 }
194 $t .= "-ALTERNATIVE END-\n";
195 return $t;
196 }
197
198 /**
199 * @param $part
200 * @param $attachments
201 *
202 * @return string
203 */
204 public static function formatMailText($part, &$attachments) {
205 $t = "\n{$part->text}\n";
206 return $t;
207 }
208
209 /**
210 * @param $part
211 * @param $attachments
212 *
213 * @return string
214 */
215 public function formatMailMultipartReport($part, &$attachments) {
216 $t = '';
217 foreach ($part->getParts() as $key => $reportPart) {
218 $t .= "-REPORT-$key-\n";
219 $t .= self::formatMailPart($reportPart, $attachments);
220 }
221 $t .= "-REPORT END---\n";
222 return $t;
223 }
224
225 /**
226 * @param $part
227 * @param $attachments
228 *
229 * @return null
230 */
231 public function formatMailFile($part, &$attachments) {
232 $attachments[] = array(
233 'dispositionType' => $part->dispositionType,
234 'contentType' => $part->contentType,
235 'mimeType' => $part->mimeType,
236 'contentID' => $part->contentId,
237 'fullName' => $part->fileName,
238 );
239 return NULL;
240 }
241
242 /**
243 * @param $addresses
244 *
245 * @return string
246 */
247 public function formatAddresses($addresses) {
248 $fa = array();
249 foreach ($addresses as $address) {
250 $fa[] = self::formatAddress($address);
251 }
252 return implode(', ', $fa);
253 }
254
255 /**
256 * @param $address
257 *
258 * @return string
259 */
260 public function formatAddress($address) {
261 $name = '';
262 if (!empty($address->name)) {
263 $name = "{$address->name} ";
264 }
265 return $name . "<{$address->email}>";
266 }
267
268 /**
269 * @param $file
270 *
271 * @return array
272 * @throws Exception
273 */
274 public function &parse(&$file) {
275
276 // check that the file exists and has some content
277 if (!file_exists($file) ||
278 !trim(file_get_contents($file))
279 ) {
280 return CRM_Core_Error::createAPIError(ts('%1 does not exists or is empty',
281 array(1 => $file)
282 ));
283 }
284
285 require_once 'ezc/Base/src/ezc_bootstrap.php';
286 require_once 'ezc/autoload/mail_autoload.php';
287
288 // explode email to digestable format
289 $set = new ezcMailFileSet(array($file));
290 $parser = new ezcMailParser();
291 $mail = $parser->parseMail($set);
292
293 if (!$mail) {
294 return CRM_Core_Error::createAPIError(ts('%1 could not be parsed',
295 array(1 => $file)
296 ));
297 }
298
299 // since we only have one fileset
300 $mail = $mail[0];
301
302 $mailParams = self::parseMailingObject($mail);
303 return $mailParams;
304 }
305
306 /**
307 * @param $mail
308 *
309 * @return array
310 */
311 public static function parseMailingObject(&$mail) {
312
313 $config = CRM_Core_Config::singleton();
314
315 // get ready for collecting data about this email
316 // and put it in a standardized format
317 $params = array('is_error' => 0);
318
319 $params['from'] = array();
320 self::parseAddress($mail->from, $field, $params['from'], $mail);
321
322 // we definitely need a contact id for the from address
323 // if we dont have one, skip this email
324 if (empty($params['from']['id'])) {
325 return NULL;
326 }
327
328 $emailFields = array('to', 'cc', 'bcc');
329 foreach ($emailFields as $field) {
330 $value = $mail->$field;
331 self::parseAddresses($value, $field, $params, $mail);
332 }
333
334 // define other parameters
335 $params['subject'] = $mail->subject;
336 $params['date'] = date("YmdHi00",
337 strtotime($mail->getHeader("Date"))
338 );
339 $attachments = array();
340 $params['body'] = self::formatMailPart($mail->body, $attachments);
341
342 // format and move attachments to the civicrm area
343 if (!empty($attachments)) {
344 $date = date('Ymdhis');
345 $config = CRM_Core_Config::singleton();
346 for ($i = 0; $i < count($attachments); $i++) {
347 $attachNum = $i + 1;
348 $fileName = basename($attachments[$i]['fullName']);
349 $newName = CRM_Utils_File::makeFileName($fileName);
350 $location = $config->uploadDir . $newName;
351
352 // move file to the civicrm upload directory
353 rename($attachments[$i]['fullName'], $location);
354
355 $mimeType = "{$attachments[$i]['contentType']}/{$attachments[$i]['mimeType']}";
356
357 $params["attachFile_$attachNum"] = array(
358 'uri' => $fileName,
359 'type' => $mimeType,
360 'upload_date' => $date,
361 'location' => $location,
362 );
363 }
364 }
365
366 return $params;
367 }
368
369 /**
370 * @param $address
371 * @param array $params
372 * @param $subParam
373 * @param $mail
374 */
375 public static function parseAddress(&$address, &$params, &$subParam, &$mail) {
376 // CRM-9484
377 if (empty($address->email)) {
378 return;
379 }
380
381 $subParam['email'] = $address->email;
382 $subParam['name'] = $address->name;
383
384 $contactID = self::getContactID($subParam['email'],
385 $subParam['name'],
386 TRUE,
387 $mail
388 );
389 $subParam['id'] = $contactID ? $contactID : NULL;
390 }
391
392 /**
393 * @param $addresses
394 * @param $token
395 * @param array $params
396 * @param $mail
397 */
398 public static function parseAddresses(&$addresses, $token, &$params, &$mail) {
399 $params[$token] = array();
400
401 foreach ($addresses as $address) {
402 $subParam = array();
403 self::parseAddress($address, $params, $subParam, $mail);
404 $params[$token][] = $subParam;
405 }
406 }
407
408 /**
409 * Retrieve a contact ID and if not present.
410 *
411 * Create one with this email
412 *
413 * @param string $email
414 * @param string $name
415 * @param bool $create
416 * @param string $mail
417 *
418 * @return int|null
419 */
420 public static function getContactID($email, $name = NULL, $create = TRUE, &$mail) {
421 $dao = CRM_Contact_BAO_Contact::matchContactOnEmail($email, 'Individual');
422
423 $contactID = NULL;
424 if ($dao) {
425 $contactID = $dao->contact_id;
426 }
427
428 $result = NULL;
429 CRM_Utils_Hook::emailProcessorContact($email, $contactID, $result);
430
431 if (!empty($result)) {
432 if ($result['action'] == self::EMAILPROCESSOR_IGNORE) {
433 return NULL;
434 }
435 if ($result['action'] == self::EMAILPROCESSOR_OVERRIDE) {
436 return $result['contactID'];
437 }
438
439 // else this is now create individual
440 // so we just fall out and do what we normally do
441 }
442
443 if ($contactID) {
444 return $contactID;
445 }
446
447 if (!$create) {
448 return NULL;
449 }
450
451 // contact does not exist, lets create it
452 $params = array(
453 'contact_type' => 'Individual',
454 'email-Primary' => $email,
455 );
456
457 CRM_Utils_String::extractName($name, $params);
458
459 return CRM_Contact_BAO_Contact::createProfileContact($params,
460 CRM_Core_DAO::$_nullArray
461 );
462 }
463
464 }