Merge pull request #22859 from civicrm/5.47
[civicrm-core.git] / CRM / Mailing / BAO / BouncePattern.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Mailing_BAO_BouncePattern extends CRM_Mailing_DAO_BouncePattern {
18
19 /**
20 * Pseudo-constant pattern array.
21 * @var array
22 */
23 public static $_patterns = NULL;
24
25 /**
26 * Build the static pattern array.
27 */
28 public static function buildPatterns() {
29 self::$_patterns = [];
30 $bp = new CRM_Mailing_BAO_BouncePattern();
31 $bp->find();
32
33 while ($bp->fetch()) {
34 self::$_patterns[$bp->bounce_type_id][] = $bp->pattern;
35 }
36
37 foreach (self::$_patterns as $type => $patterns) {
38 if (count($patterns) == 1) {
39 self::$_patterns[$type] = '{(' . $patterns[0] . ')}im';
40 }
41 else {
42 self::$_patterns[$type] = '{(' . implode(')|(', $patterns) . ')}im';
43 }
44 }
45 }
46
47 /**
48 * Try to match the string to a bounce type.
49 *
50 * @param string $message
51 * The message to be matched.
52 *
53 * @return array
54 * Tuple (bounce_type, bounce_reason)
55 */
56 public static function match($message) {
57 // clean up $message and replace all white space by a single space, CRM-4767
58 $message = preg_replace('/\s+/', ' ', $message);
59
60 if (self::$_patterns == NULL) {
61 self::buildPatterns();
62 }
63
64 foreach (self::$_patterns as $type => $re) {
65 if (preg_match($re, $message, $matches)) {
66 $bounce = [
67 'bounce_type_id' => $type,
68 'bounce_reason' => $message,
69 ];
70 return $bounce;
71 }
72 }
73
74 $bounce = [
75 'bounce_type_id' => NULL,
76 'bounce_reason' => $message,
77 ];
78
79 return $bounce;
80 }
81
82 }