Completed
Branch dev (f14602)
by
unknown
23:59 queued 18:19
created
4_10_0_stages/EE_DMS_4_10_0_Event_Question_Group.dmsstage.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
     {
22 22
         global $wpdb;
23 23
         $this->_pretty_name = esc_html__('Event-Question Group Relations', 'event_espresso');
24
-        $this->_old_table = $wpdb->prefix . 'esp_event_question_group';
24
+        $this->_old_table = $wpdb->prefix.'esp_event_question_group';
25 25
         $this->_extra_where_sql = "WHERE EQG_primary = 0 AND EQG_additional=0";
26 26
         parent::__construct();
27 27
     }
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
             // in order to avoid locking the table for too long.
45 45
             $ids_to_update = $wpdb->get_col(
46 46
                 $wpdb->prepare(
47
-                    'SELECT EQG_ID FROM ' . $this->_old_table . ' WHERE EQG_primary=1 AND EVT_ID=%d AND QSG_ID=%d',
47
+                    'SELECT EQG_ID FROM '.$this->_old_table.' WHERE EQG_primary=1 AND EVT_ID=%d AND QSG_ID=%d',
48 48
                     $event_question_group['EVT_ID'],
49 49
                     $event_question_group['QSG_ID']
50 50
                 )
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
                     . $this->_old_table
57 57
                     . ' SET EQG_additional=1 WHERE EQG_ID IN ('
58 58
                     . implode(',', array_map('intval', $ids_to_update))
59
-                    . ') LIMIT ' . count($ids_to_update)
59
+                    . ') LIMIT '.count($ids_to_update)
60 60
                 );
61 61
             }
62 62
             if ($success) {
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
                     ],
70 70
                     ['%d']
71 71
                 );
72
-                if (!$successful_delete) {
72
+                if ( ! $successful_delete) {
73 73
                     $this->add_error(
74 74
                         sprintf(
75 75
                             esc_html__('Could not delete old event-question group relation row "%1$s" because "%2$s"', 'event_espresso'),
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
                         . $this->_old_table
97 97
                         . ' SET EQG_additional=1 WHERE EQG_ID IN ('
98 98
                         . implode(',', array_map('intval', $ids_to_update2))
99
-                        . ') LIMIT ' . count($ids_to_update2)
99
+                        . ') LIMIT '.count($ids_to_update2)
100 100
                     );
101 101
                 }
102 102
             }
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
     protected function _get_rows($limit)
116 116
     {
117 117
         global $wpdb;
118
-        $query = "SELECT * FROM {$this->_old_table} {$this->_extra_where_sql} " . $wpdb->prepare(
118
+        $query = "SELECT * FROM {$this->_old_table} {$this->_extra_where_sql} ".$wpdb->prepare(
119 119
             "LIMIT %d",
120 120
             $limit
121 121
         );
Please login to merge, or discard this patch.
Indentation   +130 added lines, -130 removed lines patch added patch discarded remove patch
@@ -11,138 +11,138 @@
 block discarded – undo
11 11
  */
12 12
 class EE_DMS_4_10_0_Event_Question_Group extends EE_Data_Migration_Script_Stage_Table
13 13
 {
14
-    /**
15
-     * Just initializes the status of the migration
16
-     */
17
-    public function __construct()
18
-    {
19
-        global $wpdb;
20
-        $this->_pretty_name = esc_html__('Event-Question Group Relations', 'event_espresso');
21
-        $this->_old_table = $wpdb->prefix . 'esp_event_question_group';
22
-        $this->_extra_where_sql = "WHERE EQG_primary = 0 AND EQG_additional=0";
23
-        parent::__construct();
24
-    }
14
+	/**
15
+	 * Just initializes the status of the migration
16
+	 */
17
+	public function __construct()
18
+	{
19
+		global $wpdb;
20
+		$this->_pretty_name = esc_html__('Event-Question Group Relations', 'event_espresso');
21
+		$this->_old_table = $wpdb->prefix . 'esp_event_question_group';
22
+		$this->_extra_where_sql = "WHERE EQG_primary = 0 AND EQG_additional=0";
23
+		parent::__construct();
24
+	}
25 25
 
26 26
 
27
-    /**
28
-     * Removes the duplicate event_question_group rows that only had EQG_primary=0. Now we just have one row
29
-     * joining event-to-question-groups with two columns: EQG_primary and EQG_additional, indicating which question
30
-     * groups apply to which category of registrant.
31
-     * @param array $event_question_group an associative array where keys are column names and values are their values.
32
-     * @return null
33
-     */
34
-    protected function _migrate_old_row($event_question_group)
35
-    {
36
-        if (isset($event_question_group['EVT_ID'], $event_question_group['QSG_ID'])) {
37
-            global $wpdb;
38
-            // If the question group was also for primary attendees, we should just update that row.
39
-            // And we delete this row.
40
-            // Updating all the rows could be slow on massive DBs, so do the slow selection first, then a quick update
41
-            // in order to avoid locking the table for too long.
42
-            $ids_to_update = $wpdb->get_col(
43
-                $wpdb->prepare(
44
-                    'SELECT EQG_ID FROM ' . $this->_old_table . ' WHERE EQG_primary=1 AND EVT_ID=%d AND QSG_ID=%d',
45
-                    $event_question_group['EVT_ID'],
46
-                    $event_question_group['QSG_ID']
47
-                )
48
-            );
49
-            $success = false;
50
-            if ($ids_to_update) {
51
-                $success = $wpdb->query(
52
-                    'UPDATE '
53
-                    . $this->_old_table
54
-                    . ' SET EQG_additional=1 WHERE EQG_ID IN ('
55
-                    . implode(',', array_map('intval', $ids_to_update))
56
-                    . ') LIMIT ' . count($ids_to_update)
57
-                );
58
-            }
59
-            if ($success) {
60
-                // Ok it's confirmed: the question group WAS for the primary attendee group too. So
61
-                // now we just need to delete this row.
62
-                $successful_delete = $wpdb->delete(
63
-                    $this->_old_table,
64
-                    [
65
-                        'EQG_ID' => $event_question_group['EQG_ID']
66
-                    ],
67
-                    ['%d']
68
-                );
69
-                if (!$successful_delete) {
70
-                    $this->add_error(
71
-                        sprintf(
72
-                            esc_html__('Could not delete old event-question group relation row "%1$s" because "%2$s"', 'event_espresso'),
73
-                            wp_json_encode($event_question_group),
74
-                            $wpdb->last_error
75
-                        )
76
-                    );
77
-                }
78
-            } else {
79
-                // Oh, the question group actually was NOT for the primary attendee. So we just need to update this row
80
-                // Let's do the selection separately from the deletion, this way we don't lock big tables for too long.
81
-                $ids_to_update2 = $wpdb->get_col(
82
-                    $wpdb->prepare(
83
-                        'SELECT EQG_ID FROM '
84
-                        . $this->_old_table
85
-                        . ' WHERE EVT_ID=%d AND QSG_ID=%d',
86
-                        $event_question_group['EVT_ID'],
87
-                        $event_question_group['QSG_ID']
88
-                    )
89
-                );
90
-                if ($ids_to_update2) {
91
-                    $wpdb->query(
92
-                        'UPDATE '
93
-                        . $this->_old_table
94
-                        . ' SET EQG_additional=1 WHERE EQG_ID IN ('
95
-                        . implode(',', array_map('intval', $ids_to_update2))
96
-                        . ') LIMIT ' . count($ids_to_update2)
97
-                    );
98
-                }
99
-            }
100
-        }
101
-    }
27
+	/**
28
+	 * Removes the duplicate event_question_group rows that only had EQG_primary=0. Now we just have one row
29
+	 * joining event-to-question-groups with two columns: EQG_primary and EQG_additional, indicating which question
30
+	 * groups apply to which category of registrant.
31
+	 * @param array $event_question_group an associative array where keys are column names and values are their values.
32
+	 * @return null
33
+	 */
34
+	protected function _migrate_old_row($event_question_group)
35
+	{
36
+		if (isset($event_question_group['EVT_ID'], $event_question_group['QSG_ID'])) {
37
+			global $wpdb;
38
+			// If the question group was also for primary attendees, we should just update that row.
39
+			// And we delete this row.
40
+			// Updating all the rows could be slow on massive DBs, so do the slow selection first, then a quick update
41
+			// in order to avoid locking the table for too long.
42
+			$ids_to_update = $wpdb->get_col(
43
+				$wpdb->prepare(
44
+					'SELECT EQG_ID FROM ' . $this->_old_table . ' WHERE EQG_primary=1 AND EVT_ID=%d AND QSG_ID=%d',
45
+					$event_question_group['EVT_ID'],
46
+					$event_question_group['QSG_ID']
47
+				)
48
+			);
49
+			$success = false;
50
+			if ($ids_to_update) {
51
+				$success = $wpdb->query(
52
+					'UPDATE '
53
+					. $this->_old_table
54
+					. ' SET EQG_additional=1 WHERE EQG_ID IN ('
55
+					. implode(',', array_map('intval', $ids_to_update))
56
+					. ') LIMIT ' . count($ids_to_update)
57
+				);
58
+			}
59
+			if ($success) {
60
+				// Ok it's confirmed: the question group WAS for the primary attendee group too. So
61
+				// now we just need to delete this row.
62
+				$successful_delete = $wpdb->delete(
63
+					$this->_old_table,
64
+					[
65
+						'EQG_ID' => $event_question_group['EQG_ID']
66
+					],
67
+					['%d']
68
+				);
69
+				if (!$successful_delete) {
70
+					$this->add_error(
71
+						sprintf(
72
+							esc_html__('Could not delete old event-question group relation row "%1$s" because "%2$s"', 'event_espresso'),
73
+							wp_json_encode($event_question_group),
74
+							$wpdb->last_error
75
+						)
76
+					);
77
+				}
78
+			} else {
79
+				// Oh, the question group actually was NOT for the primary attendee. So we just need to update this row
80
+				// Let's do the selection separately from the deletion, this way we don't lock big tables for too long.
81
+				$ids_to_update2 = $wpdb->get_col(
82
+					$wpdb->prepare(
83
+						'SELECT EQG_ID FROM '
84
+						. $this->_old_table
85
+						. ' WHERE EVT_ID=%d AND QSG_ID=%d',
86
+						$event_question_group['EVT_ID'],
87
+						$event_question_group['QSG_ID']
88
+					)
89
+				);
90
+				if ($ids_to_update2) {
91
+					$wpdb->query(
92
+						'UPDATE '
93
+						. $this->_old_table
94
+						. ' SET EQG_additional=1 WHERE EQG_ID IN ('
95
+						. implode(',', array_map('intval', $ids_to_update2))
96
+						. ') LIMIT ' . count($ids_to_update2)
97
+					);
98
+				}
99
+			}
100
+		}
101
+	}
102 102
 
103
-    /**
104
-     * Gets the rows for the existing table that shouldn't exist in 4.10.
105
-     * Specifically the rows where EQG_primary=false and EQG_additional=false.
106
-     * Gotcha: because the migration is REMOVING rows as it goes, we shouldn't use the offset.
107
-     *
108
-     * @global wpdb $wpdb
109
-     * @param int   $limit
110
-     * @return array of arrays like $wpdb->get_results($sql, ARRAY_A)
111
-     */
112
-    protected function _get_rows($limit)
113
-    {
114
-        global $wpdb;
115
-        $query = "SELECT * FROM {$this->_old_table} {$this->_extra_where_sql} " . $wpdb->prepare(
116
-            "LIMIT %d",
117
-            $limit
118
-        );
119
-        return $wpdb->get_results($query, ARRAY_A);
120
-    }
103
+	/**
104
+	 * Gets the rows for the existing table that shouldn't exist in 4.10.
105
+	 * Specifically the rows where EQG_primary=false and EQG_additional=false.
106
+	 * Gotcha: because the migration is REMOVING rows as it goes, we shouldn't use the offset.
107
+	 *
108
+	 * @global wpdb $wpdb
109
+	 * @param int   $limit
110
+	 * @return array of arrays like $wpdb->get_results($sql, ARRAY_A)
111
+	 */
112
+	protected function _get_rows($limit)
113
+	{
114
+		global $wpdb;
115
+		$query = "SELECT * FROM {$this->_old_table} {$this->_extra_where_sql} " . $wpdb->prepare(
116
+			"LIMIT %d",
117
+			$limit
118
+		);
119
+		return $wpdb->get_results($query, ARRAY_A);
120
+	}
121 121
 
122
-    /**
123
-     * Slight departure from the normal procedure here: because this removes rows from the DB, we need to ensure
124
-     * we count the records first, then do the migration.
125
-     *
126
-     * @param int $num_items
127
-     * @return int number of items ACTUALLY migrated
128
-     */
129
-    public function _migration_step($num_items = 50)
130
-    {
131
-        // Count the items right away. This migration step will be removing those rows, so we need to count them
132
-        // right away to get an accurate count.
133
-        $this->count_records_to_migrate();
134
-        $rows = $this->_get_rows($num_items);
135
-        $items_actually_migrated = 0;
136
-        foreach ($rows as $old_row) {
137
-            $this->_migrate_old_row($old_row);
138
-            $items_actually_migrated++;
139
-        }
140
-        if (
141
-            empty($rows)
142
-            || ($this->count_records_migrated() + $items_actually_migrated >= $this->count_records_to_migrate())
143
-        ) {
144
-            $this->set_completed();
145
-        }
146
-        return $items_actually_migrated;
147
-    }
122
+	/**
123
+	 * Slight departure from the normal procedure here: because this removes rows from the DB, we need to ensure
124
+	 * we count the records first, then do the migration.
125
+	 *
126
+	 * @param int $num_items
127
+	 * @return int number of items ACTUALLY migrated
128
+	 */
129
+	public function _migration_step($num_items = 50)
130
+	{
131
+		// Count the items right away. This migration step will be removing those rows, so we need to count them
132
+		// right away to get an accurate count.
133
+		$this->count_records_to_migrate();
134
+		$rows = $this->_get_rows($num_items);
135
+		$items_actually_migrated = 0;
136
+		foreach ($rows as $old_row) {
137
+			$this->_migrate_old_row($old_row);
138
+			$items_actually_migrated++;
139
+		}
140
+		if (
141
+			empty($rows)
142
+			|| ($this->count_records_migrated() + $items_actually_migrated >= $this->count_records_to_migrate())
143
+		) {
144
+			$this->set_completed();
145
+		}
146
+		return $items_actually_migrated;
147
+	}
148 148
 }
Please login to merge, or discard this patch.
core/services/request/sanitizers/AllowedTags.php 1 patch
Indentation   +280 added lines, -280 removed lines patch added patch discarded remove patch
@@ -12,284 +12,284 @@
 block discarded – undo
12 12
  */
13 13
 class AllowedTags
14 14
 {
15
-    /**
16
-     * @var array[]
17
-     */
18
-    private static $attributes = [
19
-        'accept-charset'    => 1,
20
-        'action'            => 1,
21
-        'alt'               => 1,
22
-        'allow'             => 1,
23
-        'allowfullscreen'   => 1,
24
-        'align'             => 1,
25
-        'aria-*'            => 1,
26
-        'autocomplete'      => 1,
27
-        'bgcolor'           => 1,
28
-        'border'            => 1,
29
-        'cellpadding'       => 1,
30
-        'cellspacing'       => 1,
31
-        'checked'           => 1,
32
-        'class'             => 1,
33
-        'cols'              => 1,
34
-        'content'           => 1,
35
-        'data-*'            => 1,
36
-        'dir'               => 1,
37
-        'disabled'          => 1,
38
-        'enctype'           => 1,
39
-        'for'               => 1,
40
-        'frameborder'       => 1,
41
-        'height'            => 1,
42
-        'href'              => 1,
43
-        'id'                => 1,
44
-        'itemprop'          => 1,
45
-        'itemscope'         => 1,
46
-        'itemtype'          => 1,
47
-        'label'             => 1,
48
-        'lang'              => 1,
49
-        'leftmargin'        => 1,
50
-        'marginheight'      => 1,
51
-        'marginwidth'       => 1,
52
-        'max'               => 1,
53
-        'maxlength'         => 1,
54
-        'media'             => 1,
55
-        'method'            => 1,
56
-        'min'               => 1,
57
-        'multiple'          => 1,
58
-        'name'              => 1,
59
-        'novalidate'        => 1,
60
-        'placeholder'       => 1,
61
-        'property'          => 1,
62
-        'readonly'          => 1,
63
-        'rel'               => 1,
64
-        'required'          => 1,
65
-        'rows'              => 1,
66
-        'selected'          => 1,
67
-        'src'               => 1,
68
-        'size'              => 1,
69
-        'style'             => 1,
70
-        'step'              => 1,
71
-        'tabindex'          => 1,
72
-        'target'            => 1,
73
-        'title'             => 1,
74
-        'topmargin'         => 1,
75
-        'type'              => 1,
76
-        'value'             => 1,
77
-        'width'             => 1,
78
-    ];
79
-
80
-
81
-    /**
82
-     * @var array
83
-     */
84
-    private static $tags = [
85
-        'a',
86
-        'abbr',
87
-        'b',
88
-        'br',
89
-        'code',
90
-        'div',
91
-        'em',
92
-        'h1',
93
-        'h2',
94
-        'h3',
95
-        'h4',
96
-        'h5',
97
-        'h6',
98
-        'hr',
99
-        'i',
100
-        'img',
101
-        'li',
102
-        'ol',
103
-        'p',
104
-        'pre',
105
-        'small',
106
-        'span',
107
-        'strong',
108
-        'table',
109
-        'td',
110
-        'tr',
111
-        'ul',
112
-    ];
113
-
114
-
115
-    /**
116
-     * @var array
117
-     */
118
-    private static $allowed_tags;
119
-
120
-
121
-    /**
122
-     * @var array
123
-     */
124
-    private static $allowed_with_embed_tags;
125
-
126
-
127
-    /**
128
-     * @var array
129
-     */
130
-    private static $allowed_with_form_tags;
131
-
132
-
133
-    /**
134
-     * @var array
135
-     */
136
-    private static $allowed_with_script_and_style_tags;
137
-
138
-    /**
139
-     * @var array
140
-     */
141
-    private static $allowed_with_full_tags;
142
-
143
-
144
-    /**
145
-     * merges additional tags and attributes into the WP post tags
146
-     */
147
-    private static function initializeAllowedTags()
148
-    {
149
-        $allowed_post_tags = wp_kses_allowed_html('post');
150
-        $allowed_tags = [];
151
-        foreach (AllowedTags::$tags as $tag) {
152
-            $allowed_tags[ $tag ] = AllowedTags::$attributes;
153
-        }
154
-        AllowedTags::$allowed_tags = array_merge_recursive($allowed_post_tags, $allowed_tags);
155
-    }
156
-
157
-
158
-    /**
159
-     * merges embed tags and attributes into the EE all tags
160
-     */
161
-    private static function initializeWithEmbedTags()
162
-    {
163
-        $all_tags = AllowedTags::getAllowedTags();
164
-        $embed_tags = [
165
-            'iframe' => AllowedTags::$attributes
166
-        ];
167
-        AllowedTags::$allowed_with_embed_tags = array_merge_recursive($all_tags, $embed_tags);
168
-    }
169
-
170
-
171
-    /**
172
-     * merges form tags and attributes into the EE all tags
173
-     */
174
-    private static function initializeWithFormTags()
175
-    {
176
-        $all_tags = AllowedTags::getAllowedTags();
177
-        $form_tags = [
178
-            'form'     => AllowedTags::$attributes,
179
-            'label'    => AllowedTags::$attributes,
180
-            'input'    => AllowedTags::$attributes,
181
-            'select'   => AllowedTags::$attributes,
182
-            'option'   => AllowedTags::$attributes,
183
-            'optgroup' => AllowedTags::$attributes,
184
-            'textarea' => AllowedTags::$attributes,
185
-            'button'   => AllowedTags::$attributes,
186
-            'fieldset' => AllowedTags::$attributes,
187
-            'output'   => AllowedTags::$attributes,
188
-        ];
189
-        AllowedTags::$allowed_with_form_tags = array_merge_recursive($all_tags, $form_tags);
190
-    }
191
-
192
-
193
-    /**
194
-     * merges form script and style tags and attributes into the EE all tags
195
-     */
196
-    private static function initializeWithScriptAndStyleTags()
197
-    {
198
-        $all_tags = AllowedTags::getAllowedTags();
199
-        $script_and_style_tags = [
200
-            'script'   => AllowedTags::$attributes,
201
-            'style'    => AllowedTags::$attributes,
202
-            'link'     => AllowedTags::$attributes,
203
-            'noscript' => AllowedTags::$attributes,
204
-        ];
205
-        AllowedTags::$allowed_with_script_and_style_tags = array_merge_recursive($all_tags, $script_and_style_tags);
206
-    }
207
-
208
-    /**
209
-     * merges all head and body tags and attributes into the EE all tags
210
-     */
211
-    private static function initializeWithFullTags()
212
-    {
213
-        $all_tags = AllowedTags::getAllowedTags();
214
-        $full_tags = [
215
-            'script'    => AllowedTags::$attributes,
216
-            'style'     => AllowedTags::$attributes,
217
-            'link'      => AllowedTags::$attributes,
218
-            'title'     => AllowedTags::$attributes,
219
-            'meta'      => AllowedTags::$attributes,
220
-            'iframe'    => AllowedTags::$attributes,
221
-            'form'      => AllowedTags::$attributes,
222
-            'label'     => AllowedTags::$attributes,
223
-            'input'     => AllowedTags::$attributes,
224
-            'select'    => AllowedTags::$attributes,
225
-            'option'    => AllowedTags::$attributes,
226
-            'optgroup'  => AllowedTags::$attributes,
227
-            'textarea'  => AllowedTags::$attributes,
228
-            'button'    => AllowedTags::$attributes,
229
-            'fieldset'  => AllowedTags::$attributes,
230
-            'output'    => AllowedTags::$attributes,
231
-            'noscript'  => AllowedTags::$attributes,
232
-        ];
233
-        AllowedTags::$allowed_with_full_tags = array_merge_recursive($all_tags, $full_tags);
234
-    }
235
-
236
-
237
-    /**
238
-     * @return array[]
239
-     */
240
-    public static function getAllowedTags()
241
-    {
242
-        if (empty(AllowedTags::$allowed_tags)) {
243
-            AllowedTags::initializeAllowedTags();
244
-        }
245
-        return AllowedTags::$allowed_tags;
246
-    }
247
-
248
-
249
-    /**
250
-     * @return array[]
251
-     */
252
-    public static function getWithEmbedTags()
253
-    {
254
-        if (empty(AllowedTags::$allowed_with_embed_tags)) {
255
-            AllowedTags::initializeWithEmbedTags();
256
-        }
257
-        return AllowedTags::$allowed_with_embed_tags;
258
-    }
259
-
260
-
261
-    /**
262
-     * @return array[]
263
-     */
264
-    public static function getWithFormTags()
265
-    {
266
-        if (empty(AllowedTags::$allowed_with_form_tags)) {
267
-            AllowedTags::initializeWithFormTags();
268
-        }
269
-        return AllowedTags::$allowed_with_form_tags;
270
-    }
271
-
272
-
273
-    /**
274
-     * @return array[]
275
-     */
276
-    public static function getWithScriptAndStyleTags()
277
-    {
278
-        if (empty(AllowedTags::$allowed_with_script_and_style_tags)) {
279
-            AllowedTags::initializeWithScriptAndStyleTags();
280
-        }
281
-        return AllowedTags::$allowed_with_script_and_style_tags;
282
-    }
283
-
284
-
285
-    /**
286
-     * @return array[]
287
-     */
288
-    public static function getWithFullTags()
289
-    {
290
-        if (empty(AllowedTags::$allowed_with_full_tags)) {
291
-            AllowedTags::initializeWithFullTags();
292
-        }
293
-        return AllowedTags::$allowed_with_full_tags;
294
-    }
15
+	/**
16
+	 * @var array[]
17
+	 */
18
+	private static $attributes = [
19
+		'accept-charset'    => 1,
20
+		'action'            => 1,
21
+		'alt'               => 1,
22
+		'allow'             => 1,
23
+		'allowfullscreen'   => 1,
24
+		'align'             => 1,
25
+		'aria-*'            => 1,
26
+		'autocomplete'      => 1,
27
+		'bgcolor'           => 1,
28
+		'border'            => 1,
29
+		'cellpadding'       => 1,
30
+		'cellspacing'       => 1,
31
+		'checked'           => 1,
32
+		'class'             => 1,
33
+		'cols'              => 1,
34
+		'content'           => 1,
35
+		'data-*'            => 1,
36
+		'dir'               => 1,
37
+		'disabled'          => 1,
38
+		'enctype'           => 1,
39
+		'for'               => 1,
40
+		'frameborder'       => 1,
41
+		'height'            => 1,
42
+		'href'              => 1,
43
+		'id'                => 1,
44
+		'itemprop'          => 1,
45
+		'itemscope'         => 1,
46
+		'itemtype'          => 1,
47
+		'label'             => 1,
48
+		'lang'              => 1,
49
+		'leftmargin'        => 1,
50
+		'marginheight'      => 1,
51
+		'marginwidth'       => 1,
52
+		'max'               => 1,
53
+		'maxlength'         => 1,
54
+		'media'             => 1,
55
+		'method'            => 1,
56
+		'min'               => 1,
57
+		'multiple'          => 1,
58
+		'name'              => 1,
59
+		'novalidate'        => 1,
60
+		'placeholder'       => 1,
61
+		'property'          => 1,
62
+		'readonly'          => 1,
63
+		'rel'               => 1,
64
+		'required'          => 1,
65
+		'rows'              => 1,
66
+		'selected'          => 1,
67
+		'src'               => 1,
68
+		'size'              => 1,
69
+		'style'             => 1,
70
+		'step'              => 1,
71
+		'tabindex'          => 1,
72
+		'target'            => 1,
73
+		'title'             => 1,
74
+		'topmargin'         => 1,
75
+		'type'              => 1,
76
+		'value'             => 1,
77
+		'width'             => 1,
78
+	];
79
+
80
+
81
+	/**
82
+	 * @var array
83
+	 */
84
+	private static $tags = [
85
+		'a',
86
+		'abbr',
87
+		'b',
88
+		'br',
89
+		'code',
90
+		'div',
91
+		'em',
92
+		'h1',
93
+		'h2',
94
+		'h3',
95
+		'h4',
96
+		'h5',
97
+		'h6',
98
+		'hr',
99
+		'i',
100
+		'img',
101
+		'li',
102
+		'ol',
103
+		'p',
104
+		'pre',
105
+		'small',
106
+		'span',
107
+		'strong',
108
+		'table',
109
+		'td',
110
+		'tr',
111
+		'ul',
112
+	];
113
+
114
+
115
+	/**
116
+	 * @var array
117
+	 */
118
+	private static $allowed_tags;
119
+
120
+
121
+	/**
122
+	 * @var array
123
+	 */
124
+	private static $allowed_with_embed_tags;
125
+
126
+
127
+	/**
128
+	 * @var array
129
+	 */
130
+	private static $allowed_with_form_tags;
131
+
132
+
133
+	/**
134
+	 * @var array
135
+	 */
136
+	private static $allowed_with_script_and_style_tags;
137
+
138
+	/**
139
+	 * @var array
140
+	 */
141
+	private static $allowed_with_full_tags;
142
+
143
+
144
+	/**
145
+	 * merges additional tags and attributes into the WP post tags
146
+	 */
147
+	private static function initializeAllowedTags()
148
+	{
149
+		$allowed_post_tags = wp_kses_allowed_html('post');
150
+		$allowed_tags = [];
151
+		foreach (AllowedTags::$tags as $tag) {
152
+			$allowed_tags[ $tag ] = AllowedTags::$attributes;
153
+		}
154
+		AllowedTags::$allowed_tags = array_merge_recursive($allowed_post_tags, $allowed_tags);
155
+	}
156
+
157
+
158
+	/**
159
+	 * merges embed tags and attributes into the EE all tags
160
+	 */
161
+	private static function initializeWithEmbedTags()
162
+	{
163
+		$all_tags = AllowedTags::getAllowedTags();
164
+		$embed_tags = [
165
+			'iframe' => AllowedTags::$attributes
166
+		];
167
+		AllowedTags::$allowed_with_embed_tags = array_merge_recursive($all_tags, $embed_tags);
168
+	}
169
+
170
+
171
+	/**
172
+	 * merges form tags and attributes into the EE all tags
173
+	 */
174
+	private static function initializeWithFormTags()
175
+	{
176
+		$all_tags = AllowedTags::getAllowedTags();
177
+		$form_tags = [
178
+			'form'     => AllowedTags::$attributes,
179
+			'label'    => AllowedTags::$attributes,
180
+			'input'    => AllowedTags::$attributes,
181
+			'select'   => AllowedTags::$attributes,
182
+			'option'   => AllowedTags::$attributes,
183
+			'optgroup' => AllowedTags::$attributes,
184
+			'textarea' => AllowedTags::$attributes,
185
+			'button'   => AllowedTags::$attributes,
186
+			'fieldset' => AllowedTags::$attributes,
187
+			'output'   => AllowedTags::$attributes,
188
+		];
189
+		AllowedTags::$allowed_with_form_tags = array_merge_recursive($all_tags, $form_tags);
190
+	}
191
+
192
+
193
+	/**
194
+	 * merges form script and style tags and attributes into the EE all tags
195
+	 */
196
+	private static function initializeWithScriptAndStyleTags()
197
+	{
198
+		$all_tags = AllowedTags::getAllowedTags();
199
+		$script_and_style_tags = [
200
+			'script'   => AllowedTags::$attributes,
201
+			'style'    => AllowedTags::$attributes,
202
+			'link'     => AllowedTags::$attributes,
203
+			'noscript' => AllowedTags::$attributes,
204
+		];
205
+		AllowedTags::$allowed_with_script_and_style_tags = array_merge_recursive($all_tags, $script_and_style_tags);
206
+	}
207
+
208
+	/**
209
+	 * merges all head and body tags and attributes into the EE all tags
210
+	 */
211
+	private static function initializeWithFullTags()
212
+	{
213
+		$all_tags = AllowedTags::getAllowedTags();
214
+		$full_tags = [
215
+			'script'    => AllowedTags::$attributes,
216
+			'style'     => AllowedTags::$attributes,
217
+			'link'      => AllowedTags::$attributes,
218
+			'title'     => AllowedTags::$attributes,
219
+			'meta'      => AllowedTags::$attributes,
220
+			'iframe'    => AllowedTags::$attributes,
221
+			'form'      => AllowedTags::$attributes,
222
+			'label'     => AllowedTags::$attributes,
223
+			'input'     => AllowedTags::$attributes,
224
+			'select'    => AllowedTags::$attributes,
225
+			'option'    => AllowedTags::$attributes,
226
+			'optgroup'  => AllowedTags::$attributes,
227
+			'textarea'  => AllowedTags::$attributes,
228
+			'button'    => AllowedTags::$attributes,
229
+			'fieldset'  => AllowedTags::$attributes,
230
+			'output'    => AllowedTags::$attributes,
231
+			'noscript'  => AllowedTags::$attributes,
232
+		];
233
+		AllowedTags::$allowed_with_full_tags = array_merge_recursive($all_tags, $full_tags);
234
+	}
235
+
236
+
237
+	/**
238
+	 * @return array[]
239
+	 */
240
+	public static function getAllowedTags()
241
+	{
242
+		if (empty(AllowedTags::$allowed_tags)) {
243
+			AllowedTags::initializeAllowedTags();
244
+		}
245
+		return AllowedTags::$allowed_tags;
246
+	}
247
+
248
+
249
+	/**
250
+	 * @return array[]
251
+	 */
252
+	public static function getWithEmbedTags()
253
+	{
254
+		if (empty(AllowedTags::$allowed_with_embed_tags)) {
255
+			AllowedTags::initializeWithEmbedTags();
256
+		}
257
+		return AllowedTags::$allowed_with_embed_tags;
258
+	}
259
+
260
+
261
+	/**
262
+	 * @return array[]
263
+	 */
264
+	public static function getWithFormTags()
265
+	{
266
+		if (empty(AllowedTags::$allowed_with_form_tags)) {
267
+			AllowedTags::initializeWithFormTags();
268
+		}
269
+		return AllowedTags::$allowed_with_form_tags;
270
+	}
271
+
272
+
273
+	/**
274
+	 * @return array[]
275
+	 */
276
+	public static function getWithScriptAndStyleTags()
277
+	{
278
+		if (empty(AllowedTags::$allowed_with_script_and_style_tags)) {
279
+			AllowedTags::initializeWithScriptAndStyleTags();
280
+		}
281
+		return AllowedTags::$allowed_with_script_and_style_tags;
282
+	}
283
+
284
+
285
+	/**
286
+	 * @return array[]
287
+	 */
288
+	public static function getWithFullTags()
289
+	{
290
+		if (empty(AllowedTags::$allowed_with_full_tags)) {
291
+			AllowedTags::initializeWithFullTags();
292
+		}
293
+		return AllowedTags::$allowed_with_full_tags;
294
+	}
295 295
 }
Please login to merge, or discard this patch.
admin_pages/general_settings/General_Settings_Admin_Page.core.php 1 patch
Indentation   +1427 added lines, -1427 removed lines patch added patch discarded remove patch
@@ -19,1444 +19,1444 @@
 block discarded – undo
19 19
  */
20 20
 class General_Settings_Admin_Page extends EE_Admin_Page
21 21
 {
22
-    /**
23
-     * @var EE_Core_Config
24
-     */
25
-    public $core_config;
26
-
27
-
28
-    /**
29
-     * Initialize basic properties.
30
-     */
31
-    protected function _init_page_props()
32
-    {
33
-        $this->page_slug        = GEN_SET_PG_SLUG;
34
-        $this->page_label       = GEN_SET_LABEL;
35
-        $this->_admin_base_url  = GEN_SET_ADMIN_URL;
36
-        $this->_admin_base_path = GEN_SET_ADMIN;
37
-
38
-        $this->core_config = EE_Registry::instance()->CFG->core;
39
-    }
40
-
41
-
42
-    /**
43
-     * Set ajax hooks
44
-     */
45
-    protected function _ajax_hooks()
46
-    {
47
-        add_action('wp_ajax_espresso_display_country_settings', [$this, 'display_country_settings']);
48
-        add_action('wp_ajax_espresso_display_country_states', [$this, 'display_country_states']);
49
-        add_action('wp_ajax_espresso_delete_state', [$this, 'delete_state'], 10, 3);
50
-        add_action('wp_ajax_espresso_add_new_state', [$this, 'add_new_state']);
51
-    }
52
-
53
-
54
-    /**
55
-     * More page properties initialization.
56
-     */
57
-    protected function _define_page_props()
58
-    {
59
-        $this->_admin_page_title = GEN_SET_LABEL;
60
-        $this->_labels           = ['publishbox' => esc_html__('Update Settings', 'event_espresso')];
61
-    }
62
-
63
-
64
-    /**
65
-     * Set page routes property.
66
-     */
67
-    protected function _set_page_routes()
68
-    {
69
-        $this->_page_routes = [
70
-            'critical_pages'                => [
71
-                'func'       => '_espresso_page_settings',
72
-                'capability' => 'manage_options',
73
-            ],
74
-            'update_espresso_page_settings' => [
75
-                'func'       => '_update_espresso_page_settings',
76
-                'capability' => 'manage_options',
77
-                'noheader'   => true,
78
-            ],
79
-            'default'                       => [
80
-                'func'       => '_your_organization_settings',
81
-                'capability' => 'manage_options',
82
-            ],
83
-
84
-            'update_your_organization_settings' => [
85
-                'func'       => '_update_your_organization_settings',
86
-                'capability' => 'manage_options',
87
-                'noheader'   => true,
88
-            ],
89
-
90
-            'admin_option_settings' => [
91
-                'func'       => '_admin_option_settings',
92
-                'capability' => 'manage_options',
93
-            ],
94
-
95
-            'update_admin_option_settings' => [
96
-                'func'       => '_update_admin_option_settings',
97
-                'capability' => 'manage_options',
98
-                'noheader'   => true,
99
-            ],
100
-
101
-            'country_settings' => [
102
-                'func'       => '_country_settings',
103
-                'capability' => 'manage_options',
104
-            ],
105
-
106
-            'update_country_settings' => [
107
-                'func'       => '_update_country_settings',
108
-                'capability' => 'manage_options',
109
-                'noheader'   => true,
110
-            ],
111
-
112
-            'display_country_settings' => [
113
-                'func'       => 'display_country_settings',
114
-                'capability' => 'manage_options',
115
-                'noheader'   => true,
116
-            ],
117
-
118
-            'add_new_state' => [
119
-                'func'       => 'add_new_state',
120
-                'capability' => 'manage_options',
121
-                'noheader'   => true,
122
-            ],
123
-
124
-            'delete_state'            => [
125
-                'func'       => 'delete_state',
126
-                'capability' => 'manage_options',
127
-                'noheader'   => true,
128
-            ],
129
-            'privacy_settings'        => [
130
-                'func'       => 'privacySettings',
131
-                'capability' => 'manage_options',
132
-            ],
133
-            'update_privacy_settings' => [
134
-                'func'               => 'updatePrivacySettings',
135
-                'capability'         => 'manage_options',
136
-                'noheader'           => true,
137
-                'headers_sent_route' => 'privacy_settings',
138
-            ],
139
-        ];
140
-    }
141
-
142
-
143
-    /**
144
-     * Set page configuration property
145
-     */
146
-    protected function _set_page_config()
147
-    {
148
-        $this->_page_config = [
149
-            'critical_pages'        => [
150
-                'nav'           => [
151
-                    'label' => esc_html__('Critical Pages', 'event_espresso'),
152
-                    'icon' => 'dashicons-warning',
153
-                    'order' => 50,
154
-                ],
155
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
156
-                'help_tabs'     => [
157
-                    'general_settings_critical_pages_help_tab' => [
158
-                        'title'    => esc_html__('Critical Pages', 'event_espresso'),
159
-                        'filename' => 'general_settings_critical_pages',
160
-                    ],
161
-                ],
162
-                'require_nonce' => false,
163
-            ],
164
-            'default'               => [
165
-                'nav'           => [
166
-                    'label' => esc_html__('Your Organization', 'event_espresso'),
167
-                    'icon' => 'dashicons-admin-home',
168
-                    'order' => 20,
169
-                ],
170
-                'help_tabs'     => [
171
-                    'general_settings_your_organization_help_tab' => [
172
-                        'title'    => esc_html__('Your Organization', 'event_espresso'),
173
-                        'filename' => 'general_settings_your_organization',
174
-                    ],
175
-                ],
176
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
177
-                'require_nonce' => false,
178
-            ],
179
-            'admin_option_settings' => [
180
-                'nav'           => [
181
-                    'label' => esc_html__('Admin Options', 'event_espresso'),
182
-                    'icon' => 'dashicons-admin-settings',
183
-                    'order' => 60,
184
-                ],
185
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
186
-                'help_tabs'     => [
187
-                    'general_settings_admin_options_help_tab' => [
188
-                        'title'    => esc_html__('Admin Options', 'event_espresso'),
189
-                        'filename' => 'general_settings_admin_options',
190
-                    ],
191
-                ],
192
-                'require_nonce' => false,
193
-            ],
194
-            'country_settings'      => [
195
-                'nav'           => [
196
-                    'label' => esc_html__('Countries', 'event_espresso'),
197
-                    'icon' => 'dashicons-admin-site',
198
-                    'order' => 70,
199
-                ],
200
-                'help_tabs'     => [
201
-                    'general_settings_countries_help_tab' => [
202
-                        'title'    => esc_html__('Countries', 'event_espresso'),
203
-                        'filename' => 'general_settings_countries',
204
-                    ],
205
-                ],
206
-                'require_nonce' => false,
207
-            ],
208
-            'privacy_settings'      => [
209
-                'nav'           => [
210
-                    'label' => esc_html__('Privacy', 'event_espresso'),
211
-                    'icon' => 'dashicons-privacy',
212
-                    'order' => 80,
213
-                ],
214
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
215
-                'require_nonce' => false,
216
-            ],
217
-        ];
218
-    }
219
-
220
-
221
-    protected function _add_screen_options()
222
-    {
223
-    }
224
-
225
-
226
-    protected function _add_feature_pointers()
227
-    {
228
-    }
229
-
230
-
231
-    /**
232
-     * Enqueue global scripts and styles for all routes in the General Settings Admin Pages.
233
-     */
234
-    public function load_scripts_styles()
235
-    {
236
-        // styles
237
-        wp_enqueue_style('espresso-ui-theme');
238
-        // scripts
239
-        wp_enqueue_script('ee_admin_js');
240
-    }
241
-
242
-
243
-    /**
244
-     * Execute logic running on `admin_init`
245
-     */
246
-    public function admin_init()
247
-    {
248
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = wp_strip_all_tags(
249
-            esc_html__(
250
-                'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
251
-                'event_espresso'
252
-            )
253
-        );
254
-        EE_Registry::$i18n_js_strings['error_occurred']          = wp_strip_all_tags(
255
-            esc_html__(
256
-                'An error occurred! Please refresh the page and try again.',
257
-                'event_espresso'
258
-            )
259
-        );
260
-        EE_Registry::$i18n_js_strings['confirm_delete_state']    = wp_strip_all_tags(
261
-            esc_html__(
262
-                'Are you sure you want to delete this State / Province?',
263
-                'event_espresso'
264
-            )
265
-        );
266
-        EE_Registry::$i18n_js_strings['ajax_url']                = admin_url(
267
-            'admin-ajax.php?page=espresso_general_settings',
268
-            is_ssl() ? 'https://' : 'http://'
269
-        );
270
-    }
271
-
272
-
273
-    public function admin_notices()
274
-    {
275
-    }
276
-
277
-
278
-    public function admin_footer_scripts()
279
-    {
280
-    }
281
-
282
-
283
-    /**
284
-     * Enqueue scripts and styles for the default route.
285
-     */
286
-    public function load_scripts_styles_default()
287
-    {
288
-        // styles
289
-        wp_enqueue_style('thickbox');
290
-        // scripts
291
-        wp_enqueue_script('media-upload');
292
-        wp_enqueue_script('thickbox');
293
-        wp_register_script(
294
-            'organization_settings',
295
-            GEN_SET_ASSETS_URL . 'your_organization_settings.js',
296
-            ['jquery', 'media-upload', 'thickbox'],
297
-            EVENT_ESPRESSO_VERSION,
298
-            true
299
-        );
300
-        wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', [], EVENT_ESPRESSO_VERSION);
301
-        wp_enqueue_script('organization_settings');
302
-        wp_enqueue_style('organization-css');
303
-        $confirm_image_delete = [
304
-            'text' => wp_strip_all_tags(
305
-                esc_html__(
306
-                    'Do you really want to delete this image? Please remember to save your settings to complete the removal.',
307
-                    'event_espresso'
308
-                )
309
-            ),
310
-        ];
311
-        wp_localize_script('organization_settings', 'confirm_image_delete', $confirm_image_delete);
312
-    }
313
-
314
-
315
-    /**
316
-     * Enqueue scripts and styles for the country settings route.
317
-     */
318
-    public function load_scripts_styles_country_settings()
319
-    {
320
-        // scripts
321
-        wp_register_script(
322
-            'gen_settings_countries',
323
-            GEN_SET_ASSETS_URL . 'gen_settings_countries.js',
324
-            ['ee_admin_js'],
325
-            EVENT_ESPRESSO_VERSION,
326
-            true
327
-        );
328
-        wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', [], EVENT_ESPRESSO_VERSION);
329
-        wp_enqueue_script('gen_settings_countries');
330
-        wp_enqueue_style('organization-css');
331
-    }
332
-
333
-
334
-    /*************        Espresso Pages        *************/
335
-    /**
336
-     * _espresso_page_settings
337
-     *
338
-     * @throws EE_Error
339
-     * @throws DomainException
340
-     * @throws DomainException
341
-     * @throws InvalidDataTypeException
342
-     * @throws InvalidArgumentException
343
-     */
344
-    protected function _espresso_page_settings()
345
-    {
346
-        // Check to make sure all of the main pages are set up properly,
347
-        // if not create the default pages and display an admin notice
348
-        EEH_Activation::verify_default_pages_exist();
349
-        $this->_transient_garbage_collection();
350
-
351
-        $this->_template_args['values'] = $this->_yes_no_values;
352
-
353
-        $this->_template_args['reg_page_id']  = $this->core_config->reg_page_id ?? null;
354
-        $this->_template_args['reg_page_obj'] = isset($this->core_config->reg_page_id)
355
-            ? get_post($this->core_config->reg_page_id)
356
-            : false;
357
-
358
-        $this->_template_args['txn_page_id']  = $this->core_config->txn_page_id ?? null;
359
-        $this->_template_args['txn_page_obj'] = isset($this->core_config->txn_page_id)
360
-            ? get_post($this->core_config->txn_page_id)
361
-            : false;
362
-
363
-        $this->_template_args['thank_you_page_id']  = $this->core_config->thank_you_page_id ?? null;
364
-        $this->_template_args['thank_you_page_obj'] = isset($this->core_config->thank_you_page_id)
365
-            ? get_post($this->core_config->thank_you_page_id)
366
-            : false;
367
-
368
-        $this->_template_args['cancel_page_id']  = $this->core_config->cancel_page_id ?? null;
369
-        $this->_template_args['cancel_page_obj'] = isset($this->core_config->cancel_page_id)
370
-            ? get_post($this->core_config->cancel_page_id)
371
-            : false;
372
-
373
-        $this->_set_add_edit_form_tags('update_espresso_page_settings');
374
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
375
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
376
-            GEN_SET_TEMPLATE_PATH . 'espresso_page_settings.template.php',
377
-            $this->_template_args,
378
-            true
379
-        );
380
-        $this->display_admin_page_with_sidebar();
381
-    }
382
-
383
-
384
-    /**
385
-     * Handler for updating espresso page settings.
386
-     *
387
-     * @throws EE_Error
388
-     */
389
-    protected function _update_espresso_page_settings()
390
-    {
391
-        $this->core_config = EE_Registry::instance()->CFG->core;
392
-        // capture incoming request data && set page IDs
393
-        $this->core_config->reg_page_id       = $this->request->getRequestParam(
394
-            'reg_page_id',
395
-            $this->core_config->reg_page_id,
396
-            DataType::INT
397
-        );
398
-        $this->core_config->txn_page_id       = $this->request->getRequestParam(
399
-            'txn_page_id',
400
-            $this->core_config->txn_page_id,
401
-            DataType::INT
402
-        );
403
-        $this->core_config->thank_you_page_id = $this->request->getRequestParam(
404
-            'thank_you_page_id',
405
-            $this->core_config->thank_you_page_id,
406
-            DataType::INT
407
-        );
408
-        $this->core_config->cancel_page_id    = $this->request->getRequestParam(
409
-            'cancel_page_id',
410
-            $this->core_config->cancel_page_id,
411
-            DataType::INT
412
-        );
413
-
414
-        $this->core_config = apply_filters(
415
-            'FHEE__General_Settings_Admin_Page___update_espresso_page_settings__CFG_core',
416
-            $this->core_config,
417
-            $this->request->requestParams()
418
-        );
419
-
420
-        $what = esc_html__('Critical Pages & Shortcodes', 'event_espresso');
421
-        $this->_redirect_after_action(
422
-            $this->_update_espresso_configuration(
423
-                $what,
424
-                $this->core_config,
425
-                __FILE__,
426
-                __FUNCTION__,
427
-                __LINE__
428
-            ),
429
-            $what,
430
-            '',
431
-            [
432
-                'action' => 'critical_pages',
433
-            ],
434
-            true
435
-        );
436
-    }
437
-
438
-
439
-    /*************        Your Organization        *************/
440
-
441
-
442
-    /**
443
-     * @throws DomainException
444
-     * @throws EE_Error
445
-     * @throws InvalidArgumentException
446
-     * @throws InvalidDataTypeException
447
-     * @throws InvalidInterfaceException
448
-     */
449
-    protected function _your_organization_settings()
450
-    {
451
-        $this->_template_args['admin_page_content'] = '';
452
-        try {
453
-            /** @var OrganizationSettings $organization_settings_form */
454
-            $organization_settings_form = $this->loader->getShared(OrganizationSettings::class);
455
-
456
-            $this->_template_args['admin_page_content'] = EEH_HTML::div(
457
-                $organization_settings_form->display(),
458
-                '',
459
-                'padding'
460
-            );
461
-        } catch (Exception $e) {
462
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
463
-        }
464
-        $this->_set_add_edit_form_tags('update_your_organization_settings');
465
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
466
-        $this->display_admin_page_with_sidebar();
467
-    }
468
-
469
-
470
-    /**
471
-     * Handler for updating organization settings.
472
-     *
473
-     * @throws EE_Error
474
-     */
475
-    protected function _update_your_organization_settings()
476
-    {
477
-        try {
478
-            /** @var OrganizationSettings $organization_settings_form */
479
-            $organization_settings_form = $this->loader->getShared(OrganizationSettings::class);
480
-
481
-            $success = $organization_settings_form->process($this->request->requestParams());
482
-
483
-            EE_Registry::instance()->CFG = apply_filters(
484
-                'FHEE__General_Settings_Admin_Page___update_your_organization_settings__CFG',
485
-                EE_Registry::instance()->CFG
486
-            );
487
-        } catch (Exception $e) {
488
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
489
-            $success = false;
490
-        }
491
-
492
-        if ($success) {
493
-            $success = $this->_update_espresso_configuration(
494
-                esc_html__('Your Organization Settings', 'event_espresso'),
495
-                EE_Registry::instance()->CFG,
496
-                __FILE__,
497
-                __FUNCTION__,
498
-                __LINE__
499
-            );
500
-        }
501
-
502
-        $this->_redirect_after_action($success, '', '', ['action' => 'default'], true);
503
-    }
504
-
505
-
506
-
507
-    /*************        Admin Options        *************/
508
-
509
-
510
-    /**
511
-     * _admin_option_settings
512
-     *
513
-     * @throws EE_Error
514
-     * @throws LogicException
515
-     */
516
-    protected function _admin_option_settings()
517
-    {
518
-        $this->_template_args['admin_page_content'] = '';
519
-        try {
520
-            $admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
521
-            // still need this for the old school form in Extend_General_Settings_Admin_Page
522
-            $this->_template_args['values'] = $this->_yes_no_values;
523
-            // also need to account for the do_action that was in the old template
524
-            $admin_options_settings_form->setTemplateArgs($this->_template_args);
525
-            $this->_template_args['admin_page_content'] = EEH_HTML::div(
526
-                $admin_options_settings_form->display(),
527
-                '',
528
-                'padding'
529
-            );
530
-        } catch (Exception $e) {
531
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
532
-        }
533
-        $this->_set_add_edit_form_tags('update_admin_option_settings');
534
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
535
-        $this->display_admin_page_with_sidebar();
536
-    }
537
-
538
-
539
-    /**
540
-     * _update_admin_option_settings
541
-     *
542
-     * @throws EE_Error
543
-     * @throws InvalidDataTypeException
544
-     * @throws InvalidFormSubmissionException
545
-     * @throws InvalidArgumentException
546
-     * @throws LogicException
547
-     */
548
-    protected function _update_admin_option_settings()
549
-    {
550
-        try {
551
-            $admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
552
-            $admin_options_settings_form->process(
553
-                $this->request->getRequestParam(
554
-                    $admin_options_settings_form->slug(),
555
-                    [],
556
-                    DataType::STRING,
557
-                    true
558
-                )
559
-            );
560
-            EE_Registry::instance()->CFG->admin = apply_filters(
561
-                'FHEE__General_Settings_Admin_Page___update_admin_option_settings__CFG_admin',
562
-                EE_Registry::instance()->CFG->admin
563
-            );
564
-        } catch (Exception $e) {
565
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
566
-        }
567
-        $this->_redirect_after_action(
568
-            apply_filters(
569
-                'FHEE__General_Settings_Admin_Page___update_admin_option_settings__success',
570
-                $this->_update_espresso_configuration(
571
-                    esc_html__('Admin Options', 'event_espresso'),
572
-                    EE_Registry::instance()->CFG->admin,
573
-                    __FILE__,
574
-                    __FUNCTION__,
575
-                    __LINE__
576
-                )
577
-            ),
578
-            esc_html__('Admin Options', 'event_espresso'),
579
-            'updated',
580
-            ['action' => 'admin_option_settings']
581
-        );
582
-    }
583
-
584
-
585
-    /*************        Countries        *************/
586
-
587
-
588
-    /**
589
-     * @param string|null $default
590
-     * @return string
591
-     */
592
-    protected function getCountryISO(?string $default = null): string
593
-    {
594
-        $default = $default ?? $this->getCountryIsoForSite();
595
-        $CNT_ISO = $this->request->getRequestParam('country', $default);
596
-        $CNT_ISO = $this->request->getRequestParam('CNT_ISO', $CNT_ISO);
597
-        return strtoupper($CNT_ISO);
598
-    }
599
-
600
-
601
-    /**
602
-     * @return string
603
-     */
604
-    protected function getCountryIsoForSite(): string
605
-    {
606
-        return ! empty(EE_Registry::instance()->CFG->organization->CNT_ISO)
607
-            ? EE_Registry::instance()->CFG->organization->CNT_ISO
608
-            : 'US';
609
-    }
610
-
611
-
612
-    /**
613
-     * @param string          $CNT_ISO
614
-     * @param EE_Country|null $country
615
-     * @return EE_Base_Class|EE_Country
616
-     * @throws EE_Error
617
-     * @throws InvalidArgumentException
618
-     * @throws InvalidDataTypeException
619
-     * @throws InvalidInterfaceException
620
-     * @throws ReflectionException
621
-     */
622
-    protected function verifyOrGetCountryFromIso(string $CNT_ISO, ?EE_Country $country = null)
623
-    {
624
-        /** @var EE_Country $country */
625
-        return $country instanceof EE_Country && $country->ID() === $CNT_ISO
626
-            ? $country
627
-            : EEM_Country::instance()->get_one_by_ID($CNT_ISO);
628
-    }
629
-
630
-
631
-    /**
632
-     * Output Country Settings view.
633
-     *
634
-     * @throws DomainException
635
-     * @throws EE_Error
636
-     * @throws InvalidArgumentException
637
-     * @throws InvalidDataTypeException
638
-     * @throws InvalidInterfaceException
639
-     * @throws ReflectionException
640
-     */
641
-    protected function _country_settings()
642
-    {
643
-        $CNT_ISO = $this->getCountryISO();
644
-
645
-        $this->_template_args['values']    = $this->_yes_no_values;
646
-        $this->_template_args['countries'] = new EE_Question_Form_Input(
647
-            EE_Question::new_instance(
648
-                [
649
-                  'QST_ID'           => 0,
650
-                  'QST_display_text' => esc_html__('Select Country', 'event_espresso'),
651
-                  'QST_system'       => 'admin-country',
652
-                ]
653
-            ),
654
-            EE_Answer::new_instance(
655
-                [
656
-                    'ANS_ID'    => 0,
657
-                    'ANS_value' => $CNT_ISO,
658
-                ]
659
-            ),
660
-            [
661
-                'input_id'       => 'country',
662
-                'input_name'     => 'country',
663
-                'input_prefix'   => '',
664
-                'append_qstn_id' => false,
665
-            ]
666
-        );
667
-
668
-        $country = $this->verifyOrGetCountryFromIso($CNT_ISO);
669
-        add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'country_form_field_label_wrap'], 10);
670
-        add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'country_form_field_input__wrap'], 10);
671
-        $this->_template_args['country_details_settings'] = $this->display_country_settings(
672
-            $country->ID(),
673
-            $country
674
-        );
675
-        $this->_template_args['country_states_settings']  = $this->display_country_states(
676
-            $country->ID(),
677
-            $country
678
-        );
679
-        $this->_template_args['CNT_name_for_site']        = $country->name();
680
-
681
-        $this->_set_add_edit_form_tags('update_country_settings');
682
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
683
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
684
-            GEN_SET_TEMPLATE_PATH . 'countries_settings.template.php',
685
-            $this->_template_args,
686
-            true
687
-        );
688
-        $this->display_admin_page_with_no_sidebar();
689
-    }
690
-
691
-
692
-    /**
693
-     * @param string          $CNT_ISO
694
-     * @param EE_Country|null $country
695
-     * @return string
696
-     * @throws DomainException
697
-     * @throws EE_Error
698
-     * @throws InvalidArgumentException
699
-     * @throws InvalidDataTypeException
700
-     * @throws InvalidInterfaceException
701
-     * @throws ReflectionException
702
-     */
703
-    public function display_country_settings(string $CNT_ISO = '', ?EE_Country $country = null): string
704
-    {
705
-        $CNT_ISO          = $this->getCountryISO($CNT_ISO);
706
-        $CNT_ISO_for_site = $this->getCountryIsoForSite();
707
-
708
-        if (! $CNT_ISO) {
709
-            return '';
710
-        }
711
-
712
-        // for ajax
713
-        remove_all_filters('FHEE__EEH_Form_Fields__label_html');
714
-        remove_all_filters('FHEE__EEH_Form_Fields__input_html');
715
-        add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'country_form_field_label_wrap'], 10, 2);
716
-        add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'country_form_field_input__wrap'], 10, 2);
717
-        $country                                  = $this->verifyOrGetCountryFromIso($CNT_ISO, $country);
718
-        $CNT_cur_disabled                         = $CNT_ISO !== $CNT_ISO_for_site;
719
-        $this->_template_args['CNT_cur_disabled'] = $CNT_cur_disabled;
720
-
721
-        $country_input_types            = [
722
-            'CNT_active'      => [
723
-                'type'             => 'RADIO_BTN',
724
-                'input_name'       => "cntry[$CNT_ISO]",
725
-                'class'            => '',
726
-                'options'          => $this->_yes_no_values,
727
-                'use_desc_4_label' => true,
728
-            ],
729
-            'CNT_ISO'         => [
730
-                'type'       => 'TEXT',
731
-                'input_name' => "cntry[$CNT_ISO]",
732
-                'class'      => 'ee-input-width--small',
733
-            ],
734
-            'CNT_ISO3'        => [
735
-                'type'       => 'TEXT',
736
-                'input_name' => "cntry[$CNT_ISO]",
737
-                'class'      => 'ee-input-width--small',
738
-            ],
739
-            // 'RGN_ID'          => [
740
-            //     'type'       => 'TEXT',
741
-            //     'input_name' => "cntry[$CNT_ISO]",
742
-            //     'class'      => 'ee-input-width--small',
743
-            // ],
744
-            'CNT_name'        => [
745
-                'type'       => 'TEXT',
746
-                'input_name' => "cntry[$CNT_ISO]",
747
-                'class'      => 'ee-input-width--big',
748
-            ],
749
-            'CNT_cur_code'    => [
750
-                'type'       => 'TEXT',
751
-                'input_name' => "cntry[$CNT_ISO]",
752
-                'class'      => 'ee-input-width--small',
753
-                'disabled'   => $CNT_cur_disabled,
754
-            ],
755
-            'CNT_cur_single'  => [
756
-                'type'       => 'TEXT',
757
-                'input_name' => "cntry[$CNT_ISO]",
758
-                'class'      => 'ee-input-width--reg',
759
-                'disabled'   => $CNT_cur_disabled,
760
-            ],
761
-            'CNT_cur_plural'  => [
762
-                'type'       => 'TEXT',
763
-                'input_name' => "cntry[$CNT_ISO]",
764
-                'class'      => 'ee-input-width--reg',
765
-                'disabled'   => $CNT_cur_disabled,
766
-            ],
767
-            'CNT_cur_sign'    => [
768
-                'type'         => 'TEXT',
769
-                'input_name'   => "cntry[$CNT_ISO]",
770
-                'class'        => 'ee-input-width--small',
771
-                'htmlentities' => false,
772
-                'disabled'     => $CNT_cur_disabled,
773
-            ],
774
-            'CNT_cur_sign_b4' => [
775
-                'type'             => 'RADIO_BTN',
776
-                'input_name'       => "cntry[$CNT_ISO]",
777
-                'class'            => '',
778
-                'options'          => $this->_yes_no_values,
779
-                'use_desc_4_label' => true,
780
-                'disabled'         => $CNT_cur_disabled,
781
-            ],
782
-            'CNT_cur_dec_plc' => [
783
-                'type'       => 'RADIO_BTN',
784
-                'input_name' => "cntry[$CNT_ISO]",
785
-                'class'      => '',
786
-                'options'    => [
787
-                    ['id' => 0, 'text' => ''],
788
-                    ['id' => 1, 'text' => ''],
789
-                    ['id' => 2, 'text' => ''],
790
-                    ['id' => 3, 'text' => ''],
791
-                ],
792
-                'disabled'   => $CNT_cur_disabled,
793
-            ],
794
-            'CNT_cur_dec_mrk' => [
795
-                'type'             => 'RADIO_BTN',
796
-                'input_name'       => "cntry[$CNT_ISO]",
797
-                'class'            => '',
798
-                'options'          => [
799
-                    [
800
-                        'id'   => ',',
801
-                        'text' => esc_html__(', (comma)', 'event_espresso'),
802
-                    ],
803
-                    ['id' => '.', 'text' => esc_html__('. (decimal)', 'event_espresso')],
804
-                ],
805
-                'use_desc_4_label' => true,
806
-                'disabled'         => $CNT_cur_disabled,
807
-            ],
808
-            'CNT_cur_thsnds'  => [
809
-                'type'             => 'RADIO_BTN',
810
-                'input_name'       => "cntry[$CNT_ISO]",
811
-                'class'            => '',
812
-                'options'          => [
813
-                    [
814
-                        'id'   => ',',
815
-                        'text' => esc_html__(', (comma)', 'event_espresso'),
816
-                    ],
817
-                    [
818
-                        'id'   => '.',
819
-                        'text' => esc_html__('. (decimal)', 'event_espresso'),
820
-                    ],
821
-                    [
822
-                        'id'   => ' ',
823
-                        'text' => esc_html__('(space)', 'event_espresso'),
824
-                    ],
825
-                    [
826
-                        'id'   => '_',
827
-                        'text' => esc_html__('_ (underscore)', 'event_espresso'),
828
-                    ],
829
-                    [
830
-                        'id'   => "'",
831
-                        'text' => esc_html__("' (apostrophe)", 'event_espresso'),
832
-                    ],
833
-                ],
834
-                'use_desc_4_label' => true,
835
-                'disabled'         => $CNT_cur_disabled,
836
-            ],
837
-            'CNT_tel_code'    => [
838
-                'type'       => 'TEXT',
839
-                'input_name' => "cntry[$CNT_ISO]",
840
-                'class'      => 'ee-input-width--small',
841
-            ],
842
-            'CNT_is_EU'       => [
843
-                'type'             => 'RADIO_BTN',
844
-                'input_name'       => "cntry[$CNT_ISO]",
845
-                'class'            => '',
846
-                'options'          => $this->_yes_no_values,
847
-                'use_desc_4_label' => true,
848
-            ],
849
-        ];
850
-        $this->_template_args['inputs'] = EE_Question_Form_Input::generate_question_form_inputs_for_object(
851
-            $country,
852
-            $country_input_types
853
-        );
854
-        $country_details_settings       = EEH_Template::display_template(
855
-            GEN_SET_TEMPLATE_PATH . 'country_details_settings.template.php',
856
-            $this->_template_args,
857
-            true
858
-        );
859
-
860
-        if (defined('DOING_AJAX')) {
861
-            $notices = EE_Error::get_notices(false, false, false);
862
-            echo wp_json_encode(
863
-                [
864
-                    'return_data' => $country_details_settings,
865
-                    'success'     => $notices['success'],
866
-                    'errors'      => $notices['errors'],
867
-                ]
868
-            );
869
-            die();
870
-        }
871
-        return $country_details_settings;
872
-    }
873
-
874
-
875
-    /**
876
-     * @param string          $CNT_ISO
877
-     * @param EE_Country|null $country
878
-     * @return string
879
-     * @throws DomainException
880
-     * @throws EE_Error
881
-     * @throws InvalidArgumentException
882
-     * @throws InvalidDataTypeException
883
-     * @throws InvalidInterfaceException
884
-     * @throws ReflectionException
885
-     */
886
-    public function display_country_states(string $CNT_ISO = '', ?EE_Country $country = null): string
887
-    {
888
-        $CNT_ISO = $this->getCountryISO($CNT_ISO);
889
-        if (! $CNT_ISO) {
890
-            return '';
891
-        }
892
-        // for ajax
893
-        remove_all_filters('FHEE__EEH_Form_Fields__label_html');
894
-        remove_all_filters('FHEE__EEH_Form_Fields__input_html');
895
-        add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'state_form_field_label_wrap'], 10, 2);
896
-        add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'state_form_field_input__wrap'], 10);
897
-        $states = EEM_State::instance()->get_all_states_for_these_countries([$CNT_ISO => $CNT_ISO]);
898
-        if (empty($states)) {
899
-            /** @var EventEspresso\core\services\address\CountrySubRegionDao $countrySubRegionDao */
900
-            $countrySubRegionDao = $this->loader->getShared(
901
-                'EventEspresso\core\services\address\CountrySubRegionDao'
902
-            );
903
-            if ($countrySubRegionDao instanceof EventEspresso\core\services\address\CountrySubRegionDao) {
904
-                $country = $this->verifyOrGetCountryFromIso($CNT_ISO, $country);
905
-                if ($countrySubRegionDao->saveCountrySubRegions($country)) {
906
-                    $states = EEM_State::instance()->get_all_states_for_these_countries([$CNT_ISO => $CNT_ISO]);
907
-                }
908
-            }
909
-        }
910
-        if (is_array($states)) {
911
-            foreach ($states as $STA_ID => $state) {
912
-                if ($state instanceof EE_State) {
913
-                    $inputs = EE_Question_Form_Input::generate_question_form_inputs_for_object(
914
-                        $state,
915
-                        [
916
-                            'STA_abbrev' => [
917
-                                'type'             => 'TEXT',
918
-                                'label'            => esc_html__('Code', 'event_espresso'),
919
-                                'input_name'       => "states[$STA_ID]",
920
-                                'class'            => 'ee-input-width--tiny',
921
-                                'add_mobile_label' => true,
922
-                            ],
923
-                            'STA_name'   => [
924
-                                'type'             => 'TEXT',
925
-                                'label'            => esc_html__('Name', 'event_espresso'),
926
-                                'input_name'       => "states[$STA_ID]",
927
-                                'class'            => 'ee-input-width--big',
928
-                                'add_mobile_label' => true,
929
-                            ],
930
-                            'STA_active' => [
931
-                                'type'             => 'RADIO_BTN',
932
-                                'label'            => esc_html__(
933
-                                    'State Appears in Dropdown Select Lists',
934
-                                    'event_espresso'
935
-                                ),
936
-                                'input_name'       => "states[$STA_ID]",
937
-                                'options'          => $this->_yes_no_values,
938
-                                'use_desc_4_label' => true,
939
-                                'add_mobile_label' => true,
940
-                            ],
941
-                        ]
942
-                    );
943
-
944
-                    $delete_state_url = EE_Admin_Page::add_query_args_and_nonce(
945
-                        [
946
-                            'action'     => 'delete_state',
947
-                            'STA_ID'     => $STA_ID,
948
-                            'CNT_ISO'    => $CNT_ISO,
949
-                            'STA_abbrev' => $state->abbrev(),
950
-                        ],
951
-                        GEN_SET_ADMIN_URL
952
-                    );
953
-
954
-                    $this->_template_args['states'][ $STA_ID ]['inputs']           = $inputs;
955
-                    $this->_template_args['states'][ $STA_ID ]['delete_state_url'] = $delete_state_url;
956
-                }
957
-            }
958
-        } else {
959
-            $this->_template_args['states'] = false;
960
-        }
961
-
962
-        $this->_template_args['add_new_state_url'] = EE_Admin_Page::add_query_args_and_nonce(
963
-            ['action' => 'add_new_state'],
964
-            GEN_SET_ADMIN_URL
965
-        );
966
-
967
-        $state_details_settings = EEH_Template::display_template(
968
-            GEN_SET_TEMPLATE_PATH . 'state_details_settings.template.php',
969
-            $this->_template_args,
970
-            true
971
-        );
972
-
973
-        if (defined('DOING_AJAX')) {
974
-            $notices = EE_Error::get_notices(false, false, false);
975
-            echo wp_json_encode(
976
-                [
977
-                    'return_data' => $state_details_settings,
978
-                    'success'     => $notices['success'],
979
-                    'errors'      => $notices['errors'],
980
-                ]
981
-            );
982
-            die();
983
-        }
984
-        return $state_details_settings;
985
-    }
986
-
987
-
988
-    /**
989
-     * @return void
990
-     * @throws EE_Error
991
-     * @throws InvalidArgumentException
992
-     * @throws InvalidDataTypeException
993
-     * @throws InvalidInterfaceException
994
-     * @throws ReflectionException
995
-     */
996
-    public function add_new_state()
997
-    {
998
-        $success = true;
999
-        $CNT_ISO = $this->getCountryISO('');
1000
-        if (! $CNT_ISO) {
1001
-            EE_Error::add_error(
1002
-                esc_html__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
1003
-                __FILE__,
1004
-                __FUNCTION__,
1005
-                __LINE__
1006
-            );
1007
-            $success = false;
1008
-        }
1009
-        $STA_abbrev = $this->request->getRequestParam('STA_abbrev');
1010
-        if (! $STA_abbrev) {
1011
-            EE_Error::add_error(
1012
-                esc_html__('No State ISO code or an invalid State ISO code was received.', 'event_espresso'),
1013
-                __FILE__,
1014
-                __FUNCTION__,
1015
-                __LINE__
1016
-            );
1017
-            $success = false;
1018
-        }
1019
-        $STA_name = $this->request->getRequestParam('STA_name');
1020
-        if (! $STA_name) {
1021
-            EE_Error::add_error(
1022
-                esc_html__('No State name or an invalid State name was received.', 'event_espresso'),
1023
-                __FILE__,
1024
-                __FUNCTION__,
1025
-                __LINE__
1026
-            );
1027
-            $success = false;
1028
-        }
1029
-
1030
-        if ($success) {
1031
-            $cols_n_values = [
1032
-                'CNT_ISO'    => $CNT_ISO,
1033
-                'STA_abbrev' => $STA_abbrev,
1034
-                'STA_name'   => $STA_name,
1035
-                'STA_active' => true,
1036
-            ];
1037
-            $success       = EEM_State::instance()->insert($cols_n_values);
1038
-            EE_Error::add_success(esc_html__('The State was added successfully.', 'event_espresso'));
1039
-        }
1040
-
1041
-        if (defined('DOING_AJAX')) {
1042
-            $notices = EE_Error::get_notices(false, false, false);
1043
-            echo wp_json_encode(array_merge($notices, ['return_data' => $CNT_ISO]));
1044
-            die();
1045
-        }
1046
-        $this->_redirect_after_action(
1047
-            $success,
1048
-            esc_html__('State', 'event_espresso'),
1049
-            'added',
1050
-            ['action' => 'country_settings']
1051
-        );
1052
-    }
1053
-
1054
-
1055
-    /**
1056
-     * @return void
1057
-     * @throws EE_Error
1058
-     * @throws InvalidArgumentException
1059
-     * @throws InvalidDataTypeException
1060
-     * @throws InvalidInterfaceException
1061
-     * @throws ReflectionException
1062
-     */
1063
-    public function delete_state()
1064
-    {
1065
-        $CNT_ISO    = $this->getCountryISO();
1066
-        $STA_ID     = $this->request->getRequestParam('STA_ID');
1067
-        $STA_abbrev = $this->request->getRequestParam('STA_abbrev');
1068
-
1069
-        if (! $STA_ID) {
1070
-            EE_Error::add_error(
1071
-                esc_html__('No State ID or an invalid State ID was received.', 'event_espresso'),
1072
-                __FILE__,
1073
-                __FUNCTION__,
1074
-                __LINE__
1075
-            );
1076
-            return;
1077
-        }
1078
-
1079
-        $success = EEM_State::instance()->delete_by_ID($STA_ID);
1080
-        if ($success !== false) {
1081
-            do_action(
1082
-                'AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
1083
-                $CNT_ISO,
1084
-                $STA_ID,
1085
-                ['STA_abbrev' => $STA_abbrev]
1086
-            );
1087
-            EE_Error::add_success(esc_html__('The State was deleted successfully.', 'event_espresso'));
1088
-        }
1089
-        if (defined('DOING_AJAX')) {
1090
-            $notices                = EE_Error::get_notices(false);
1091
-            $notices['return_data'] = true;
1092
-            echo wp_json_encode($notices);
1093
-            die();
1094
-        }
1095
-        $this->_redirect_after_action(
1096
-            $success,
1097
-            esc_html__('State', 'event_espresso'),
1098
-            'deleted',
1099
-            ['action' => 'country_settings']
1100
-        );
1101
-    }
1102
-
1103
-
1104
-    /**
1105
-     * @return void
1106
-     * @throws EE_Error
1107
-     * @throws InvalidArgumentException
1108
-     * @throws InvalidDataTypeException
1109
-     * @throws InvalidInterfaceException
1110
-     * @throws ReflectionException
1111
-     */
1112
-    protected function _update_country_settings()
1113
-    {
1114
-        $CNT_ISO = $this->getCountryISO();
1115
-        if (! $CNT_ISO) {
1116
-            EE_Error::add_error(
1117
-                esc_html__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
1118
-                __FILE__,
1119
-                __FUNCTION__,
1120
-                __LINE__
1121
-            );
1122
-            return;
1123
-        }
1124
-
1125
-        $country = $this->verifyOrGetCountryFromIso($CNT_ISO);
1126
-
1127
-        $cols_n_values                    = [];
1128
-        $cols_n_values['CNT_ISO3']        = strtoupper(
1129
-            $this->request->getRequestParam('cntry', $country->ISO3())
1130
-        );
1131
-        $cols_n_values['CNT_name']        = $this->request->getRequestParam(
1132
-            "cntry[$CNT_ISO][CNT_name]",
1133
-            $country->name()
1134
-        );
1135
-        $cols_n_values['CNT_cur_code']    = strtoupper(
1136
-            $this->request->getRequestParam(
1137
-                "cntry[$CNT_ISO][CNT_cur_code]",
1138
-                $country->currency_code()
1139
-            )
1140
-        );
1141
-        $cols_n_values['CNT_cur_single']  = $this->request->getRequestParam(
1142
-            "cntry[$CNT_ISO][CNT_cur_single]",
1143
-            $country->currency_name_single()
1144
-        );
1145
-        $cols_n_values['CNT_cur_plural']  = $this->request->getRequestParam(
1146
-            "cntry[$CNT_ISO][CNT_cur_plural]",
1147
-            $country->currency_name_plural()
1148
-        );
1149
-        $cols_n_values['CNT_cur_sign']    = $this->request->getRequestParam(
1150
-            "cntry[$CNT_ISO][CNT_cur_sign]",
1151
-            $country->currency_sign()
1152
-        );
1153
-        $cols_n_values['CNT_cur_sign_b4'] = $this->request->getRequestParam(
1154
-            "cntry[$CNT_ISO][CNT_cur_sign_b4]",
1155
-            $country->currency_sign_before(),
1156
-            DataType::BOOL
1157
-        );
1158
-        $cols_n_values['CNT_cur_dec_plc'] = $this->request->getRequestParam(
1159
-            "cntry[$CNT_ISO][CNT_cur_dec_plc]",
1160
-            $country->currency_decimal_places()
1161
-        );
1162
-        $cols_n_values['CNT_cur_dec_mrk'] = $this->request->getRequestParam(
1163
-            "cntry[$CNT_ISO][CNT_cur_dec_mrk]",
1164
-            $country->currency_decimal_mark()
1165
-        );
1166
-        $cols_n_values['CNT_cur_thsnds']  = $this->request->getRequestParam(
1167
-            "cntry[$CNT_ISO][CNT_cur_thsnds]",
1168
-            $country->currency_thousands_separator()
1169
-        );
1170
-        $cols_n_values['CNT_tel_code']    = $this->request->getRequestParam(
1171
-            "cntry[$CNT_ISO][CNT_tel_code]",
1172
-            $country->telephoneCode()
1173
-        );
1174
-        $cols_n_values['CNT_active']      = $this->request->getRequestParam(
1175
-            "cntry[$CNT_ISO][CNT_active]",
1176
-            $country->isActive(),
1177
-            DataType::BOOL
1178
-        );
1179
-
1180
-        // allow filtering of country data
1181
-        $cols_n_values = apply_filters(
1182
-            'FHEE__General_Settings_Admin_Page___update_country_settings__cols_n_values',
1183
-            $cols_n_values
1184
-        );
1185
-
1186
-        // where values
1187
-        $where_cols_n_values = [['CNT_ISO' => $CNT_ISO]];
1188
-        // run the update
1189
-        $success = EEM_Country::instance()->update($cols_n_values, $where_cols_n_values);
1190
-
1191
-        // allow filtering of states data
1192
-        $states = apply_filters(
1193
-            'FHEE__General_Settings_Admin_Page___update_country_settings__states',
1194
-            $this->request->getRequestParam('states', [], DataType::STRING, true)
1195
-        );
1196
-
1197
-        if (! empty($states) && $success !== false) {
1198
-            // loop thru state data ( looks like : states[75][STA_name] )
1199
-            foreach ($states as $STA_ID => $state) {
1200
-                $cols_n_values = [
1201
-                    'CNT_ISO'    => $CNT_ISO,
1202
-                    'STA_abbrev' => sanitize_text_field($state['STA_abbrev']),
1203
-                    'STA_name'   => sanitize_text_field($state['STA_name']),
1204
-                    'STA_active' => filter_var($state['STA_active'], FILTER_VALIDATE_BOOLEAN),
1205
-                ];
1206
-                // where values
1207
-                $where_cols_n_values = [['STA_ID' => $STA_ID]];
1208
-                // run the update
1209
-                $success = EEM_State::instance()->update($cols_n_values, $where_cols_n_values);
1210
-                if ($success !== false) {
1211
-                    do_action(
1212
-                        'AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
1213
-                        $CNT_ISO,
1214
-                        $STA_ID,
1215
-                        $cols_n_values
1216
-                    );
1217
-                }
1218
-            }
1219
-        }
1220
-        // check if country being edited matches org option country, and if so, then  update EE_Config with new settings
1221
-        if (
1222
-            isset(EE_Registry::instance()->CFG->organization->CNT_ISO)
1223
-            && $CNT_ISO == EE_Registry::instance()->CFG->organization->CNT_ISO
1224
-        ) {
1225
-            EE_Registry::instance()->CFG->currency = new EE_Currency_Config($CNT_ISO);
1226
-            EE_Registry::instance()->CFG->update_espresso_config();
1227
-        }
1228
-
1229
-        if ($success !== false) {
1230
-            EE_Error::add_success(
1231
-                esc_html__('Country Settings updated successfully.', 'event_espresso')
1232
-            );
1233
-        }
1234
-        $this->_redirect_after_action(
1235
-            $success,
1236
-            '',
1237
-            '',
1238
-            ['action' => 'country_settings', 'country' => $CNT_ISO],
1239
-            true
1240
-        );
1241
-    }
1242
-
1243
-
1244
-    /**
1245
-     * form_form_field_label_wrap
1246
-     *
1247
-     * @param string $label
1248
-     * @return string
1249
-     */
1250
-    public function country_form_field_label_wrap(string $label): string
1251
-    {
1252
-        return '
22
+	/**
23
+	 * @var EE_Core_Config
24
+	 */
25
+	public $core_config;
26
+
27
+
28
+	/**
29
+	 * Initialize basic properties.
30
+	 */
31
+	protected function _init_page_props()
32
+	{
33
+		$this->page_slug        = GEN_SET_PG_SLUG;
34
+		$this->page_label       = GEN_SET_LABEL;
35
+		$this->_admin_base_url  = GEN_SET_ADMIN_URL;
36
+		$this->_admin_base_path = GEN_SET_ADMIN;
37
+
38
+		$this->core_config = EE_Registry::instance()->CFG->core;
39
+	}
40
+
41
+
42
+	/**
43
+	 * Set ajax hooks
44
+	 */
45
+	protected function _ajax_hooks()
46
+	{
47
+		add_action('wp_ajax_espresso_display_country_settings', [$this, 'display_country_settings']);
48
+		add_action('wp_ajax_espresso_display_country_states', [$this, 'display_country_states']);
49
+		add_action('wp_ajax_espresso_delete_state', [$this, 'delete_state'], 10, 3);
50
+		add_action('wp_ajax_espresso_add_new_state', [$this, 'add_new_state']);
51
+	}
52
+
53
+
54
+	/**
55
+	 * More page properties initialization.
56
+	 */
57
+	protected function _define_page_props()
58
+	{
59
+		$this->_admin_page_title = GEN_SET_LABEL;
60
+		$this->_labels           = ['publishbox' => esc_html__('Update Settings', 'event_espresso')];
61
+	}
62
+
63
+
64
+	/**
65
+	 * Set page routes property.
66
+	 */
67
+	protected function _set_page_routes()
68
+	{
69
+		$this->_page_routes = [
70
+			'critical_pages'                => [
71
+				'func'       => '_espresso_page_settings',
72
+				'capability' => 'manage_options',
73
+			],
74
+			'update_espresso_page_settings' => [
75
+				'func'       => '_update_espresso_page_settings',
76
+				'capability' => 'manage_options',
77
+				'noheader'   => true,
78
+			],
79
+			'default'                       => [
80
+				'func'       => '_your_organization_settings',
81
+				'capability' => 'manage_options',
82
+			],
83
+
84
+			'update_your_organization_settings' => [
85
+				'func'       => '_update_your_organization_settings',
86
+				'capability' => 'manage_options',
87
+				'noheader'   => true,
88
+			],
89
+
90
+			'admin_option_settings' => [
91
+				'func'       => '_admin_option_settings',
92
+				'capability' => 'manage_options',
93
+			],
94
+
95
+			'update_admin_option_settings' => [
96
+				'func'       => '_update_admin_option_settings',
97
+				'capability' => 'manage_options',
98
+				'noheader'   => true,
99
+			],
100
+
101
+			'country_settings' => [
102
+				'func'       => '_country_settings',
103
+				'capability' => 'manage_options',
104
+			],
105
+
106
+			'update_country_settings' => [
107
+				'func'       => '_update_country_settings',
108
+				'capability' => 'manage_options',
109
+				'noheader'   => true,
110
+			],
111
+
112
+			'display_country_settings' => [
113
+				'func'       => 'display_country_settings',
114
+				'capability' => 'manage_options',
115
+				'noheader'   => true,
116
+			],
117
+
118
+			'add_new_state' => [
119
+				'func'       => 'add_new_state',
120
+				'capability' => 'manage_options',
121
+				'noheader'   => true,
122
+			],
123
+
124
+			'delete_state'            => [
125
+				'func'       => 'delete_state',
126
+				'capability' => 'manage_options',
127
+				'noheader'   => true,
128
+			],
129
+			'privacy_settings'        => [
130
+				'func'       => 'privacySettings',
131
+				'capability' => 'manage_options',
132
+			],
133
+			'update_privacy_settings' => [
134
+				'func'               => 'updatePrivacySettings',
135
+				'capability'         => 'manage_options',
136
+				'noheader'           => true,
137
+				'headers_sent_route' => 'privacy_settings',
138
+			],
139
+		];
140
+	}
141
+
142
+
143
+	/**
144
+	 * Set page configuration property
145
+	 */
146
+	protected function _set_page_config()
147
+	{
148
+		$this->_page_config = [
149
+			'critical_pages'        => [
150
+				'nav'           => [
151
+					'label' => esc_html__('Critical Pages', 'event_espresso'),
152
+					'icon' => 'dashicons-warning',
153
+					'order' => 50,
154
+				],
155
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
156
+				'help_tabs'     => [
157
+					'general_settings_critical_pages_help_tab' => [
158
+						'title'    => esc_html__('Critical Pages', 'event_espresso'),
159
+						'filename' => 'general_settings_critical_pages',
160
+					],
161
+				],
162
+				'require_nonce' => false,
163
+			],
164
+			'default'               => [
165
+				'nav'           => [
166
+					'label' => esc_html__('Your Organization', 'event_espresso'),
167
+					'icon' => 'dashicons-admin-home',
168
+					'order' => 20,
169
+				],
170
+				'help_tabs'     => [
171
+					'general_settings_your_organization_help_tab' => [
172
+						'title'    => esc_html__('Your Organization', 'event_espresso'),
173
+						'filename' => 'general_settings_your_organization',
174
+					],
175
+				],
176
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
177
+				'require_nonce' => false,
178
+			],
179
+			'admin_option_settings' => [
180
+				'nav'           => [
181
+					'label' => esc_html__('Admin Options', 'event_espresso'),
182
+					'icon' => 'dashicons-admin-settings',
183
+					'order' => 60,
184
+				],
185
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
186
+				'help_tabs'     => [
187
+					'general_settings_admin_options_help_tab' => [
188
+						'title'    => esc_html__('Admin Options', 'event_espresso'),
189
+						'filename' => 'general_settings_admin_options',
190
+					],
191
+				],
192
+				'require_nonce' => false,
193
+			],
194
+			'country_settings'      => [
195
+				'nav'           => [
196
+					'label' => esc_html__('Countries', 'event_espresso'),
197
+					'icon' => 'dashicons-admin-site',
198
+					'order' => 70,
199
+				],
200
+				'help_tabs'     => [
201
+					'general_settings_countries_help_tab' => [
202
+						'title'    => esc_html__('Countries', 'event_espresso'),
203
+						'filename' => 'general_settings_countries',
204
+					],
205
+				],
206
+				'require_nonce' => false,
207
+			],
208
+			'privacy_settings'      => [
209
+				'nav'           => [
210
+					'label' => esc_html__('Privacy', 'event_espresso'),
211
+					'icon' => 'dashicons-privacy',
212
+					'order' => 80,
213
+				],
214
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
215
+				'require_nonce' => false,
216
+			],
217
+		];
218
+	}
219
+
220
+
221
+	protected function _add_screen_options()
222
+	{
223
+	}
224
+
225
+
226
+	protected function _add_feature_pointers()
227
+	{
228
+	}
229
+
230
+
231
+	/**
232
+	 * Enqueue global scripts and styles for all routes in the General Settings Admin Pages.
233
+	 */
234
+	public function load_scripts_styles()
235
+	{
236
+		// styles
237
+		wp_enqueue_style('espresso-ui-theme');
238
+		// scripts
239
+		wp_enqueue_script('ee_admin_js');
240
+	}
241
+
242
+
243
+	/**
244
+	 * Execute logic running on `admin_init`
245
+	 */
246
+	public function admin_init()
247
+	{
248
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = wp_strip_all_tags(
249
+			esc_html__(
250
+				'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
251
+				'event_espresso'
252
+			)
253
+		);
254
+		EE_Registry::$i18n_js_strings['error_occurred']          = wp_strip_all_tags(
255
+			esc_html__(
256
+				'An error occurred! Please refresh the page and try again.',
257
+				'event_espresso'
258
+			)
259
+		);
260
+		EE_Registry::$i18n_js_strings['confirm_delete_state']    = wp_strip_all_tags(
261
+			esc_html__(
262
+				'Are you sure you want to delete this State / Province?',
263
+				'event_espresso'
264
+			)
265
+		);
266
+		EE_Registry::$i18n_js_strings['ajax_url']                = admin_url(
267
+			'admin-ajax.php?page=espresso_general_settings',
268
+			is_ssl() ? 'https://' : 'http://'
269
+		);
270
+	}
271
+
272
+
273
+	public function admin_notices()
274
+	{
275
+	}
276
+
277
+
278
+	public function admin_footer_scripts()
279
+	{
280
+	}
281
+
282
+
283
+	/**
284
+	 * Enqueue scripts and styles for the default route.
285
+	 */
286
+	public function load_scripts_styles_default()
287
+	{
288
+		// styles
289
+		wp_enqueue_style('thickbox');
290
+		// scripts
291
+		wp_enqueue_script('media-upload');
292
+		wp_enqueue_script('thickbox');
293
+		wp_register_script(
294
+			'organization_settings',
295
+			GEN_SET_ASSETS_URL . 'your_organization_settings.js',
296
+			['jquery', 'media-upload', 'thickbox'],
297
+			EVENT_ESPRESSO_VERSION,
298
+			true
299
+		);
300
+		wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', [], EVENT_ESPRESSO_VERSION);
301
+		wp_enqueue_script('organization_settings');
302
+		wp_enqueue_style('organization-css');
303
+		$confirm_image_delete = [
304
+			'text' => wp_strip_all_tags(
305
+				esc_html__(
306
+					'Do you really want to delete this image? Please remember to save your settings to complete the removal.',
307
+					'event_espresso'
308
+				)
309
+			),
310
+		];
311
+		wp_localize_script('organization_settings', 'confirm_image_delete', $confirm_image_delete);
312
+	}
313
+
314
+
315
+	/**
316
+	 * Enqueue scripts and styles for the country settings route.
317
+	 */
318
+	public function load_scripts_styles_country_settings()
319
+	{
320
+		// scripts
321
+		wp_register_script(
322
+			'gen_settings_countries',
323
+			GEN_SET_ASSETS_URL . 'gen_settings_countries.js',
324
+			['ee_admin_js'],
325
+			EVENT_ESPRESSO_VERSION,
326
+			true
327
+		);
328
+		wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', [], EVENT_ESPRESSO_VERSION);
329
+		wp_enqueue_script('gen_settings_countries');
330
+		wp_enqueue_style('organization-css');
331
+	}
332
+
333
+
334
+	/*************        Espresso Pages        *************/
335
+	/**
336
+	 * _espresso_page_settings
337
+	 *
338
+	 * @throws EE_Error
339
+	 * @throws DomainException
340
+	 * @throws DomainException
341
+	 * @throws InvalidDataTypeException
342
+	 * @throws InvalidArgumentException
343
+	 */
344
+	protected function _espresso_page_settings()
345
+	{
346
+		// Check to make sure all of the main pages are set up properly,
347
+		// if not create the default pages and display an admin notice
348
+		EEH_Activation::verify_default_pages_exist();
349
+		$this->_transient_garbage_collection();
350
+
351
+		$this->_template_args['values'] = $this->_yes_no_values;
352
+
353
+		$this->_template_args['reg_page_id']  = $this->core_config->reg_page_id ?? null;
354
+		$this->_template_args['reg_page_obj'] = isset($this->core_config->reg_page_id)
355
+			? get_post($this->core_config->reg_page_id)
356
+			: false;
357
+
358
+		$this->_template_args['txn_page_id']  = $this->core_config->txn_page_id ?? null;
359
+		$this->_template_args['txn_page_obj'] = isset($this->core_config->txn_page_id)
360
+			? get_post($this->core_config->txn_page_id)
361
+			: false;
362
+
363
+		$this->_template_args['thank_you_page_id']  = $this->core_config->thank_you_page_id ?? null;
364
+		$this->_template_args['thank_you_page_obj'] = isset($this->core_config->thank_you_page_id)
365
+			? get_post($this->core_config->thank_you_page_id)
366
+			: false;
367
+
368
+		$this->_template_args['cancel_page_id']  = $this->core_config->cancel_page_id ?? null;
369
+		$this->_template_args['cancel_page_obj'] = isset($this->core_config->cancel_page_id)
370
+			? get_post($this->core_config->cancel_page_id)
371
+			: false;
372
+
373
+		$this->_set_add_edit_form_tags('update_espresso_page_settings');
374
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
375
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
376
+			GEN_SET_TEMPLATE_PATH . 'espresso_page_settings.template.php',
377
+			$this->_template_args,
378
+			true
379
+		);
380
+		$this->display_admin_page_with_sidebar();
381
+	}
382
+
383
+
384
+	/**
385
+	 * Handler for updating espresso page settings.
386
+	 *
387
+	 * @throws EE_Error
388
+	 */
389
+	protected function _update_espresso_page_settings()
390
+	{
391
+		$this->core_config = EE_Registry::instance()->CFG->core;
392
+		// capture incoming request data && set page IDs
393
+		$this->core_config->reg_page_id       = $this->request->getRequestParam(
394
+			'reg_page_id',
395
+			$this->core_config->reg_page_id,
396
+			DataType::INT
397
+		);
398
+		$this->core_config->txn_page_id       = $this->request->getRequestParam(
399
+			'txn_page_id',
400
+			$this->core_config->txn_page_id,
401
+			DataType::INT
402
+		);
403
+		$this->core_config->thank_you_page_id = $this->request->getRequestParam(
404
+			'thank_you_page_id',
405
+			$this->core_config->thank_you_page_id,
406
+			DataType::INT
407
+		);
408
+		$this->core_config->cancel_page_id    = $this->request->getRequestParam(
409
+			'cancel_page_id',
410
+			$this->core_config->cancel_page_id,
411
+			DataType::INT
412
+		);
413
+
414
+		$this->core_config = apply_filters(
415
+			'FHEE__General_Settings_Admin_Page___update_espresso_page_settings__CFG_core',
416
+			$this->core_config,
417
+			$this->request->requestParams()
418
+		);
419
+
420
+		$what = esc_html__('Critical Pages & Shortcodes', 'event_espresso');
421
+		$this->_redirect_after_action(
422
+			$this->_update_espresso_configuration(
423
+				$what,
424
+				$this->core_config,
425
+				__FILE__,
426
+				__FUNCTION__,
427
+				__LINE__
428
+			),
429
+			$what,
430
+			'',
431
+			[
432
+				'action' => 'critical_pages',
433
+			],
434
+			true
435
+		);
436
+	}
437
+
438
+
439
+	/*************        Your Organization        *************/
440
+
441
+
442
+	/**
443
+	 * @throws DomainException
444
+	 * @throws EE_Error
445
+	 * @throws InvalidArgumentException
446
+	 * @throws InvalidDataTypeException
447
+	 * @throws InvalidInterfaceException
448
+	 */
449
+	protected function _your_organization_settings()
450
+	{
451
+		$this->_template_args['admin_page_content'] = '';
452
+		try {
453
+			/** @var OrganizationSettings $organization_settings_form */
454
+			$organization_settings_form = $this->loader->getShared(OrganizationSettings::class);
455
+
456
+			$this->_template_args['admin_page_content'] = EEH_HTML::div(
457
+				$organization_settings_form->display(),
458
+				'',
459
+				'padding'
460
+			);
461
+		} catch (Exception $e) {
462
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
463
+		}
464
+		$this->_set_add_edit_form_tags('update_your_organization_settings');
465
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
466
+		$this->display_admin_page_with_sidebar();
467
+	}
468
+
469
+
470
+	/**
471
+	 * Handler for updating organization settings.
472
+	 *
473
+	 * @throws EE_Error
474
+	 */
475
+	protected function _update_your_organization_settings()
476
+	{
477
+		try {
478
+			/** @var OrganizationSettings $organization_settings_form */
479
+			$organization_settings_form = $this->loader->getShared(OrganizationSettings::class);
480
+
481
+			$success = $organization_settings_form->process($this->request->requestParams());
482
+
483
+			EE_Registry::instance()->CFG = apply_filters(
484
+				'FHEE__General_Settings_Admin_Page___update_your_organization_settings__CFG',
485
+				EE_Registry::instance()->CFG
486
+			);
487
+		} catch (Exception $e) {
488
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
489
+			$success = false;
490
+		}
491
+
492
+		if ($success) {
493
+			$success = $this->_update_espresso_configuration(
494
+				esc_html__('Your Organization Settings', 'event_espresso'),
495
+				EE_Registry::instance()->CFG,
496
+				__FILE__,
497
+				__FUNCTION__,
498
+				__LINE__
499
+			);
500
+		}
501
+
502
+		$this->_redirect_after_action($success, '', '', ['action' => 'default'], true);
503
+	}
504
+
505
+
506
+
507
+	/*************        Admin Options        *************/
508
+
509
+
510
+	/**
511
+	 * _admin_option_settings
512
+	 *
513
+	 * @throws EE_Error
514
+	 * @throws LogicException
515
+	 */
516
+	protected function _admin_option_settings()
517
+	{
518
+		$this->_template_args['admin_page_content'] = '';
519
+		try {
520
+			$admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
521
+			// still need this for the old school form in Extend_General_Settings_Admin_Page
522
+			$this->_template_args['values'] = $this->_yes_no_values;
523
+			// also need to account for the do_action that was in the old template
524
+			$admin_options_settings_form->setTemplateArgs($this->_template_args);
525
+			$this->_template_args['admin_page_content'] = EEH_HTML::div(
526
+				$admin_options_settings_form->display(),
527
+				'',
528
+				'padding'
529
+			);
530
+		} catch (Exception $e) {
531
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
532
+		}
533
+		$this->_set_add_edit_form_tags('update_admin_option_settings');
534
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
535
+		$this->display_admin_page_with_sidebar();
536
+	}
537
+
538
+
539
+	/**
540
+	 * _update_admin_option_settings
541
+	 *
542
+	 * @throws EE_Error
543
+	 * @throws InvalidDataTypeException
544
+	 * @throws InvalidFormSubmissionException
545
+	 * @throws InvalidArgumentException
546
+	 * @throws LogicException
547
+	 */
548
+	protected function _update_admin_option_settings()
549
+	{
550
+		try {
551
+			$admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
552
+			$admin_options_settings_form->process(
553
+				$this->request->getRequestParam(
554
+					$admin_options_settings_form->slug(),
555
+					[],
556
+					DataType::STRING,
557
+					true
558
+				)
559
+			);
560
+			EE_Registry::instance()->CFG->admin = apply_filters(
561
+				'FHEE__General_Settings_Admin_Page___update_admin_option_settings__CFG_admin',
562
+				EE_Registry::instance()->CFG->admin
563
+			);
564
+		} catch (Exception $e) {
565
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
566
+		}
567
+		$this->_redirect_after_action(
568
+			apply_filters(
569
+				'FHEE__General_Settings_Admin_Page___update_admin_option_settings__success',
570
+				$this->_update_espresso_configuration(
571
+					esc_html__('Admin Options', 'event_espresso'),
572
+					EE_Registry::instance()->CFG->admin,
573
+					__FILE__,
574
+					__FUNCTION__,
575
+					__LINE__
576
+				)
577
+			),
578
+			esc_html__('Admin Options', 'event_espresso'),
579
+			'updated',
580
+			['action' => 'admin_option_settings']
581
+		);
582
+	}
583
+
584
+
585
+	/*************        Countries        *************/
586
+
587
+
588
+	/**
589
+	 * @param string|null $default
590
+	 * @return string
591
+	 */
592
+	protected function getCountryISO(?string $default = null): string
593
+	{
594
+		$default = $default ?? $this->getCountryIsoForSite();
595
+		$CNT_ISO = $this->request->getRequestParam('country', $default);
596
+		$CNT_ISO = $this->request->getRequestParam('CNT_ISO', $CNT_ISO);
597
+		return strtoupper($CNT_ISO);
598
+	}
599
+
600
+
601
+	/**
602
+	 * @return string
603
+	 */
604
+	protected function getCountryIsoForSite(): string
605
+	{
606
+		return ! empty(EE_Registry::instance()->CFG->organization->CNT_ISO)
607
+			? EE_Registry::instance()->CFG->organization->CNT_ISO
608
+			: 'US';
609
+	}
610
+
611
+
612
+	/**
613
+	 * @param string          $CNT_ISO
614
+	 * @param EE_Country|null $country
615
+	 * @return EE_Base_Class|EE_Country
616
+	 * @throws EE_Error
617
+	 * @throws InvalidArgumentException
618
+	 * @throws InvalidDataTypeException
619
+	 * @throws InvalidInterfaceException
620
+	 * @throws ReflectionException
621
+	 */
622
+	protected function verifyOrGetCountryFromIso(string $CNT_ISO, ?EE_Country $country = null)
623
+	{
624
+		/** @var EE_Country $country */
625
+		return $country instanceof EE_Country && $country->ID() === $CNT_ISO
626
+			? $country
627
+			: EEM_Country::instance()->get_one_by_ID($CNT_ISO);
628
+	}
629
+
630
+
631
+	/**
632
+	 * Output Country Settings view.
633
+	 *
634
+	 * @throws DomainException
635
+	 * @throws EE_Error
636
+	 * @throws InvalidArgumentException
637
+	 * @throws InvalidDataTypeException
638
+	 * @throws InvalidInterfaceException
639
+	 * @throws ReflectionException
640
+	 */
641
+	protected function _country_settings()
642
+	{
643
+		$CNT_ISO = $this->getCountryISO();
644
+
645
+		$this->_template_args['values']    = $this->_yes_no_values;
646
+		$this->_template_args['countries'] = new EE_Question_Form_Input(
647
+			EE_Question::new_instance(
648
+				[
649
+				  'QST_ID'           => 0,
650
+				  'QST_display_text' => esc_html__('Select Country', 'event_espresso'),
651
+				  'QST_system'       => 'admin-country',
652
+				]
653
+			),
654
+			EE_Answer::new_instance(
655
+				[
656
+					'ANS_ID'    => 0,
657
+					'ANS_value' => $CNT_ISO,
658
+				]
659
+			),
660
+			[
661
+				'input_id'       => 'country',
662
+				'input_name'     => 'country',
663
+				'input_prefix'   => '',
664
+				'append_qstn_id' => false,
665
+			]
666
+		);
667
+
668
+		$country = $this->verifyOrGetCountryFromIso($CNT_ISO);
669
+		add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'country_form_field_label_wrap'], 10);
670
+		add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'country_form_field_input__wrap'], 10);
671
+		$this->_template_args['country_details_settings'] = $this->display_country_settings(
672
+			$country->ID(),
673
+			$country
674
+		);
675
+		$this->_template_args['country_states_settings']  = $this->display_country_states(
676
+			$country->ID(),
677
+			$country
678
+		);
679
+		$this->_template_args['CNT_name_for_site']        = $country->name();
680
+
681
+		$this->_set_add_edit_form_tags('update_country_settings');
682
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
683
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
684
+			GEN_SET_TEMPLATE_PATH . 'countries_settings.template.php',
685
+			$this->_template_args,
686
+			true
687
+		);
688
+		$this->display_admin_page_with_no_sidebar();
689
+	}
690
+
691
+
692
+	/**
693
+	 * @param string          $CNT_ISO
694
+	 * @param EE_Country|null $country
695
+	 * @return string
696
+	 * @throws DomainException
697
+	 * @throws EE_Error
698
+	 * @throws InvalidArgumentException
699
+	 * @throws InvalidDataTypeException
700
+	 * @throws InvalidInterfaceException
701
+	 * @throws ReflectionException
702
+	 */
703
+	public function display_country_settings(string $CNT_ISO = '', ?EE_Country $country = null): string
704
+	{
705
+		$CNT_ISO          = $this->getCountryISO($CNT_ISO);
706
+		$CNT_ISO_for_site = $this->getCountryIsoForSite();
707
+
708
+		if (! $CNT_ISO) {
709
+			return '';
710
+		}
711
+
712
+		// for ajax
713
+		remove_all_filters('FHEE__EEH_Form_Fields__label_html');
714
+		remove_all_filters('FHEE__EEH_Form_Fields__input_html');
715
+		add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'country_form_field_label_wrap'], 10, 2);
716
+		add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'country_form_field_input__wrap'], 10, 2);
717
+		$country                                  = $this->verifyOrGetCountryFromIso($CNT_ISO, $country);
718
+		$CNT_cur_disabled                         = $CNT_ISO !== $CNT_ISO_for_site;
719
+		$this->_template_args['CNT_cur_disabled'] = $CNT_cur_disabled;
720
+
721
+		$country_input_types            = [
722
+			'CNT_active'      => [
723
+				'type'             => 'RADIO_BTN',
724
+				'input_name'       => "cntry[$CNT_ISO]",
725
+				'class'            => '',
726
+				'options'          => $this->_yes_no_values,
727
+				'use_desc_4_label' => true,
728
+			],
729
+			'CNT_ISO'         => [
730
+				'type'       => 'TEXT',
731
+				'input_name' => "cntry[$CNT_ISO]",
732
+				'class'      => 'ee-input-width--small',
733
+			],
734
+			'CNT_ISO3'        => [
735
+				'type'       => 'TEXT',
736
+				'input_name' => "cntry[$CNT_ISO]",
737
+				'class'      => 'ee-input-width--small',
738
+			],
739
+			// 'RGN_ID'          => [
740
+			//     'type'       => 'TEXT',
741
+			//     'input_name' => "cntry[$CNT_ISO]",
742
+			//     'class'      => 'ee-input-width--small',
743
+			// ],
744
+			'CNT_name'        => [
745
+				'type'       => 'TEXT',
746
+				'input_name' => "cntry[$CNT_ISO]",
747
+				'class'      => 'ee-input-width--big',
748
+			],
749
+			'CNT_cur_code'    => [
750
+				'type'       => 'TEXT',
751
+				'input_name' => "cntry[$CNT_ISO]",
752
+				'class'      => 'ee-input-width--small',
753
+				'disabled'   => $CNT_cur_disabled,
754
+			],
755
+			'CNT_cur_single'  => [
756
+				'type'       => 'TEXT',
757
+				'input_name' => "cntry[$CNT_ISO]",
758
+				'class'      => 'ee-input-width--reg',
759
+				'disabled'   => $CNT_cur_disabled,
760
+			],
761
+			'CNT_cur_plural'  => [
762
+				'type'       => 'TEXT',
763
+				'input_name' => "cntry[$CNT_ISO]",
764
+				'class'      => 'ee-input-width--reg',
765
+				'disabled'   => $CNT_cur_disabled,
766
+			],
767
+			'CNT_cur_sign'    => [
768
+				'type'         => 'TEXT',
769
+				'input_name'   => "cntry[$CNT_ISO]",
770
+				'class'        => 'ee-input-width--small',
771
+				'htmlentities' => false,
772
+				'disabled'     => $CNT_cur_disabled,
773
+			],
774
+			'CNT_cur_sign_b4' => [
775
+				'type'             => 'RADIO_BTN',
776
+				'input_name'       => "cntry[$CNT_ISO]",
777
+				'class'            => '',
778
+				'options'          => $this->_yes_no_values,
779
+				'use_desc_4_label' => true,
780
+				'disabled'         => $CNT_cur_disabled,
781
+			],
782
+			'CNT_cur_dec_plc' => [
783
+				'type'       => 'RADIO_BTN',
784
+				'input_name' => "cntry[$CNT_ISO]",
785
+				'class'      => '',
786
+				'options'    => [
787
+					['id' => 0, 'text' => ''],
788
+					['id' => 1, 'text' => ''],
789
+					['id' => 2, 'text' => ''],
790
+					['id' => 3, 'text' => ''],
791
+				],
792
+				'disabled'   => $CNT_cur_disabled,
793
+			],
794
+			'CNT_cur_dec_mrk' => [
795
+				'type'             => 'RADIO_BTN',
796
+				'input_name'       => "cntry[$CNT_ISO]",
797
+				'class'            => '',
798
+				'options'          => [
799
+					[
800
+						'id'   => ',',
801
+						'text' => esc_html__(', (comma)', 'event_espresso'),
802
+					],
803
+					['id' => '.', 'text' => esc_html__('. (decimal)', 'event_espresso')],
804
+				],
805
+				'use_desc_4_label' => true,
806
+				'disabled'         => $CNT_cur_disabled,
807
+			],
808
+			'CNT_cur_thsnds'  => [
809
+				'type'             => 'RADIO_BTN',
810
+				'input_name'       => "cntry[$CNT_ISO]",
811
+				'class'            => '',
812
+				'options'          => [
813
+					[
814
+						'id'   => ',',
815
+						'text' => esc_html__(', (comma)', 'event_espresso'),
816
+					],
817
+					[
818
+						'id'   => '.',
819
+						'text' => esc_html__('. (decimal)', 'event_espresso'),
820
+					],
821
+					[
822
+						'id'   => ' ',
823
+						'text' => esc_html__('(space)', 'event_espresso'),
824
+					],
825
+					[
826
+						'id'   => '_',
827
+						'text' => esc_html__('_ (underscore)', 'event_espresso'),
828
+					],
829
+					[
830
+						'id'   => "'",
831
+						'text' => esc_html__("' (apostrophe)", 'event_espresso'),
832
+					],
833
+				],
834
+				'use_desc_4_label' => true,
835
+				'disabled'         => $CNT_cur_disabled,
836
+			],
837
+			'CNT_tel_code'    => [
838
+				'type'       => 'TEXT',
839
+				'input_name' => "cntry[$CNT_ISO]",
840
+				'class'      => 'ee-input-width--small',
841
+			],
842
+			'CNT_is_EU'       => [
843
+				'type'             => 'RADIO_BTN',
844
+				'input_name'       => "cntry[$CNT_ISO]",
845
+				'class'            => '',
846
+				'options'          => $this->_yes_no_values,
847
+				'use_desc_4_label' => true,
848
+			],
849
+		];
850
+		$this->_template_args['inputs'] = EE_Question_Form_Input::generate_question_form_inputs_for_object(
851
+			$country,
852
+			$country_input_types
853
+		);
854
+		$country_details_settings       = EEH_Template::display_template(
855
+			GEN_SET_TEMPLATE_PATH . 'country_details_settings.template.php',
856
+			$this->_template_args,
857
+			true
858
+		);
859
+
860
+		if (defined('DOING_AJAX')) {
861
+			$notices = EE_Error::get_notices(false, false, false);
862
+			echo wp_json_encode(
863
+				[
864
+					'return_data' => $country_details_settings,
865
+					'success'     => $notices['success'],
866
+					'errors'      => $notices['errors'],
867
+				]
868
+			);
869
+			die();
870
+		}
871
+		return $country_details_settings;
872
+	}
873
+
874
+
875
+	/**
876
+	 * @param string          $CNT_ISO
877
+	 * @param EE_Country|null $country
878
+	 * @return string
879
+	 * @throws DomainException
880
+	 * @throws EE_Error
881
+	 * @throws InvalidArgumentException
882
+	 * @throws InvalidDataTypeException
883
+	 * @throws InvalidInterfaceException
884
+	 * @throws ReflectionException
885
+	 */
886
+	public function display_country_states(string $CNT_ISO = '', ?EE_Country $country = null): string
887
+	{
888
+		$CNT_ISO = $this->getCountryISO($CNT_ISO);
889
+		if (! $CNT_ISO) {
890
+			return '';
891
+		}
892
+		// for ajax
893
+		remove_all_filters('FHEE__EEH_Form_Fields__label_html');
894
+		remove_all_filters('FHEE__EEH_Form_Fields__input_html');
895
+		add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'state_form_field_label_wrap'], 10, 2);
896
+		add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'state_form_field_input__wrap'], 10);
897
+		$states = EEM_State::instance()->get_all_states_for_these_countries([$CNT_ISO => $CNT_ISO]);
898
+		if (empty($states)) {
899
+			/** @var EventEspresso\core\services\address\CountrySubRegionDao $countrySubRegionDao */
900
+			$countrySubRegionDao = $this->loader->getShared(
901
+				'EventEspresso\core\services\address\CountrySubRegionDao'
902
+			);
903
+			if ($countrySubRegionDao instanceof EventEspresso\core\services\address\CountrySubRegionDao) {
904
+				$country = $this->verifyOrGetCountryFromIso($CNT_ISO, $country);
905
+				if ($countrySubRegionDao->saveCountrySubRegions($country)) {
906
+					$states = EEM_State::instance()->get_all_states_for_these_countries([$CNT_ISO => $CNT_ISO]);
907
+				}
908
+			}
909
+		}
910
+		if (is_array($states)) {
911
+			foreach ($states as $STA_ID => $state) {
912
+				if ($state instanceof EE_State) {
913
+					$inputs = EE_Question_Form_Input::generate_question_form_inputs_for_object(
914
+						$state,
915
+						[
916
+							'STA_abbrev' => [
917
+								'type'             => 'TEXT',
918
+								'label'            => esc_html__('Code', 'event_espresso'),
919
+								'input_name'       => "states[$STA_ID]",
920
+								'class'            => 'ee-input-width--tiny',
921
+								'add_mobile_label' => true,
922
+							],
923
+							'STA_name'   => [
924
+								'type'             => 'TEXT',
925
+								'label'            => esc_html__('Name', 'event_espresso'),
926
+								'input_name'       => "states[$STA_ID]",
927
+								'class'            => 'ee-input-width--big',
928
+								'add_mobile_label' => true,
929
+							],
930
+							'STA_active' => [
931
+								'type'             => 'RADIO_BTN',
932
+								'label'            => esc_html__(
933
+									'State Appears in Dropdown Select Lists',
934
+									'event_espresso'
935
+								),
936
+								'input_name'       => "states[$STA_ID]",
937
+								'options'          => $this->_yes_no_values,
938
+								'use_desc_4_label' => true,
939
+								'add_mobile_label' => true,
940
+							],
941
+						]
942
+					);
943
+
944
+					$delete_state_url = EE_Admin_Page::add_query_args_and_nonce(
945
+						[
946
+							'action'     => 'delete_state',
947
+							'STA_ID'     => $STA_ID,
948
+							'CNT_ISO'    => $CNT_ISO,
949
+							'STA_abbrev' => $state->abbrev(),
950
+						],
951
+						GEN_SET_ADMIN_URL
952
+					);
953
+
954
+					$this->_template_args['states'][ $STA_ID ]['inputs']           = $inputs;
955
+					$this->_template_args['states'][ $STA_ID ]['delete_state_url'] = $delete_state_url;
956
+				}
957
+			}
958
+		} else {
959
+			$this->_template_args['states'] = false;
960
+		}
961
+
962
+		$this->_template_args['add_new_state_url'] = EE_Admin_Page::add_query_args_and_nonce(
963
+			['action' => 'add_new_state'],
964
+			GEN_SET_ADMIN_URL
965
+		);
966
+
967
+		$state_details_settings = EEH_Template::display_template(
968
+			GEN_SET_TEMPLATE_PATH . 'state_details_settings.template.php',
969
+			$this->_template_args,
970
+			true
971
+		);
972
+
973
+		if (defined('DOING_AJAX')) {
974
+			$notices = EE_Error::get_notices(false, false, false);
975
+			echo wp_json_encode(
976
+				[
977
+					'return_data' => $state_details_settings,
978
+					'success'     => $notices['success'],
979
+					'errors'      => $notices['errors'],
980
+				]
981
+			);
982
+			die();
983
+		}
984
+		return $state_details_settings;
985
+	}
986
+
987
+
988
+	/**
989
+	 * @return void
990
+	 * @throws EE_Error
991
+	 * @throws InvalidArgumentException
992
+	 * @throws InvalidDataTypeException
993
+	 * @throws InvalidInterfaceException
994
+	 * @throws ReflectionException
995
+	 */
996
+	public function add_new_state()
997
+	{
998
+		$success = true;
999
+		$CNT_ISO = $this->getCountryISO('');
1000
+		if (! $CNT_ISO) {
1001
+			EE_Error::add_error(
1002
+				esc_html__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
1003
+				__FILE__,
1004
+				__FUNCTION__,
1005
+				__LINE__
1006
+			);
1007
+			$success = false;
1008
+		}
1009
+		$STA_abbrev = $this->request->getRequestParam('STA_abbrev');
1010
+		if (! $STA_abbrev) {
1011
+			EE_Error::add_error(
1012
+				esc_html__('No State ISO code or an invalid State ISO code was received.', 'event_espresso'),
1013
+				__FILE__,
1014
+				__FUNCTION__,
1015
+				__LINE__
1016
+			);
1017
+			$success = false;
1018
+		}
1019
+		$STA_name = $this->request->getRequestParam('STA_name');
1020
+		if (! $STA_name) {
1021
+			EE_Error::add_error(
1022
+				esc_html__('No State name or an invalid State name was received.', 'event_espresso'),
1023
+				__FILE__,
1024
+				__FUNCTION__,
1025
+				__LINE__
1026
+			);
1027
+			$success = false;
1028
+		}
1029
+
1030
+		if ($success) {
1031
+			$cols_n_values = [
1032
+				'CNT_ISO'    => $CNT_ISO,
1033
+				'STA_abbrev' => $STA_abbrev,
1034
+				'STA_name'   => $STA_name,
1035
+				'STA_active' => true,
1036
+			];
1037
+			$success       = EEM_State::instance()->insert($cols_n_values);
1038
+			EE_Error::add_success(esc_html__('The State was added successfully.', 'event_espresso'));
1039
+		}
1040
+
1041
+		if (defined('DOING_AJAX')) {
1042
+			$notices = EE_Error::get_notices(false, false, false);
1043
+			echo wp_json_encode(array_merge($notices, ['return_data' => $CNT_ISO]));
1044
+			die();
1045
+		}
1046
+		$this->_redirect_after_action(
1047
+			$success,
1048
+			esc_html__('State', 'event_espresso'),
1049
+			'added',
1050
+			['action' => 'country_settings']
1051
+		);
1052
+	}
1053
+
1054
+
1055
+	/**
1056
+	 * @return void
1057
+	 * @throws EE_Error
1058
+	 * @throws InvalidArgumentException
1059
+	 * @throws InvalidDataTypeException
1060
+	 * @throws InvalidInterfaceException
1061
+	 * @throws ReflectionException
1062
+	 */
1063
+	public function delete_state()
1064
+	{
1065
+		$CNT_ISO    = $this->getCountryISO();
1066
+		$STA_ID     = $this->request->getRequestParam('STA_ID');
1067
+		$STA_abbrev = $this->request->getRequestParam('STA_abbrev');
1068
+
1069
+		if (! $STA_ID) {
1070
+			EE_Error::add_error(
1071
+				esc_html__('No State ID or an invalid State ID was received.', 'event_espresso'),
1072
+				__FILE__,
1073
+				__FUNCTION__,
1074
+				__LINE__
1075
+			);
1076
+			return;
1077
+		}
1078
+
1079
+		$success = EEM_State::instance()->delete_by_ID($STA_ID);
1080
+		if ($success !== false) {
1081
+			do_action(
1082
+				'AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
1083
+				$CNT_ISO,
1084
+				$STA_ID,
1085
+				['STA_abbrev' => $STA_abbrev]
1086
+			);
1087
+			EE_Error::add_success(esc_html__('The State was deleted successfully.', 'event_espresso'));
1088
+		}
1089
+		if (defined('DOING_AJAX')) {
1090
+			$notices                = EE_Error::get_notices(false);
1091
+			$notices['return_data'] = true;
1092
+			echo wp_json_encode($notices);
1093
+			die();
1094
+		}
1095
+		$this->_redirect_after_action(
1096
+			$success,
1097
+			esc_html__('State', 'event_espresso'),
1098
+			'deleted',
1099
+			['action' => 'country_settings']
1100
+		);
1101
+	}
1102
+
1103
+
1104
+	/**
1105
+	 * @return void
1106
+	 * @throws EE_Error
1107
+	 * @throws InvalidArgumentException
1108
+	 * @throws InvalidDataTypeException
1109
+	 * @throws InvalidInterfaceException
1110
+	 * @throws ReflectionException
1111
+	 */
1112
+	protected function _update_country_settings()
1113
+	{
1114
+		$CNT_ISO = $this->getCountryISO();
1115
+		if (! $CNT_ISO) {
1116
+			EE_Error::add_error(
1117
+				esc_html__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
1118
+				__FILE__,
1119
+				__FUNCTION__,
1120
+				__LINE__
1121
+			);
1122
+			return;
1123
+		}
1124
+
1125
+		$country = $this->verifyOrGetCountryFromIso($CNT_ISO);
1126
+
1127
+		$cols_n_values                    = [];
1128
+		$cols_n_values['CNT_ISO3']        = strtoupper(
1129
+			$this->request->getRequestParam('cntry', $country->ISO3())
1130
+		);
1131
+		$cols_n_values['CNT_name']        = $this->request->getRequestParam(
1132
+			"cntry[$CNT_ISO][CNT_name]",
1133
+			$country->name()
1134
+		);
1135
+		$cols_n_values['CNT_cur_code']    = strtoupper(
1136
+			$this->request->getRequestParam(
1137
+				"cntry[$CNT_ISO][CNT_cur_code]",
1138
+				$country->currency_code()
1139
+			)
1140
+		);
1141
+		$cols_n_values['CNT_cur_single']  = $this->request->getRequestParam(
1142
+			"cntry[$CNT_ISO][CNT_cur_single]",
1143
+			$country->currency_name_single()
1144
+		);
1145
+		$cols_n_values['CNT_cur_plural']  = $this->request->getRequestParam(
1146
+			"cntry[$CNT_ISO][CNT_cur_plural]",
1147
+			$country->currency_name_plural()
1148
+		);
1149
+		$cols_n_values['CNT_cur_sign']    = $this->request->getRequestParam(
1150
+			"cntry[$CNT_ISO][CNT_cur_sign]",
1151
+			$country->currency_sign()
1152
+		);
1153
+		$cols_n_values['CNT_cur_sign_b4'] = $this->request->getRequestParam(
1154
+			"cntry[$CNT_ISO][CNT_cur_sign_b4]",
1155
+			$country->currency_sign_before(),
1156
+			DataType::BOOL
1157
+		);
1158
+		$cols_n_values['CNT_cur_dec_plc'] = $this->request->getRequestParam(
1159
+			"cntry[$CNT_ISO][CNT_cur_dec_plc]",
1160
+			$country->currency_decimal_places()
1161
+		);
1162
+		$cols_n_values['CNT_cur_dec_mrk'] = $this->request->getRequestParam(
1163
+			"cntry[$CNT_ISO][CNT_cur_dec_mrk]",
1164
+			$country->currency_decimal_mark()
1165
+		);
1166
+		$cols_n_values['CNT_cur_thsnds']  = $this->request->getRequestParam(
1167
+			"cntry[$CNT_ISO][CNT_cur_thsnds]",
1168
+			$country->currency_thousands_separator()
1169
+		);
1170
+		$cols_n_values['CNT_tel_code']    = $this->request->getRequestParam(
1171
+			"cntry[$CNT_ISO][CNT_tel_code]",
1172
+			$country->telephoneCode()
1173
+		);
1174
+		$cols_n_values['CNT_active']      = $this->request->getRequestParam(
1175
+			"cntry[$CNT_ISO][CNT_active]",
1176
+			$country->isActive(),
1177
+			DataType::BOOL
1178
+		);
1179
+
1180
+		// allow filtering of country data
1181
+		$cols_n_values = apply_filters(
1182
+			'FHEE__General_Settings_Admin_Page___update_country_settings__cols_n_values',
1183
+			$cols_n_values
1184
+		);
1185
+
1186
+		// where values
1187
+		$where_cols_n_values = [['CNT_ISO' => $CNT_ISO]];
1188
+		// run the update
1189
+		$success = EEM_Country::instance()->update($cols_n_values, $where_cols_n_values);
1190
+
1191
+		// allow filtering of states data
1192
+		$states = apply_filters(
1193
+			'FHEE__General_Settings_Admin_Page___update_country_settings__states',
1194
+			$this->request->getRequestParam('states', [], DataType::STRING, true)
1195
+		);
1196
+
1197
+		if (! empty($states) && $success !== false) {
1198
+			// loop thru state data ( looks like : states[75][STA_name] )
1199
+			foreach ($states as $STA_ID => $state) {
1200
+				$cols_n_values = [
1201
+					'CNT_ISO'    => $CNT_ISO,
1202
+					'STA_abbrev' => sanitize_text_field($state['STA_abbrev']),
1203
+					'STA_name'   => sanitize_text_field($state['STA_name']),
1204
+					'STA_active' => filter_var($state['STA_active'], FILTER_VALIDATE_BOOLEAN),
1205
+				];
1206
+				// where values
1207
+				$where_cols_n_values = [['STA_ID' => $STA_ID]];
1208
+				// run the update
1209
+				$success = EEM_State::instance()->update($cols_n_values, $where_cols_n_values);
1210
+				if ($success !== false) {
1211
+					do_action(
1212
+						'AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
1213
+						$CNT_ISO,
1214
+						$STA_ID,
1215
+						$cols_n_values
1216
+					);
1217
+				}
1218
+			}
1219
+		}
1220
+		// check if country being edited matches org option country, and if so, then  update EE_Config with new settings
1221
+		if (
1222
+			isset(EE_Registry::instance()->CFG->organization->CNT_ISO)
1223
+			&& $CNT_ISO == EE_Registry::instance()->CFG->organization->CNT_ISO
1224
+		) {
1225
+			EE_Registry::instance()->CFG->currency = new EE_Currency_Config($CNT_ISO);
1226
+			EE_Registry::instance()->CFG->update_espresso_config();
1227
+		}
1228
+
1229
+		if ($success !== false) {
1230
+			EE_Error::add_success(
1231
+				esc_html__('Country Settings updated successfully.', 'event_espresso')
1232
+			);
1233
+		}
1234
+		$this->_redirect_after_action(
1235
+			$success,
1236
+			'',
1237
+			'',
1238
+			['action' => 'country_settings', 'country' => $CNT_ISO],
1239
+			true
1240
+		);
1241
+	}
1242
+
1243
+
1244
+	/**
1245
+	 * form_form_field_label_wrap
1246
+	 *
1247
+	 * @param string $label
1248
+	 * @return string
1249
+	 */
1250
+	public function country_form_field_label_wrap(string $label): string
1251
+	{
1252
+		return '
1253 1253
 			<tr>
1254 1254
 				<th>
1255 1255
 					' . $label . '
1256 1256
 				</th>';
1257
-    }
1258
-
1259
-
1260
-    /**
1261
-     * form_form_field_input__wrap
1262
-     *
1263
-     * @param string $input
1264
-     * @return string
1265
-     */
1266
-    public function country_form_field_input__wrap(string $input): string
1267
-    {
1268
-        return '
1257
+	}
1258
+
1259
+
1260
+	/**
1261
+	 * form_form_field_input__wrap
1262
+	 *
1263
+	 * @param string $input
1264
+	 * @return string
1265
+	 */
1266
+	public function country_form_field_input__wrap(string $input): string
1267
+	{
1268
+		return '
1269 1269
 				<td class="general-settings-country-input-td">
1270 1270
 					' . $input . '
1271 1271
 				</td>
1272 1272
 			</tr>';
1273
-    }
1274
-
1275
-
1276
-    /**
1277
-     * form_form_field_label_wrap
1278
-     *
1279
-     * @param string $label
1280
-     * @param string $required_text
1281
-     * @return string
1282
-     */
1283
-    public function state_form_field_label_wrap(string $label, string $required_text): string
1284
-    {
1285
-        return $required_text;
1286
-    }
1287
-
1288
-
1289
-    /**
1290
-     * form_form_field_input__wrap
1291
-     *
1292
-     * @param string $input
1293
-     * @return string
1294
-     */
1295
-    public function state_form_field_input__wrap(string $input): string
1296
-    {
1297
-        return '
1273
+	}
1274
+
1275
+
1276
+	/**
1277
+	 * form_form_field_label_wrap
1278
+	 *
1279
+	 * @param string $label
1280
+	 * @param string $required_text
1281
+	 * @return string
1282
+	 */
1283
+	public function state_form_field_label_wrap(string $label, string $required_text): string
1284
+	{
1285
+		return $required_text;
1286
+	}
1287
+
1288
+
1289
+	/**
1290
+	 * form_form_field_input__wrap
1291
+	 *
1292
+	 * @param string $input
1293
+	 * @return string
1294
+	 */
1295
+	public function state_form_field_input__wrap(string $input): string
1296
+	{
1297
+		return '
1298 1298
 				<td class="general-settings-country-state-input-td">
1299 1299
 					' . $input . '
1300 1300
 				</td>';
1301
-    }
1302
-
1303
-
1304
-    /***********/
1305
-
1306
-
1307
-    /**
1308
-     * displays edit and view links for critical EE pages
1309
-     *
1310
-     * @param int $ee_page_id
1311
-     * @return string
1312
-     */
1313
-    public static function edit_view_links(int $ee_page_id): string
1314
-    {
1315
-        $edit_url = add_query_arg(
1316
-            ['post' => $ee_page_id, 'action' => 'edit'],
1317
-            admin_url('post.php')
1318
-        );
1319
-        $links    = '<a href="' . esc_url_raw($edit_url) . '" >' . esc_html__('Edit', 'event_espresso') . '</a>';
1320
-        $links    .= ' &nbsp;|&nbsp; ';
1321
-        $links    .= '<a href="' . get_permalink($ee_page_id) . '" >' . esc_html__('View', 'event_espresso') . '</a>';
1322
-
1323
-        return $links;
1324
-    }
1325
-
1326
-
1327
-    /**
1328
-     * displays page and shortcode status for critical EE pages
1329
-     *
1330
-     * @param WP_Post $ee_page
1331
-     * @param string  $shortcode
1332
-     * @return string
1333
-     */
1334
-    public static function page_and_shortcode_status(WP_Post $ee_page, string $shortcode): string
1335
-    {
1336
-        // page status
1337
-        if (isset($ee_page->post_status) && $ee_page->post_status == 'publish') {
1338
-            $pg_class  = 'ee-status-bg--success';
1339
-            $pg_status = sprintf(esc_html__('Page%sStatus%sOK', 'event_espresso'), '&nbsp;', '&nbsp;');
1340
-        } else {
1341
-            $pg_class  = 'ee-status-bg--error';
1342
-            $pg_status = sprintf(esc_html__('Page%sVisibility%sProblem', 'event_espresso'), '&nbsp;', '&nbsp;');
1343
-        }
1344
-
1345
-        // shortcode status
1346
-        if (isset($ee_page->post_content) && strpos($ee_page->post_content, $shortcode) !== false) {
1347
-            $sc_class  = 'ee-status-bg--success';
1348
-            $sc_status = sprintf(esc_html__('Shortcode%sOK', 'event_espresso'), '&nbsp;');
1349
-        } else {
1350
-            $sc_class  = 'ee-status-bg--error';
1351
-            $sc_status = sprintf(esc_html__('Shortcode%sProblem', 'event_espresso'), '&nbsp;');
1352
-        }
1353
-
1354
-        return '
1301
+	}
1302
+
1303
+
1304
+	/***********/
1305
+
1306
+
1307
+	/**
1308
+	 * displays edit and view links for critical EE pages
1309
+	 *
1310
+	 * @param int $ee_page_id
1311
+	 * @return string
1312
+	 */
1313
+	public static function edit_view_links(int $ee_page_id): string
1314
+	{
1315
+		$edit_url = add_query_arg(
1316
+			['post' => $ee_page_id, 'action' => 'edit'],
1317
+			admin_url('post.php')
1318
+		);
1319
+		$links    = '<a href="' . esc_url_raw($edit_url) . '" >' . esc_html__('Edit', 'event_espresso') . '</a>';
1320
+		$links    .= ' &nbsp;|&nbsp; ';
1321
+		$links    .= '<a href="' . get_permalink($ee_page_id) . '" >' . esc_html__('View', 'event_espresso') . '</a>';
1322
+
1323
+		return $links;
1324
+	}
1325
+
1326
+
1327
+	/**
1328
+	 * displays page and shortcode status for critical EE pages
1329
+	 *
1330
+	 * @param WP_Post $ee_page
1331
+	 * @param string  $shortcode
1332
+	 * @return string
1333
+	 */
1334
+	public static function page_and_shortcode_status(WP_Post $ee_page, string $shortcode): string
1335
+	{
1336
+		// page status
1337
+		if (isset($ee_page->post_status) && $ee_page->post_status == 'publish') {
1338
+			$pg_class  = 'ee-status-bg--success';
1339
+			$pg_status = sprintf(esc_html__('Page%sStatus%sOK', 'event_espresso'), '&nbsp;', '&nbsp;');
1340
+		} else {
1341
+			$pg_class  = 'ee-status-bg--error';
1342
+			$pg_status = sprintf(esc_html__('Page%sVisibility%sProblem', 'event_espresso'), '&nbsp;', '&nbsp;');
1343
+		}
1344
+
1345
+		// shortcode status
1346
+		if (isset($ee_page->post_content) && strpos($ee_page->post_content, $shortcode) !== false) {
1347
+			$sc_class  = 'ee-status-bg--success';
1348
+			$sc_status = sprintf(esc_html__('Shortcode%sOK', 'event_espresso'), '&nbsp;');
1349
+		} else {
1350
+			$sc_class  = 'ee-status-bg--error';
1351
+			$sc_status = sprintf(esc_html__('Shortcode%sProblem', 'event_espresso'), '&nbsp;');
1352
+		}
1353
+
1354
+		return '
1355 1355
         <span class="ee-page-status ' . $pg_class . '"><strong>' . $pg_status . '</strong></span>
1356 1356
         <span class="ee-page-status ' . $sc_class . '"><strong>' . $sc_status . '</strong></span>';
1357
-    }
1358
-
1359
-
1360
-    /**
1361
-     * generates a dropdown of all parent pages - copied from WP core
1362
-     *
1363
-     * @param int  $default
1364
-     * @param int  $parent
1365
-     * @param int  $level
1366
-     * @param bool $echo
1367
-     * @return string;
1368
-     */
1369
-    public static function page_settings_dropdown(
1370
-        int $default = 0,
1371
-        int $parent = 0,
1372
-        int $level = 0,
1373
-        bool $echo = true
1374
-    ): string {
1375
-        global $wpdb;
1376
-        $items  = $wpdb->get_results(
1377
-            $wpdb->prepare(
1378
-                "SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' AND post_status != 'trash' ORDER BY menu_order",
1379
-                $parent
1380
-            )
1381
-        );
1382
-        $output = '';
1383
-
1384
-        if ($items) {
1385
-            $level = absint($level);
1386
-            foreach ($items as $item) {
1387
-                $ID         = absint($item->ID);
1388
-                $post_title = wp_strip_all_tags($item->post_title);
1389
-                $pad        = str_repeat('&nbsp;', $level * 3);
1390
-                $option     = "\n\t";
1391
-                $option     .= '<option class="level-' . $level . '" ';
1392
-                $option     .= 'value="' . $ID . '" ';
1393
-                $option     .= $ID === absint($default) ? ' selected' : '';
1394
-                $option     .= '>';
1395
-                $option     .= "$pad {$post_title}";
1396
-                $option     .= '</option>';
1397
-                $output     .= $option;
1398
-                ob_start();
1399
-                parent_dropdown($default, $item->ID, $level + 1);
1400
-                $output .= ob_get_clean();
1401
-            }
1402
-        }
1403
-        if ($echo) {
1404
-            echo wp_kses($output, AllowedTags::getWithFormTags());
1405
-            return '';
1406
-        }
1407
-        return $output;
1408
-    }
1409
-
1410
-
1411
-    /**
1412
-     * Loads the scripts for the privacy settings form
1413
-     */
1414
-    public function load_scripts_styles_privacy_settings()
1415
-    {
1416
-        $form_handler = $this->loader->getShared(
1417
-            'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1418
-        );
1419
-        $form_handler->enqueueStylesAndScripts();
1420
-    }
1421
-
1422
-
1423
-    /**
1424
-     * display the privacy settings form
1425
-     *
1426
-     * @throws EE_Error
1427
-     */
1428
-    public function privacySettings()
1429
-    {
1430
-        $this->_set_add_edit_form_tags('update_privacy_settings');
1431
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
1432
-        $form_handler                               = $this->loader->getShared(
1433
-            'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1434
-        );
1435
-        $this->_template_args['admin_page_content'] = EEH_HTML::div(
1436
-            $form_handler->display(),
1437
-            '',
1438
-            'padding'
1439
-        );
1440
-        $this->display_admin_page_with_sidebar();
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * Update the privacy settings from form data
1446
-     *
1447
-     * @throws EE_Error
1448
-     */
1449
-    public function updatePrivacySettings()
1450
-    {
1451
-        $form_handler = $this->loader->getShared(
1452
-            'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1453
-        );
1454
-        $success      = $form_handler->process($this->get_request_data());
1455
-        $this->_redirect_after_action(
1456
-            $success,
1457
-            esc_html__('Registration Form Options', 'event_espresso'),
1458
-            'updated',
1459
-            ['action' => 'privacy_settings']
1460
-        );
1461
-    }
1357
+	}
1358
+
1359
+
1360
+	/**
1361
+	 * generates a dropdown of all parent pages - copied from WP core
1362
+	 *
1363
+	 * @param int  $default
1364
+	 * @param int  $parent
1365
+	 * @param int  $level
1366
+	 * @param bool $echo
1367
+	 * @return string;
1368
+	 */
1369
+	public static function page_settings_dropdown(
1370
+		int $default = 0,
1371
+		int $parent = 0,
1372
+		int $level = 0,
1373
+		bool $echo = true
1374
+	): string {
1375
+		global $wpdb;
1376
+		$items  = $wpdb->get_results(
1377
+			$wpdb->prepare(
1378
+				"SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' AND post_status != 'trash' ORDER BY menu_order",
1379
+				$parent
1380
+			)
1381
+		);
1382
+		$output = '';
1383
+
1384
+		if ($items) {
1385
+			$level = absint($level);
1386
+			foreach ($items as $item) {
1387
+				$ID         = absint($item->ID);
1388
+				$post_title = wp_strip_all_tags($item->post_title);
1389
+				$pad        = str_repeat('&nbsp;', $level * 3);
1390
+				$option     = "\n\t";
1391
+				$option     .= '<option class="level-' . $level . '" ';
1392
+				$option     .= 'value="' . $ID . '" ';
1393
+				$option     .= $ID === absint($default) ? ' selected' : '';
1394
+				$option     .= '>';
1395
+				$option     .= "$pad {$post_title}";
1396
+				$option     .= '</option>';
1397
+				$output     .= $option;
1398
+				ob_start();
1399
+				parent_dropdown($default, $item->ID, $level + 1);
1400
+				$output .= ob_get_clean();
1401
+			}
1402
+		}
1403
+		if ($echo) {
1404
+			echo wp_kses($output, AllowedTags::getWithFormTags());
1405
+			return '';
1406
+		}
1407
+		return $output;
1408
+	}
1409
+
1410
+
1411
+	/**
1412
+	 * Loads the scripts for the privacy settings form
1413
+	 */
1414
+	public function load_scripts_styles_privacy_settings()
1415
+	{
1416
+		$form_handler = $this->loader->getShared(
1417
+			'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1418
+		);
1419
+		$form_handler->enqueueStylesAndScripts();
1420
+	}
1421
+
1422
+
1423
+	/**
1424
+	 * display the privacy settings form
1425
+	 *
1426
+	 * @throws EE_Error
1427
+	 */
1428
+	public function privacySettings()
1429
+	{
1430
+		$this->_set_add_edit_form_tags('update_privacy_settings');
1431
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
1432
+		$form_handler                               = $this->loader->getShared(
1433
+			'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1434
+		);
1435
+		$this->_template_args['admin_page_content'] = EEH_HTML::div(
1436
+			$form_handler->display(),
1437
+			'',
1438
+			'padding'
1439
+		);
1440
+		$this->display_admin_page_with_sidebar();
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * Update the privacy settings from form data
1446
+	 *
1447
+	 * @throws EE_Error
1448
+	 */
1449
+	public function updatePrivacySettings()
1450
+	{
1451
+		$form_handler = $this->loader->getShared(
1452
+			'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1453
+		);
1454
+		$success      = $form_handler->process($this->get_request_data());
1455
+		$this->_redirect_after_action(
1456
+			$success,
1457
+			esc_html__('Registration Form Options', 'event_espresso'),
1458
+			'updated',
1459
+			['action' => 'privacy_settings']
1460
+		);
1461
+	}
1462 1462
 }
Please login to merge, or discard this patch.
domain/services/admin/registrations/list_table/csv_reports/AnswersCSV.php 2 patches
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -18,65 +18,65 @@
 block discarded – undo
18 18
  */
19 19
 class AnswersCSV
20 20
 {
21
-    /**
22
-     * Add question / answer columns to the CSV row
23
-     *
24
-     * @param array $reg_row
25
-     * @param array $data
26
-     * @param array $question_labels
27
-     * @return array
28
-     * @throws EE_Error
29
-     * @throws ReflectionException
30
-     */
31
-    public static function addAnswerColumns(array $reg_row, array $data, array $question_labels): array
32
-    {
33
-        $answer_model = EEM_Answer::instance();
34
-        $qst_model = EEM_Question::instance();
35
-        $state_model = EEM_State::instance();
36
-        // make sure each registration has the same questions in the same order
37
-        foreach ($question_labels as $question_label) {
38
-            if (! isset($data[ $question_label ])) {
39
-                $data[ $question_label ] = null;
40
-            }
41
-        }
42
-        $answers = $answer_model->get_all_wpdb_results([
43
-            ['REG_ID' => $reg_row['Registration.REG_ID']],
44
-            'force_join' => ['Question'],
45
-        ]);
46
-        // now fill out the questions THEY answered
47
-        foreach ($answers as $answer_row) {
48
-            if ($answer_row['Question.QST_system']) {
49
-                // it's an answer to a system question. That was already displayed as part of the attendee
50
-                // fields, so don't write it out again thanks.
51
-                continue;
52
-            }
21
+	/**
22
+	 * Add question / answer columns to the CSV row
23
+	 *
24
+	 * @param array $reg_row
25
+	 * @param array $data
26
+	 * @param array $question_labels
27
+	 * @return array
28
+	 * @throws EE_Error
29
+	 * @throws ReflectionException
30
+	 */
31
+	public static function addAnswerColumns(array $reg_row, array $data, array $question_labels): array
32
+	{
33
+		$answer_model = EEM_Answer::instance();
34
+		$qst_model = EEM_Question::instance();
35
+		$state_model = EEM_State::instance();
36
+		// make sure each registration has the same questions in the same order
37
+		foreach ($question_labels as $question_label) {
38
+			if (! isset($data[ $question_label ])) {
39
+				$data[ $question_label ] = null;
40
+			}
41
+		}
42
+		$answers = $answer_model->get_all_wpdb_results([
43
+			['REG_ID' => $reg_row['Registration.REG_ID']],
44
+			'force_join' => ['Question'],
45
+		]);
46
+		// now fill out the questions THEY answered
47
+		foreach ($answers as $answer_row) {
48
+			if ($answer_row['Question.QST_system']) {
49
+				// it's an answer to a system question. That was already displayed as part of the attendee
50
+				// fields, so don't write it out again thanks.
51
+				continue;
52
+			}
53 53
 
54
-            $question_label = $answer_row['Question.QST_ID']
55
-                ? EEH_Export::prepare_value_from_db_for_display(
56
-                    $qst_model,
57
-                    'QST_admin_label',
58
-                    $answer_row['Question.QST_admin_label']
59
-                )
60
-                : sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
54
+			$question_label = $answer_row['Question.QST_ID']
55
+				? EEH_Export::prepare_value_from_db_for_display(
56
+					$qst_model,
57
+					'QST_admin_label',
58
+					$answer_row['Question.QST_admin_label']
59
+				)
60
+				: sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
61 61
 
62
-            if (! array_key_exists($question_label, $data)) {
63
-                // We don't need an answer for this specific question in the current dataset
64
-                // so skip adding this value to $data.
65
-                continue;
66
-            }
62
+			if (! array_key_exists($question_label, $data)) {
63
+				// We don't need an answer for this specific question in the current dataset
64
+				// so skip adding this value to $data.
65
+				continue;
66
+			}
67 67
 
68
-            $data[ $question_label ] = isset($answer_row['Question.QST_type'])
69
-                                       && $answer_row['Question.QST_type'] === EEM_Question::QST_type_state
70
-                ? $state_model->get_state_name_by_ID($answer_row['Answer.ANS_value'])
71
-                // this isn't for html, so don't show html entities
72
-                : html_entity_decode(
73
-                    EEH_Export::prepare_value_from_db_for_display(
74
-                        $answer_model,
75
-                        'ANS_value',
76
-                        $answer_row['Answer.ANS_value']
77
-                    )
78
-                );
79
-        }
80
-        return $data;
81
-    }
68
+			$data[ $question_label ] = isset($answer_row['Question.QST_type'])
69
+									   && $answer_row['Question.QST_type'] === EEM_Question::QST_type_state
70
+				? $state_model->get_state_name_by_ID($answer_row['Answer.ANS_value'])
71
+				// this isn't for html, so don't show html entities
72
+				: html_entity_decode(
73
+					EEH_Export::prepare_value_from_db_for_display(
74
+						$answer_model,
75
+						'ANS_value',
76
+						$answer_row['Answer.ANS_value']
77
+					)
78
+				);
79
+		}
80
+		return $data;
81
+	}
82 82
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -35,8 +35,8 @@  discard block
 block discarded – undo
35 35
         $state_model = EEM_State::instance();
36 36
         // make sure each registration has the same questions in the same order
37 37
         foreach ($question_labels as $question_label) {
38
-            if (! isset($data[ $question_label ])) {
39
-                $data[ $question_label ] = null;
38
+            if ( ! isset($data[$question_label])) {
39
+                $data[$question_label] = null;
40 40
             }
41 41
         }
42 42
         $answers = $answer_model->get_all_wpdb_results([
@@ -59,13 +59,13 @@  discard block
 block discarded – undo
59 59
                 )
60 60
                 : sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
61 61
 
62
-            if (! array_key_exists($question_label, $data)) {
62
+            if ( ! array_key_exists($question_label, $data)) {
63 63
                 // We don't need an answer for this specific question in the current dataset
64 64
                 // so skip adding this value to $data.
65 65
                 continue;
66 66
             }
67 67
 
68
-            $data[ $question_label ] = isset($answer_row['Question.QST_type'])
68
+            $data[$question_label] = isset($answer_row['Question.QST_type'])
69 69
                                        && $answer_row['Question.QST_type'] === EEM_Question::QST_type_state
70 70
                 ? $state_model->get_state_name_by_ID($answer_row['Answer.ANS_value'])
71 71
                 // this isn't for html, so don't show html entities
Please login to merge, or discard this patch.
core/libraries/messages/EE_messenger.lib.php 1 patch
Indentation   +776 added lines, -776 removed lines patch added patch discarded remove patch
@@ -16,182 +16,182 @@  discard block
 block discarded – undo
16 16
  */
17 17
 abstract class EE_messenger extends EE_Messages_Base
18 18
 {
19
-    /**
20
-     * This property holds the default message types associated with this messenger when it is activated. The values of the array must match a valid message type.
21
-     * This property gets set by the _set_default_message_types() method.
22
-     *
23
-     * @var array
24
-     */
25
-    protected $_default_message_types = array();
19
+	/**
20
+	 * This property holds the default message types associated with this messenger when it is activated. The values of the array must match a valid message type.
21
+	 * This property gets set by the _set_default_message_types() method.
22
+	 *
23
+	 * @var array
24
+	 */
25
+	protected $_default_message_types = array();
26 26
 
27 27
 
28 28
 
29 29
 
30
-    /**
31
-     * This property holds the message types that are valid for use with this messenger.
32
-     * It gets set by the _set_valid_message_types() method.
33
-     *
34
-     * @var array
35
-     */
36
-    protected $_valid_message_types = array();
30
+	/**
31
+	 * This property holds the message types that are valid for use with this messenger.
32
+	 * It gets set by the _set_valid_message_types() method.
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $_valid_message_types = array();
37 37
 
38 38
 
39 39
 
40
-    /**
41
-     * Holds the configuration for the EE_Messages_Validator class to know how to validated the different fields. Note that the Validator will match each field here with the allowed shortcodes set in the "valid_shortcodes" array for the matched message type context.  So message types don't need to set a $_validator_config property.
42
-     *
43
-     * Remember, ALL fields must be declared in this array.  However, an empty value for the field means that the field will accept all valid shortcodes set for the given context in the message type (by default).
44
-     *
45
-     * Array should be in this format:
46
-     *
47
-     * array(
48
-     *  'field_name(i.e.to)' => array(
49
-     *      'shortcodes' => array('email'), //an array of shortcode groups (correspond to EE_Shortcodes library class) that are allowed in the field. Typically you can just include $this->_valid_shortcodes['field_name'] as the value here (because they will match).
50
-     *      'specific_shortcodes' => array( array('[EVENT_AUTHOR_EMAIL]' => esc_html__('Admin Email', 'event_espresso')), //if this index is present you can further restrict the field to ONLY specific shortcodes if an entire group isn't sufficient. Specific shortcodes need to be listed as an array with the index the shortcode and the value = the label.
51
-     *      'type' => 'email' //this is the field type and should match one of the validator types (see EE_Messages_Validator::validator() for all the possible types).  If not required you can just leave empty.,
52
-     *      'required' => array'[SHORTCODE]') //this is used to indicate the shortcodes that MUST be in the assembled array of shortcodes by the validator in order for this field to be included in validation.  Otherwise the validator will always assign shortcodes for this field (regardless of whether the field settings for the given messenger/message_type/context use the field or not.).. please note, this does NOT mean that the shortcodes listed here MUST be in the given field.
53
-     *  )
54
-     * )
55
-     *
56
-     * @var array
57
-     */
58
-    protected $_validator_config = array();
40
+	/**
41
+	 * Holds the configuration for the EE_Messages_Validator class to know how to validated the different fields. Note that the Validator will match each field here with the allowed shortcodes set in the "valid_shortcodes" array for the matched message type context.  So message types don't need to set a $_validator_config property.
42
+	 *
43
+	 * Remember, ALL fields must be declared in this array.  However, an empty value for the field means that the field will accept all valid shortcodes set for the given context in the message type (by default).
44
+	 *
45
+	 * Array should be in this format:
46
+	 *
47
+	 * array(
48
+	 *  'field_name(i.e.to)' => array(
49
+	 *      'shortcodes' => array('email'), //an array of shortcode groups (correspond to EE_Shortcodes library class) that are allowed in the field. Typically you can just include $this->_valid_shortcodes['field_name'] as the value here (because they will match).
50
+	 *      'specific_shortcodes' => array( array('[EVENT_AUTHOR_EMAIL]' => esc_html__('Admin Email', 'event_espresso')), //if this index is present you can further restrict the field to ONLY specific shortcodes if an entire group isn't sufficient. Specific shortcodes need to be listed as an array with the index the shortcode and the value = the label.
51
+	 *      'type' => 'email' //this is the field type and should match one of the validator types (see EE_Messages_Validator::validator() for all the possible types).  If not required you can just leave empty.,
52
+	 *      'required' => array'[SHORTCODE]') //this is used to indicate the shortcodes that MUST be in the assembled array of shortcodes by the validator in order for this field to be included in validation.  Otherwise the validator will always assign shortcodes for this field (regardless of whether the field settings for the given messenger/message_type/context use the field or not.).. please note, this does NOT mean that the shortcodes listed here MUST be in the given field.
53
+	 *  )
54
+	 * )
55
+	 *
56
+	 * @var array
57
+	 */
58
+	protected $_validator_config = array();
59 59
 
60 60
 
61 61
 
62
-    /**
63
-     * This will hold the EEM_message_templates model for interacting with the database and retrieving active templates for the messenger
64
-     * @var object
65
-     */
66
-    protected $_EEM_data;
62
+	/**
63
+	 * This will hold the EEM_message_templates model for interacting with the database and retrieving active templates for the messenger
64
+	 * @var object
65
+	 */
66
+	protected $_EEM_data;
67 67
 
68 68
 
69 69
 
70
-    /**
71
-     * this property just holds an array of the various template refs.
72
-     * @var array
73
-     */
74
-    protected $_template_fields = array();
70
+	/**
71
+	 * this property just holds an array of the various template refs.
72
+	 * @var array
73
+	 */
74
+	protected $_template_fields = array();
75 75
 
76 76
 
77 77
 
78 78
 
79
-    /**
80
-     * This holds an array of the arguments used in parsing a template for the sender.
81
-     * @var array
82
-     */
83
-    protected $_template_args = array();
79
+	/**
80
+	 * This holds an array of the arguments used in parsing a template for the sender.
81
+	 * @var array
82
+	 */
83
+	protected $_template_args = array();
84 84
 
85 85
 
86 86
 
87 87
 
88 88
 
89 89
 
90
-    /**
91
-     * This property will hold the configuration for any test settings fields that are required for the "test" button that is used to trigger an actual test of this messenger
92
-     *
93
-     * @protected
94
-     * @var array
95
-     */
96
-    protected $_test_settings_fields = array();
90
+	/**
91
+	 * This property will hold the configuration for any test settings fields that are required for the "test" button that is used to trigger an actual test of this messenger
92
+	 *
93
+	 * @protected
94
+	 * @var array
95
+	 */
96
+	protected $_test_settings_fields = array();
97 97
 
98 98
 
99 99
 
100 100
 
101 101
 
102 102
 
103
-    /**
104
-     * This will hold the EE_Messages_Template_Pack object when set on the messenger.  This is set via the validate and setup method which grabs the template pack from the incoming messages object.
105
-     *
106
-     * @since 4.5.0
107
-     *
108
-     * @var EE_Messages_Template_Pack
109
-     */
110
-    protected $_tmp_pack;
103
+	/**
104
+	 * This will hold the EE_Messages_Template_Pack object when set on the messenger.  This is set via the validate and setup method which grabs the template pack from the incoming messages object.
105
+	 *
106
+	 * @since 4.5.0
107
+	 *
108
+	 * @var EE_Messages_Template_Pack
109
+	 */
110
+	protected $_tmp_pack;
111 111
 
112 112
 
113 113
 
114 114
 
115
-    /**
116
-     * This will hold the variation to use when performing a send.  It is set via the validate and setup method which grabs the variation from the incoming messages object on the send method.
117
-     *
118
-     * @since 4.5.0
119
-     *
120
-     * @var string
121
-     */
122
-    protected $_variation;
115
+	/**
116
+	 * This will hold the variation to use when performing a send.  It is set via the validate and setup method which grabs the variation from the incoming messages object on the send method.
117
+	 *
118
+	 * @since 4.5.0
119
+	 *
120
+	 * @var string
121
+	 */
122
+	protected $_variation;
123 123
 
124 124
 
125 125
 
126 126
 
127 127
 
128
-    /**
129
-     * This property is a stdClass that holds labels for all the various supporting properties for this messenger.  These labels are set via the _set_supports_labels() method in children classes. Initially this will include the label for:
130
-     *
131
-     *  - template pack
132
-     *  - template variation
133
-     *
134
-     * @since 4.5.0
135
-     *
136
-     * @var stdClass
137
-     */
138
-    protected $_supports_labels;
128
+	/**
129
+	 * This property is a stdClass that holds labels for all the various supporting properties for this messenger.  These labels are set via the _set_supports_labels() method in children classes. Initially this will include the label for:
130
+	 *
131
+	 *  - template pack
132
+	 *  - template variation
133
+	 *
134
+	 * @since 4.5.0
135
+	 *
136
+	 * @var stdClass
137
+	 */
138
+	protected $_supports_labels;
139 139
 
140 140
 
141 141
 
142 142
 
143 143
 
144
-    /**
145
-     * This property is set when the send_message() method is called and holds the Message Type used to generate templates with this messenger for the messages.
146
-     *
147
-     * @var EE_message_type
148
-     */
149
-    protected $_incoming_message_type;
144
+	/**
145
+	 * This property is set when the send_message() method is called and holds the Message Type used to generate templates with this messenger for the messages.
146
+	 *
147
+	 * @var EE_message_type
148
+	 */
149
+	protected $_incoming_message_type;
150 150
 
151 151
 
152 152
 
153
-    /**
154
-     * This flag sets whether a messenger is activated by default  on installation (or reactivation) of EE core or not.
155
-     *
156
-     * @var bool
157
-     */
158
-    public $activate_on_install = false;
153
+	/**
154
+	 * This flag sets whether a messenger is activated by default  on installation (or reactivation) of EE core or not.
155
+	 *
156
+	 * @var bool
157
+	 */
158
+	public $activate_on_install = false;
159 159
 
160 160
 
161 161
 
162 162
 
163 163
 
164
-    public function __construct()
165
-    {
166
-        $this->_EEM_data = EEM_Message_Template_Group::instance();
167
-        $this->_messages_item_type = 'messenger';
164
+	public function __construct()
165
+	{
166
+		$this->_EEM_data = EEM_Message_Template_Group::instance();
167
+		$this->_messages_item_type = 'messenger';
168 168
 
169
-        parent::__construct();
169
+		parent::__construct();
170 170
 
171
-        $this->_set_test_settings_fields();
172
-        $this->_set_template_fields();
173
-        $this->_set_default_message_types();
174
-        $this->_set_valid_message_types();
175
-        $this->_set_validator_config();
171
+		$this->_set_test_settings_fields();
172
+		$this->_set_template_fields();
173
+		$this->_set_default_message_types();
174
+		$this->_set_valid_message_types();
175
+		$this->_set_validator_config();
176 176
 
177 177
 
178
-        $this->_supports_labels = new stdClass();
179
-        $this->_set_supports_labels();
180
-    }
178
+		$this->_supports_labels = new stdClass();
179
+		$this->_set_supports_labels();
180
+	}
181 181
 
182 182
 
183 183
 
184 184
 
185 185
 
186
-    /**
187
-     * _set_template_fields
188
-     * This sets up the fields that a messenger requires for the message to go out.
189
-     *
190
-     * @abstract
191
-     * @access  protected
192
-     * @return void
193
-     */
194
-    abstract protected function _set_template_fields();
186
+	/**
187
+	 * _set_template_fields
188
+	 * This sets up the fields that a messenger requires for the message to go out.
189
+	 *
190
+	 * @abstract
191
+	 * @access  protected
192
+	 * @return void
193
+	 */
194
+	abstract protected function _set_template_fields();
195 195
 
196 196
 
197 197
 
@@ -201,14 +201,14 @@  discard block
 block discarded – undo
201 201
 
202 202
 
203 203
 
204
-    /**
205
-     * This method sets the _default_message_type property (see definition in docs attached to property)
206
-     *
207
-     * @abstract
208
-     * @access protected
209
-     * @return void
210
-     */
211
-    abstract protected function _set_default_message_types();
204
+	/**
205
+	 * This method sets the _default_message_type property (see definition in docs attached to property)
206
+	 *
207
+	 * @abstract
208
+	 * @access protected
209
+	 * @return void
210
+	 */
211
+	abstract protected function _set_default_message_types();
212 212
 
213 213
 
214 214
 
@@ -216,15 +216,15 @@  discard block
 block discarded – undo
216 216
 
217 217
 
218 218
 
219
-    /**
220
-     * Sets the _valid_message_types property (see definition in cods attached to property)
221
-     *
222
-     * @since 4.5.0
223
-     *
224
-     * @abstract
225
-     * @return void
226
-     */
227
-    abstract protected function _set_valid_message_types();
219
+	/**
220
+	 * Sets the _valid_message_types property (see definition in cods attached to property)
221
+	 *
222
+	 * @since 4.5.0
223
+	 *
224
+	 * @abstract
225
+	 * @return void
226
+	 */
227
+	abstract protected function _set_valid_message_types();
228 228
 
229 229
 
230 230
 
@@ -232,171 +232,171 @@  discard block
 block discarded – undo
232 232
 
233 233
 
234 234
 
235
-    /**
236
-     * Child classes must declare the $_validator_config property using this method.
237
-     * See comments for $_validator_config for details on what it is used for.
238
-     *
239
-     * NOTE:  messengers should set an array of valid shortcodes for ALL scenarios.  The corresponding validator class (validators/{messenger}) can be used to restrict only certain shortcodes per template so users cannot add certain shortcodes.
240
-     *
241
-     * @access protected
242
-     * @return void
243
-     */
244
-    abstract protected function _set_validator_config();
235
+	/**
236
+	 * Child classes must declare the $_validator_config property using this method.
237
+	 * See comments for $_validator_config for details on what it is used for.
238
+	 *
239
+	 * NOTE:  messengers should set an array of valid shortcodes for ALL scenarios.  The corresponding validator class (validators/{messenger}) can be used to restrict only certain shortcodes per template so users cannot add certain shortcodes.
240
+	 *
241
+	 * @access protected
242
+	 * @return void
243
+	 */
244
+	abstract protected function _set_validator_config();
245 245
 
246 246
 
247 247
 
248 248
 
249 249
 
250 250
 
251
-    /**
252
-     * We just deliver the messages don't kill us!!  This method will need to be modified by child classes for whatever action is taken to actually send a message.
253
-     *
254
-     * @return bool|WP_Error
255
-     * @throw \Exception
256
-     */
257
-    abstract protected function _send_message();
251
+	/**
252
+	 * We just deliver the messages don't kill us!!  This method will need to be modified by child classes for whatever action is taken to actually send a message.
253
+	 *
254
+	 * @return bool|WP_Error
255
+	 * @throw \Exception
256
+	 */
257
+	abstract protected function _send_message();
258 258
 
259 259
 
260 260
 
261 261
 
262
-    /**
263
-     * We give you pretty previews of the messages!
264
-     * @return string html body for message content.
265
-     */
266
-    abstract protected function _preview();
262
+	/**
263
+	 * We give you pretty previews of the messages!
264
+	 * @return string html body for message content.
265
+	 */
266
+	abstract protected function _preview();
267 267
 
268 268
 
269 269
 
270 270
 
271
-    /**
272
-     * Used by messengers (or preview) for enqueueing any scripts or styles need in message generation.
273
-     *
274
-     * @since 4.5.0
275
-     *
276
-     * @return void
277
-     */
278
-    public function enqueue_scripts_styles()
279
-    {
280
-        do_action('AHEE__EE_messenger__enqueue_scripts_styles');
281
-    }
271
+	/**
272
+	 * Used by messengers (or preview) for enqueueing any scripts or styles need in message generation.
273
+	 *
274
+	 * @since 4.5.0
275
+	 *
276
+	 * @return void
277
+	 */
278
+	public function enqueue_scripts_styles()
279
+	{
280
+		do_action('AHEE__EE_messenger__enqueue_scripts_styles');
281
+	}
282 282
 
283 283
 
284 284
 
285 285
 
286 286
 
287
-    /**
288
-     * This is used to indicate whether a messenger must be sent immediately or not.
289
-     * eg. The HTML messenger will override this to return true because it should be displayed in user's browser right
290
-     * away.  The PDF messenger is similar.
291
-     *
292
-     * This flag thus overrides any priorities that may be set on the message type used to generate the message.
293
-     *
294
-     * Default for this is false.  So children classes must override this if they want a message to be executed immediately.
295
-     *
296
-     * @since  4.9.0
297
-     * @return bool
298
-     */
299
-    public function send_now()
300
-    {
301
-        return false;
302
-    }
287
+	/**
288
+	 * This is used to indicate whether a messenger must be sent immediately or not.
289
+	 * eg. The HTML messenger will override this to return true because it should be displayed in user's browser right
290
+	 * away.  The PDF messenger is similar.
291
+	 *
292
+	 * This flag thus overrides any priorities that may be set on the message type used to generate the message.
293
+	 *
294
+	 * Default for this is false.  So children classes must override this if they want a message to be executed immediately.
295
+	 *
296
+	 * @since  4.9.0
297
+	 * @return bool
298
+	 */
299
+	public function send_now()
300
+	{
301
+		return false;
302
+	}
303 303
 
304 304
 
305 305
 
306 306
 
307 307
 
308
-    /**
309
-     * This is a way for a messenger to indicate whether it allows an empty to field or not.
310
-     * Note: If the generated message is a for a preview, this value is ignored.
311
-     * @since 4.9.0
312
-     * @return bool
313
-     */
314
-    public function allow_empty_to_field()
315
-    {
316
-        return false;
317
-    }
308
+	/**
309
+	 * This is a way for a messenger to indicate whether it allows an empty to field or not.
310
+	 * Note: If the generated message is a for a preview, this value is ignored.
311
+	 * @since 4.9.0
312
+	 * @return bool
313
+	 */
314
+	public function allow_empty_to_field()
315
+	{
316
+		return false;
317
+	}
318 318
 
319 319
 
320 320
 
321 321
 
322 322
 
323
-    /**
324
-     * Sets the defaults for the _supports_labels property.  Can be overridden by child classes.
325
-     * @see property definition for info on how its formatted.
326
-     *
327
-     * @since 4.5.0;
328
-     * @return void
329
-     */
330
-    protected function _set_supports_labels()
331
-    {
332
-        $this->_set_supports_labels_defaults();
333
-    }
323
+	/**
324
+	 * Sets the defaults for the _supports_labels property.  Can be overridden by child classes.
325
+	 * @see property definition for info on how its formatted.
326
+	 *
327
+	 * @since 4.5.0;
328
+	 * @return void
329
+	 */
330
+	protected function _set_supports_labels()
331
+	{
332
+		$this->_set_supports_labels_defaults();
333
+	}
334 334
 
335 335
 
336 336
 
337 337
 
338 338
 
339
-    /**
340
-     * Sets the defaults for the _supports_labels property.
341
-     *
342
-     * @since 4.5.0
343
-     *
344
-     * @return void
345
-     */
346
-    private function _set_supports_labels_defaults()
347
-    {
348
-        $this->_supports_labels->template_pack = esc_html__('Template Structure', 'event_espresso');
349
-        $this->_supports_labels->template_variation = esc_html__('Template Style', 'event_espresso');
350
-        $this->_supports_labels->template_pack_description = esc_html__('Template Structure options are bundled structural changes for templates.', 'event_espresso');
339
+	/**
340
+	 * Sets the defaults for the _supports_labels property.
341
+	 *
342
+	 * @since 4.5.0
343
+	 *
344
+	 * @return void
345
+	 */
346
+	private function _set_supports_labels_defaults()
347
+	{
348
+		$this->_supports_labels->template_pack = esc_html__('Template Structure', 'event_espresso');
349
+		$this->_supports_labels->template_variation = esc_html__('Template Style', 'event_espresso');
350
+		$this->_supports_labels->template_pack_description = esc_html__('Template Structure options are bundled structural changes for templates.', 'event_espresso');
351 351
 
352
-        $this->_supports_labels->template_variation_description = esc_html__('These are different styles to choose from for the selected template structure.  Usually these affect things like font style, color, borders etc.  In some cases the styles will also make minor layout changes.', 'event_espresso');
352
+		$this->_supports_labels->template_variation_description = esc_html__('These are different styles to choose from for the selected template structure.  Usually these affect things like font style, color, borders etc.  In some cases the styles will also make minor layout changes.', 'event_espresso');
353 353
 
354
-        $this->_supports_labels = apply_filters('FHEE__EE_messenger___set_supports_labels_defaults___supports_labels', $this->_supports_labels, $this);
355
-    }
354
+		$this->_supports_labels = apply_filters('FHEE__EE_messenger___set_supports_labels_defaults___supports_labels', $this->_supports_labels, $this);
355
+	}
356 356
 
357 357
 
358 358
 
359 359
 
360 360
 
361
-    /**
362
-     * This returns the _supports_labels property.
363
-     *
364
-     * @since 4.5.0
365
-     *
366
-     * @return stdClass
367
-     */
368
-    public function get_supports_labels()
369
-    {
370
-        if (empty($this->_supports_labels->template_pack) || empty($this->_supports_labels->template_variation)) {
371
-            $this->_set_supports_labels_defaults();
372
-        }
373
-        return apply_filters('FHEE__EE_messenger__get_supports_labels', $this->_supports_labels, $this);
374
-    }
361
+	/**
362
+	 * This returns the _supports_labels property.
363
+	 *
364
+	 * @since 4.5.0
365
+	 *
366
+	 * @return stdClass
367
+	 */
368
+	public function get_supports_labels()
369
+	{
370
+		if (empty($this->_supports_labels->template_pack) || empty($this->_supports_labels->template_variation)) {
371
+			$this->_set_supports_labels_defaults();
372
+		}
373
+		return apply_filters('FHEE__EE_messenger__get_supports_labels', $this->_supports_labels, $this);
374
+	}
375 375
 
376 376
 
377 377
 
378 378
 
379
-    /**
380
-     * Used to retrieve a variation (typically the path/url to a css file)
381
-     *
382
-     * @since 4.5.0
383
-     *
384
-     * @param EE_Messages_Template_Pack $pack   The template pack used for retrieving the variation.
385
-     * @param string                    $message_type_name The name property of the message type that we need the variation for.
386
-     * @param bool                      $url   Whether to return url (true) or path (false). Default is false.
387
-     * @param string                    $type What variation type to return. Default is 'main'.
388
-     * @param string               $variation What variation for the template pack
389
-     * @param bool             $skip_filters This allows messengers to add a filter for another messengers get_variation but call skip filters on the callback so there is no recursion on apply_filters.
390
-     *
391
-     * @return string                    path or url for the requested variation.
392
-     */
393
-    public function get_variation(EE_Messages_Template_Pack $pack, $message_type_name, $url = false, $type = 'main', $variation = 'default', $skip_filters = false)
394
-    {
395
-        $this->_tmp_pack = $pack;
396
-        $variation_path = apply_filters('EE_messenger__get_variation__variation', false, $pack, $this->name, $message_type_name, $url, $type, $variation, $skip_filters);
397
-        $variation_path = empty($variation_path) ? $this->_tmp_pack->get_variation($this->name, $message_type_name, $type, $variation, $url, '.css', $skip_filters) : $variation_path;
398
-        return $variation_path;
399
-    }
379
+	/**
380
+	 * Used to retrieve a variation (typically the path/url to a css file)
381
+	 *
382
+	 * @since 4.5.0
383
+	 *
384
+	 * @param EE_Messages_Template_Pack $pack   The template pack used for retrieving the variation.
385
+	 * @param string                    $message_type_name The name property of the message type that we need the variation for.
386
+	 * @param bool                      $url   Whether to return url (true) or path (false). Default is false.
387
+	 * @param string                    $type What variation type to return. Default is 'main'.
388
+	 * @param string               $variation What variation for the template pack
389
+	 * @param bool             $skip_filters This allows messengers to add a filter for another messengers get_variation but call skip filters on the callback so there is no recursion on apply_filters.
390
+	 *
391
+	 * @return string                    path or url for the requested variation.
392
+	 */
393
+	public function get_variation(EE_Messages_Template_Pack $pack, $message_type_name, $url = false, $type = 'main', $variation = 'default', $skip_filters = false)
394
+	{
395
+		$this->_tmp_pack = $pack;
396
+		$variation_path = apply_filters('EE_messenger__get_variation__variation', false, $pack, $this->name, $message_type_name, $url, $type, $variation, $skip_filters);
397
+		$variation_path = empty($variation_path) ? $this->_tmp_pack->get_variation($this->name, $message_type_name, $type, $variation, $url, '.css', $skip_filters) : $variation_path;
398
+		return $variation_path;
399
+	}
400 400
 
401 401
 
402 402
 
@@ -404,205 +404,205 @@  discard block
 block discarded – undo
404 404
 
405 405
 
406 406
 
407
-    /**
408
-     * This just returns the default message types associated with this messenger when it is first activated.
409
-     *
410
-     * @access public
411
-     * @return array
412
-     */
413
-    public function get_default_message_types()
414
-    {
415
-        $class = get_class($this);
407
+	/**
408
+	 * This just returns the default message types associated with this messenger when it is first activated.
409
+	 *
410
+	 * @access public
411
+	 * @return array
412
+	 */
413
+	public function get_default_message_types()
414
+	{
415
+		$class = get_class($this);
416 416
 
417
-        // messenger specific filter
418
-        $default_types = apply_filters('FHEE__' . $class . '__get_default_message_types__default_types', $this->_default_message_types, $this);
417
+		// messenger specific filter
418
+		$default_types = apply_filters('FHEE__' . $class . '__get_default_message_types__default_types', $this->_default_message_types, $this);
419 419
 
420
-        // all messengers filter
421
-        $default_types = apply_filters('FHEE__EE_messenger__get_default_message_types__default_types', $default_types, $this);
422
-        return $default_types;
423
-    }
420
+		// all messengers filter
421
+		$default_types = apply_filters('FHEE__EE_messenger__get_default_message_types__default_types', $default_types, $this);
422
+		return $default_types;
423
+	}
424 424
 
425 425
 
426 426
 
427 427
 
428
-    /**
429
-     * Returns the valid message types associated with this messenger.
430
-     *
431
-     * @since 4.5.0
432
-     *
433
-     * @return array
434
-     */
435
-    public function get_valid_message_types()
436
-    {
437
-        $class = get_class($this);
438
-
439
-        // messenger specific filter
440
-        // messenger specific filter
441
-        $valid_types = apply_filters('FHEE__' . $class . '__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
442
-
443
-        // all messengers filter
444
-        $valid_types = apply_filters('FHEE__EE_messenger__get_valid_message_types__valid_types', $valid_types, $this);
445
-        return $valid_types;
446
-    }
447
-
448
-
449
-
450
-
451
-
452
-    /**
453
-     * this is just used by the custom validators (EE_Messages_Validator classes) to modify the _validator_config for certain message_type/messenger combos where a context may only use certain shortcodes etc.
454
-     *
455
-     * @access public
456
-     * @param array $new_config Whatever is put in here will reset the _validator_config property
457
-     */
458
-    public function set_validator_config($new_config)
459
-    {
460
-        $this->_validator_config = $new_config;
461
-    }
462
-
463
-
464
-
465
-
466
-    /**
467
-     * This returns the _validator_config property
468
-     *
469
-     * @access public
470
-     * @return array
471
-     */
472
-    public function get_validator_config()
473
-    {
474
-        $class = get_class($this);
475
-
476
-        $config = apply_filters('FHEE__' . $class . '__get_validator_config', $this->_validator_config, $this);
477
-        $config = apply_filters('FHEE__EE_messenger__get_validator_config', $config, $this);
478
-        return $config;
479
-    }
480
-
481
-
482
-
483
-
484
-    /**
485
-     * this public method accepts a page slug (for an EE_admin page) and will return the response from the child class callback function if that page is registered via the `_admin_registered_page` property set by the child class.
486
-     *
487
-     * @param string $page the slug of the EE admin page
488
-     * @param array $message_types an array of active message type objects
489
-     * @param string $action the page action (to allow for more specific handling - i.e. edit vs. add pages)
490
-     * @param array $extra  This is just an extra argument that can be used to pass additional data for setting up page content.
491
-     * @access public
492
-     * @return string content for page
493
-     */
494
-    public function get_messenger_admin_page_content($page, $action = null, $extra = array(), $message_types = array())
495
-    {
496
-        return $this->_get_admin_page_content($page, $action, $extra, $message_types);
497
-    }
498
-
499
-
500
-
501
-    /**
502
-     * @param $message_types
503
-     * @param array $extra
504
-     * @return mixed|string
505
-     */
506
-    protected function _get_admin_content_events_edit($message_types, $extra)
507
-    {
508
-        // defaults
509
-        $template_args = array();
510
-        $selector_rows = '';
511
-
512
-        // we don't need message types here so we're just going to ignore. we do, however, expect the event id here. The event id is needed to provide a link to setup a custom template for this event.
513
-        $event_id = isset($extra['event']) ? $extra['event'] : null;
514
-
515
-        $template_wrapper_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
516
-        $template_row_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_row.template.php';
517
-
518
-        // array of template objects for global and custom (non-trashed) (but remember just for this messenger!)
519
-        $global_templates = EEM_Message_Template_Group::instance()->get_all(
520
-            array( array( 'MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true ) )
521
-        );
522
-        $templates_for_event = EEM_Message_Template_Group::instance()->get_all_custom_templates_by_event(
523
-            $event_id,
524
-            array(
525
-                'MTP_messenger' => $this->name,
526
-                'MTP_is_active' => true
527
-            )
528
-        );
529
-        $templates_for_event = !empty($templates_for_event) ? $templates_for_event : array();
530
-
531
-        $msg_type_status_map = [
532
-            'payment' => 'PAP',
533
-            'payment_refund' => 'PRF',
534
-            'payment_reminder' => 'PPN',
535
-            'registration' => 'RAP',
536
-            'not_approved_registration' => 'RNA',
537
-            'pending_approval' => 'RPP',
538
-            'payment_declined' => 'PDC',
539
-            'declined_registration' => 'RDC',
540
-            'cancelled_registration' => 'RCN',
541
-            'payment_failed' => 'PFL',
542
-            'payment_cancelled' => 'PCN',
543
-        ];
544
-
545
-        // so we need to setup the rows for the selectors and we use the global mtpgs (cause those will the active message template groups)
546
-        foreach ($global_templates as $mtpgID => $mtpg) {
547
-            if ($mtpg instanceof EE_Message_Template_Group) {
548
-                // verify this message type is supposed to show on this page
549
-                $mtp_obj = $mtpg->message_type_obj();
550
-                if (! $mtp_obj instanceof EE_message_type) {
551
-                    continue;
552
-                }
553
-                $mtp_obj->admin_registered_pages = (array) $mtp_obj->admin_registered_pages;
554
-                if (! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
555
-                    continue;
556
-                }
557
-                $select_values = array();
558
-                $select_values[ $mtpgID ] = esc_html__('Global', 'event_espresso');
559
-                $default_value = array_key_exists($mtpgID, $templates_for_event) && ! $mtpg->get('MTP_is_override') ? $mtpgID : null;
560
-                // if the override has been set for the global template, then that means even if there are custom templates already created we ignore them because of the set override.
561
-                if (! $mtpg->get('MTP_is_override')) {
562
-                    // any custom templates for this message type?
563
-                    $custom_templates = EEM_Message_Template_Group::instance()->get_custom_message_template_by_m_and_mt($this->name, $mtpg->message_type());
564
-                    foreach ($custom_templates as $cmtpgID => $cmtpg) {
565
-                        $select_values[ $cmtpgID ] = $cmtpg->name();
566
-                        $default_value = array_key_exists($cmtpgID, $templates_for_event) ? $cmtpgID : $default_value;
567
-                    }
568
-                }
569
-                // if there is no $default_value then we set it as the global
570
-                $default_value = empty($default_value) ? $mtpgID : $default_value;
571
-                $c_config = $mtpg->contexts_config();
572
-                $edit_context = key(array_slice($c_config, -1));
573
-                $edit_url_query_args = [
574
-                    'page' => 'espresso_messages',
575
-                    'action' => 'edit_message_template',
576
-                    'id' => $default_value,
577
-                    'evt_id' => $event_id,
578
-                    'context' => $edit_context,
579
-                ];
580
-                $edit_url = EEH_URL::add_query_args_and_nonce($edit_url_query_args, admin_url('admin.php'));
581
-                $create_url_query_args = [
582
-                    'page' => 'espresso_messages',
583
-                    'action' => 'add_new_message_template',
584
-                    'GRP_ID' => $default_value,
585
-                    'message_type' => $mtpg->message_type(),
586
-                    'messenger' => $this->name
587
-                ];
588
-                $mt_slug = $mtpg->message_type();
589
-                $create_url = EEH_URL::add_query_args_and_nonce($create_url_query_args, admin_url('admin.php'));
590
-                $st_args['mtpgID'] = $mtpgID;
591
-                $st_args['mt_name'] = ucwords($mtp_obj->label['singular']);
592
-                $st_args['mt_slug'] = $mt_slug;
593
-                $st_args['messenger_slug'] = $this->name;
594
-                $st_args['status_code'] = $msg_type_status_map[ $mt_slug ] ?? '';
595
-                $st_args['selector'] = EEH_Form_Fields::select_input(
596
-                    'event_message_templates_relation[' . $mtpgID . ']',
597
-                    $select_values,
598
-                    $default_value,
599
-                    'data-messenger="' . $this->name . '" data-messagetype="' . $mt_slug . '"',
600
-                    'message-template-selector'
601
-                );
602
-                // note that  message template group that has override_all_custom set will remove the ability to set a custom message template based off of the global (and that also in turn overrides any other custom templates).
603
-                $st_args['create_button'] = $mtpg->get('MTP_is_override')
604
-                    ? ''
605
-                    : '
428
+	/**
429
+	 * Returns the valid message types associated with this messenger.
430
+	 *
431
+	 * @since 4.5.0
432
+	 *
433
+	 * @return array
434
+	 */
435
+	public function get_valid_message_types()
436
+	{
437
+		$class = get_class($this);
438
+
439
+		// messenger specific filter
440
+		// messenger specific filter
441
+		$valid_types = apply_filters('FHEE__' . $class . '__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
442
+
443
+		// all messengers filter
444
+		$valid_types = apply_filters('FHEE__EE_messenger__get_valid_message_types__valid_types', $valid_types, $this);
445
+		return $valid_types;
446
+	}
447
+
448
+
449
+
450
+
451
+
452
+	/**
453
+	 * this is just used by the custom validators (EE_Messages_Validator classes) to modify the _validator_config for certain message_type/messenger combos where a context may only use certain shortcodes etc.
454
+	 *
455
+	 * @access public
456
+	 * @param array $new_config Whatever is put in here will reset the _validator_config property
457
+	 */
458
+	public function set_validator_config($new_config)
459
+	{
460
+		$this->_validator_config = $new_config;
461
+	}
462
+
463
+
464
+
465
+
466
+	/**
467
+	 * This returns the _validator_config property
468
+	 *
469
+	 * @access public
470
+	 * @return array
471
+	 */
472
+	public function get_validator_config()
473
+	{
474
+		$class = get_class($this);
475
+
476
+		$config = apply_filters('FHEE__' . $class . '__get_validator_config', $this->_validator_config, $this);
477
+		$config = apply_filters('FHEE__EE_messenger__get_validator_config', $config, $this);
478
+		return $config;
479
+	}
480
+
481
+
482
+
483
+
484
+	/**
485
+	 * this public method accepts a page slug (for an EE_admin page) and will return the response from the child class callback function if that page is registered via the `_admin_registered_page` property set by the child class.
486
+	 *
487
+	 * @param string $page the slug of the EE admin page
488
+	 * @param array $message_types an array of active message type objects
489
+	 * @param string $action the page action (to allow for more specific handling - i.e. edit vs. add pages)
490
+	 * @param array $extra  This is just an extra argument that can be used to pass additional data for setting up page content.
491
+	 * @access public
492
+	 * @return string content for page
493
+	 */
494
+	public function get_messenger_admin_page_content($page, $action = null, $extra = array(), $message_types = array())
495
+	{
496
+		return $this->_get_admin_page_content($page, $action, $extra, $message_types);
497
+	}
498
+
499
+
500
+
501
+	/**
502
+	 * @param $message_types
503
+	 * @param array $extra
504
+	 * @return mixed|string
505
+	 */
506
+	protected function _get_admin_content_events_edit($message_types, $extra)
507
+	{
508
+		// defaults
509
+		$template_args = array();
510
+		$selector_rows = '';
511
+
512
+		// we don't need message types here so we're just going to ignore. we do, however, expect the event id here. The event id is needed to provide a link to setup a custom template for this event.
513
+		$event_id = isset($extra['event']) ? $extra['event'] : null;
514
+
515
+		$template_wrapper_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
516
+		$template_row_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_row.template.php';
517
+
518
+		// array of template objects for global and custom (non-trashed) (but remember just for this messenger!)
519
+		$global_templates = EEM_Message_Template_Group::instance()->get_all(
520
+			array( array( 'MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true ) )
521
+		);
522
+		$templates_for_event = EEM_Message_Template_Group::instance()->get_all_custom_templates_by_event(
523
+			$event_id,
524
+			array(
525
+				'MTP_messenger' => $this->name,
526
+				'MTP_is_active' => true
527
+			)
528
+		);
529
+		$templates_for_event = !empty($templates_for_event) ? $templates_for_event : array();
530
+
531
+		$msg_type_status_map = [
532
+			'payment' => 'PAP',
533
+			'payment_refund' => 'PRF',
534
+			'payment_reminder' => 'PPN',
535
+			'registration' => 'RAP',
536
+			'not_approved_registration' => 'RNA',
537
+			'pending_approval' => 'RPP',
538
+			'payment_declined' => 'PDC',
539
+			'declined_registration' => 'RDC',
540
+			'cancelled_registration' => 'RCN',
541
+			'payment_failed' => 'PFL',
542
+			'payment_cancelled' => 'PCN',
543
+		];
544
+
545
+		// so we need to setup the rows for the selectors and we use the global mtpgs (cause those will the active message template groups)
546
+		foreach ($global_templates as $mtpgID => $mtpg) {
547
+			if ($mtpg instanceof EE_Message_Template_Group) {
548
+				// verify this message type is supposed to show on this page
549
+				$mtp_obj = $mtpg->message_type_obj();
550
+				if (! $mtp_obj instanceof EE_message_type) {
551
+					continue;
552
+				}
553
+				$mtp_obj->admin_registered_pages = (array) $mtp_obj->admin_registered_pages;
554
+				if (! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
555
+					continue;
556
+				}
557
+				$select_values = array();
558
+				$select_values[ $mtpgID ] = esc_html__('Global', 'event_espresso');
559
+				$default_value = array_key_exists($mtpgID, $templates_for_event) && ! $mtpg->get('MTP_is_override') ? $mtpgID : null;
560
+				// if the override has been set for the global template, then that means even if there are custom templates already created we ignore them because of the set override.
561
+				if (! $mtpg->get('MTP_is_override')) {
562
+					// any custom templates for this message type?
563
+					$custom_templates = EEM_Message_Template_Group::instance()->get_custom_message_template_by_m_and_mt($this->name, $mtpg->message_type());
564
+					foreach ($custom_templates as $cmtpgID => $cmtpg) {
565
+						$select_values[ $cmtpgID ] = $cmtpg->name();
566
+						$default_value = array_key_exists($cmtpgID, $templates_for_event) ? $cmtpgID : $default_value;
567
+					}
568
+				}
569
+				// if there is no $default_value then we set it as the global
570
+				$default_value = empty($default_value) ? $mtpgID : $default_value;
571
+				$c_config = $mtpg->contexts_config();
572
+				$edit_context = key(array_slice($c_config, -1));
573
+				$edit_url_query_args = [
574
+					'page' => 'espresso_messages',
575
+					'action' => 'edit_message_template',
576
+					'id' => $default_value,
577
+					'evt_id' => $event_id,
578
+					'context' => $edit_context,
579
+				];
580
+				$edit_url = EEH_URL::add_query_args_and_nonce($edit_url_query_args, admin_url('admin.php'));
581
+				$create_url_query_args = [
582
+					'page' => 'espresso_messages',
583
+					'action' => 'add_new_message_template',
584
+					'GRP_ID' => $default_value,
585
+					'message_type' => $mtpg->message_type(),
586
+					'messenger' => $this->name
587
+				];
588
+				$mt_slug = $mtpg->message_type();
589
+				$create_url = EEH_URL::add_query_args_and_nonce($create_url_query_args, admin_url('admin.php'));
590
+				$st_args['mtpgID'] = $mtpgID;
591
+				$st_args['mt_name'] = ucwords($mtp_obj->label['singular']);
592
+				$st_args['mt_slug'] = $mt_slug;
593
+				$st_args['messenger_slug'] = $this->name;
594
+				$st_args['status_code'] = $msg_type_status_map[ $mt_slug ] ?? '';
595
+				$st_args['selector'] = EEH_Form_Fields::select_input(
596
+					'event_message_templates_relation[' . $mtpgID . ']',
597
+					$select_values,
598
+					$default_value,
599
+					'data-messenger="' . $this->name . '" data-messagetype="' . $mt_slug . '"',
600
+					'message-template-selector'
601
+				);
602
+				// note that  message template group that has override_all_custom set will remove the ability to set a custom message template based off of the global (and that also in turn overrides any other custom templates).
603
+				$st_args['create_button'] = $mtpg->get('MTP_is_override')
604
+					? ''
605
+					: '
606 606
                     <a data-messenger="' . $this->name . '"
607 607
                        data-messagetype="' . $mt_slug . '"
608 608
                        data-grpid="' . $default_value . '"
@@ -612,18 +612,18 @@  discard block
 block discarded – undo
612 612
                     >
613 613
                         ' . esc_html__('Create New Custom', 'event_espresso') . '
614 614
                     </a>';
615
-                $st_args['create_button'] = EE_Registry::instance()->CAP->current_user_can(
616
-                    'ee_edit_messages',
617
-                    'espresso_messages_add_new_message_template'
618
-                )
619
-                    ? $st_args['create_button']
620
-                    : '';
621
-                $st_args['edit_button']   = EE_Registry::instance()->CAP->current_user_can(
622
-                    'ee_edit_message',
623
-                    'espresso_messages_edit_message_template',
624
-                    $mtpgID
625
-                )
626
-                    ? '
615
+				$st_args['create_button'] = EE_Registry::instance()->CAP->current_user_can(
616
+					'ee_edit_messages',
617
+					'espresso_messages_add_new_message_template'
618
+				)
619
+					? $st_args['create_button']
620
+					: '';
621
+				$st_args['edit_button']   = EE_Registry::instance()->CAP->current_user_can(
622
+					'ee_edit_message',
623
+					'espresso_messages_edit_message_template',
624
+					$mtpgID
625
+				)
626
+					? '
627 627
                     <a data-messagetype="' . $mt_slug . '"
628 628
                        data-grpid="' . $default_value . '"
629 629
                        target="_blank"
@@ -632,322 +632,322 @@  discard block
 block discarded – undo
632 632
                     >
633 633
                         ' . esc_html__('Edit', 'event_espresso') . '
634 634
                     </a>'
635
-                    : '';
636
-                $selector_rows .= EEH_Template::display_template($template_row_path, $st_args, true);
637
-            }
638
-        }
639
-
640
-        // if no selectors present then get out.
641
-        if (empty($selector_rows)) {
642
-            return '';
643
-        }
644
-
645
-        $template_args['selector_rows'] = $selector_rows;
646
-        return EEH_Template::display_template($template_wrapper_path, $template_args, true);
647
-    }
648
-
649
-
650
-
651
-
652
-
653
-
654
-    /**
655
-     * get_template_fields
656
-     *
657
-     * @access public
658
-     * @return array $this->_template_fields
659
-     */
660
-    public function get_template_fields()
661
-    {
662
-        $template_fields = apply_filters('FHEE__' . get_class($this) . '__get_template_fields', $this->_template_fields, $this);
663
-        $template_fields = apply_filters('FHEE__EE_messenger__get_template_fields', $template_fields, $this);
664
-        return $template_fields;
665
-    }
666
-
667
-
668
-
669
-
670
-    /** SETUP METHODS **/
671
-    /**
672
-     * The following method doesn't NEED to be used by child classes but might be modified by the specific messenger
673
-     * @param string $item
674
-     * @param mixed $value
675
-     */
676
-    protected function _set_template_value($item, $value)
677
-    {
678
-        if (array_key_exists($item, $this->_template_fields)) {
679
-            $prop = '_' . $item;
680
-            $this->{$prop} = $value;
681
-        }
682
-    }
683
-
684
-    /**
685
-     * Sets up the message for sending.
686
-     *
687
-     * @param  EE_message $message the message object that contains details about the message.
688
-     * @param EE_message_type $message_type The message type object used in combination with this messenger to generate the provided message.
689
-     *
690
-     * @return bool Very important that all messengers return bool for successful send or not.  Error messages can be
691
-     *              added to EE_Error.
692
-     *              true = message sent successfully
693
-     *              false = message not sent but can be retried (i.e. the failure might be just due to communication issues at the time of send).
694
-     *              Throwing a SendMessageException means the message failed sending and cannot be retried.
695
-     *
696
-     * @throws SendMessageException
697
-     */
698
-    final public function send_message($message, EE_message_type $message_type)
699
-    {
700
-        try {
701
-            $this->_validate_and_setup($message);
702
-            $this->_incoming_message_type = $message_type;
703
-            $response = $this->_send_message();
704
-            if ($response instanceof WP_Error) {
705
-                EE_Error::add_error($response->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
706
-                $response = false;
707
-            }
708
-        } catch (\Exception $e) {
709
-            // convert to an instance of SendMessageException
710
-            throw new SendMessageException($e->getMessage());
711
-        }
712
-        return $response;
713
-    }
714
-
715
-
716
-
717
-    /**
718
-     * Sets up and returns message preview
719
-     * @param  EE_Message $message incoming message object
720
-     * @param EE_message_type $message_type This is whatever message type was used in combination with this messenger to generate the message.
721
-     * @param  bool   $send    true we will actually use the _send method (for test sends). FALSE we just return preview
722
-     * @return string          return the message html content
723
-     */
724
-    public function get_preview(EE_Message $message, EE_message_type $message_type, $send = false)
725
-    {
726
-        $this->_validate_and_setup($message);
727
-
728
-        $this->_incoming_message_type = $message_type;
729
-
730
-        if ($send) {
731
-            // are we overriding any existing template fields?
732
-            $settings = apply_filters(
733
-                'FHEE__EE_messenger__get_preview__messenger_test_settings',
734
-                $this->get_existing_test_settings(),
735
-                $this,
736
-                $send,
737
-                $message,
738
-                $message_type
739
-            );
740
-            if (! empty($settings)) {
741
-                foreach ($settings as $field => $value) {
742
-                    $this->_set_template_value($field, $value);
743
-                }
744
-            }
745
-        }
746
-
747
-        // enqueue preview js so that any links/buttons on the page are disabled.
748
-        if (! $send) {
749
-            // the below may seem like duplication.  However, typically if a messenger enqueues scripts/styles,
750
-            // it deregisters all existing wp scripts and styles first.  So the second hook ensures our previewer still gets setup.
751
-            add_action('admin_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
752
-            add_action('wp_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
753
-            add_action('AHEE__EE_messenger__enqueue_scripts_styles', array( $this, 'add_preview_script' ), 10);
754
-        }
755
-
756
-        return $send ? $this->_send_message() : $this->_preview();
757
-    }
758
-
759
-
760
-
761
-
762
-    /**
763
-     * Callback for enqueue_scripts so that we setup the preview script for all previews.
764
-     *
765
-     * @since 4.5.0
766
-     *
767
-     * @return void
768
-     */
769
-    public function add_preview_script()
770
-    {
771
-        // error message
772
-        EE_Registry::$i18n_js_strings['links_disabled'] = wp_strip_all_tags(
773
-            __('All the links on this page have been disabled because this is a generated preview message for the purpose of ensuring layout, style, and content setup.  To test generated links, you must trigger an actual message notification.', 'event_espresso')
774
-        );
775
-        wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL . 'messages/messenger/assets/js/ee-messages-preview.js', array( 'jquery' ), EVENT_ESPRESSO_VERSION, true);
776
-        wp_localize_script('ee-messages-preview-js', 'eei18n', EE_Registry::$i18n_js_strings);
777
-        wp_enqueue_script('ee-messages-preview-js');
778
-    }
779
-
780
-
781
-
782
-
783
-    /**
784
-     * simply validates the incoming message object and then sets up the properties for the messenger
785
-     * @param  EE_Message $message
786
-     * @throws EE_Error
787
-     */
788
-    protected function _validate_and_setup(EE_Message $message)
789
-    {
790
-        $template_pack = $message->get_template_pack();
791
-        $variation = $message->get_template_pack_variation();
792
-
793
-        // verify we have the required template pack value on the $message object.
794
-        if (! $template_pack instanceof EE_Messages_Template_Pack) {
795
-            throw new EE_Error(esc_html__('Incoming $message object must have an EE_Messages_Template_Pack object available.', 'event_espresso'));
796
-        }
797
-
798
-        $this->_tmp_pack = $template_pack;
799
-
800
-        $this->_variation = $variation ? $variation : 'default';
801
-
802
-        $template_fields = $this->get_template_fields();
803
-
804
-        foreach ($template_fields as $template => $value) {
805
-            if ($template !== 'extra') {
806
-                $column_value = $message->get_field_or_extra_meta('MSG_' . $template);
807
-                $message_template_value = $column_value ? $column_value : null;
808
-                $this->_set_template_value($template, $message_template_value);
809
-            }
810
-        }
811
-    }
812
-
813
-
814
-
815
-    /**
816
-     * Utility method for child classes to get the contents of a template file and return
817
-     *
818
-     * We're assuming the child messenger class has already setup template args!
819
-     * @param  bool $preview if true we use the preview wrapper otherwise we use main wrapper.
820
-     * @return string
821
-     * @throws \EE_Error
822
-     */
823
-    protected function _get_main_template($preview = false)
824
-    {
825
-        $type = $preview ? 'preview' : 'main';
826
-
827
-        $wrapper_template = $this->_tmp_pack->get_wrapper($this->name, $type);
828
-
829
-        // check file exists and is readable
830
-        if (!is_readable($wrapper_template)) {
831
-            throw new EE_Error(sprintf(esc_html__('Unable to access the template file for the %s messenger main content wrapper.  The location being attempted is %s.', 'event_espresso'), ucwords($this->label['singular']), $wrapper_template));
832
-        }
833
-
834
-        // add message type to template args
835
-        $this->_template_args['message_type'] = $this->_incoming_message_type;
836
-
837
-        return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
838
-    }
839
-
840
-
841
-
842
-    /**
843
-     * set the _test_settings_fields property
844
-     *
845
-     * @access protected
846
-     * @return void
847
-     */
848
-    protected function _set_test_settings_fields()
849
-    {
850
-        $this->_test_settings_fields = array();
851
-    }
852
-
853
-
854
-
855
-    /**
856
-     * return the _test_settings_fields property
857
-     * @return array
858
-     */
859
-    public function get_test_settings_fields()
860
-    {
861
-        return $this->_test_settings_fields;
862
-    }
863
-
864
-
865
-
866
-
867
-    /**
868
-     * This just returns any existing test settings that might be saved in the database
869
-     *
870
-     * @access public
871
-     * @return array
872
-     */
873
-    public function get_existing_test_settings()
874
-    {
875
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
876
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
877
-        $settings = $Message_Resource_Manager->get_active_messengers_option();
878
-        return isset($settings[ $this->name ]['test_settings']) ? $settings[ $this->name ]['test_settings'] : array();
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * All this does is set the existing test settings (in the db) for the messenger
885
-     *
886
-     * @access public
887
-     * @param $settings
888
-     * @return bool success/fail
889
-     */
890
-    public function set_existing_test_settings($settings)
891
-    {
892
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
893
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
894
-        $existing = $Message_Resource_Manager->get_active_messengers_option();
895
-        $existing[ $this->name ]['test_settings'] = $settings;
896
-        return $Message_Resource_Manager->update_active_messengers_option($existing);
897
-    }
898
-
899
-
900
-
901
-    /**
902
-     * This just returns the field label for a given field setup in the _template_fields property.
903
-     *
904
-     * @since   4.3.0
905
-     *
906
-     * @param string $field The field to retrieve the label for
907
-     * @return string             The label
908
-     */
909
-    public function get_field_label($field)
910
-    {
911
-        // first let's see if the field requests is in the top level array.
912
-        if (isset($this->_template_fields[ $field ]) && !empty($this->_template_fields[ $field ]['label'])) {
913
-            return $this->_template[ $field ]['label'];
914
-        }
915
-
916
-        // nope so let's look in the extra array to see if it's there HOWEVER if the field exists as a top level index in the extra array then we know the label is in the 'main' index.
917
-        if (isset($this->_template_fields['extra']) && !empty($this->_template_fields['extra'][ $field ]) && !empty($this->_template_fields['extra'][ $field ]['main']['label'])) {
918
-            return $this->_template_fields['extra'][ $field ]['main']['label'];
919
-        }
920
-
921
-        // now it's possible this field may just be existing in any of the extra array items.
922
-        if (!empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
923
-            foreach ($this->_template_fields['extra'] as $main_field => $subfields) {
924
-                if (!is_array($subfields)) {
925
-                    continue;
926
-                }
927
-                if (isset($subfields[ $field ]) && !empty($subfields[ $field ]['label'])) {
928
-                    return $subfields[ $field ]['label'];
929
-                }
930
-            }
931
-        }
932
-
933
-        // if we made it here then there's no label set so let's just return the $field.
934
-        return $field;
935
-    }
936
-
937
-
938
-
939
-
940
-    /**
941
-     * This is a method called from EE_messages when this messenger is a generating messenger and the sending messenger is a different messenger.  Child messengers can set hooks for the sending messenger to callback on if necessary (i.e. swap out css files or something else).
942
-     *
943
-     * @since 4.5.0
944
-     *
945
-     * @param string $sending_messenger_name the name of the sending messenger so we only set the hooks needed.
946
-     *
947
-     * @return void
948
-     */
949
-    public function do_secondary_messenger_hooks($sending_messenger_name)
950
-    {
951
-        return;
952
-    }
635
+					: '';
636
+				$selector_rows .= EEH_Template::display_template($template_row_path, $st_args, true);
637
+			}
638
+		}
639
+
640
+		// if no selectors present then get out.
641
+		if (empty($selector_rows)) {
642
+			return '';
643
+		}
644
+
645
+		$template_args['selector_rows'] = $selector_rows;
646
+		return EEH_Template::display_template($template_wrapper_path, $template_args, true);
647
+	}
648
+
649
+
650
+
651
+
652
+
653
+
654
+	/**
655
+	 * get_template_fields
656
+	 *
657
+	 * @access public
658
+	 * @return array $this->_template_fields
659
+	 */
660
+	public function get_template_fields()
661
+	{
662
+		$template_fields = apply_filters('FHEE__' . get_class($this) . '__get_template_fields', $this->_template_fields, $this);
663
+		$template_fields = apply_filters('FHEE__EE_messenger__get_template_fields', $template_fields, $this);
664
+		return $template_fields;
665
+	}
666
+
667
+
668
+
669
+
670
+	/** SETUP METHODS **/
671
+	/**
672
+	 * The following method doesn't NEED to be used by child classes but might be modified by the specific messenger
673
+	 * @param string $item
674
+	 * @param mixed $value
675
+	 */
676
+	protected function _set_template_value($item, $value)
677
+	{
678
+		if (array_key_exists($item, $this->_template_fields)) {
679
+			$prop = '_' . $item;
680
+			$this->{$prop} = $value;
681
+		}
682
+	}
683
+
684
+	/**
685
+	 * Sets up the message for sending.
686
+	 *
687
+	 * @param  EE_message $message the message object that contains details about the message.
688
+	 * @param EE_message_type $message_type The message type object used in combination with this messenger to generate the provided message.
689
+	 *
690
+	 * @return bool Very important that all messengers return bool for successful send or not.  Error messages can be
691
+	 *              added to EE_Error.
692
+	 *              true = message sent successfully
693
+	 *              false = message not sent but can be retried (i.e. the failure might be just due to communication issues at the time of send).
694
+	 *              Throwing a SendMessageException means the message failed sending and cannot be retried.
695
+	 *
696
+	 * @throws SendMessageException
697
+	 */
698
+	final public function send_message($message, EE_message_type $message_type)
699
+	{
700
+		try {
701
+			$this->_validate_and_setup($message);
702
+			$this->_incoming_message_type = $message_type;
703
+			$response = $this->_send_message();
704
+			if ($response instanceof WP_Error) {
705
+				EE_Error::add_error($response->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
706
+				$response = false;
707
+			}
708
+		} catch (\Exception $e) {
709
+			// convert to an instance of SendMessageException
710
+			throw new SendMessageException($e->getMessage());
711
+		}
712
+		return $response;
713
+	}
714
+
715
+
716
+
717
+	/**
718
+	 * Sets up and returns message preview
719
+	 * @param  EE_Message $message incoming message object
720
+	 * @param EE_message_type $message_type This is whatever message type was used in combination with this messenger to generate the message.
721
+	 * @param  bool   $send    true we will actually use the _send method (for test sends). FALSE we just return preview
722
+	 * @return string          return the message html content
723
+	 */
724
+	public function get_preview(EE_Message $message, EE_message_type $message_type, $send = false)
725
+	{
726
+		$this->_validate_and_setup($message);
727
+
728
+		$this->_incoming_message_type = $message_type;
729
+
730
+		if ($send) {
731
+			// are we overriding any existing template fields?
732
+			$settings = apply_filters(
733
+				'FHEE__EE_messenger__get_preview__messenger_test_settings',
734
+				$this->get_existing_test_settings(),
735
+				$this,
736
+				$send,
737
+				$message,
738
+				$message_type
739
+			);
740
+			if (! empty($settings)) {
741
+				foreach ($settings as $field => $value) {
742
+					$this->_set_template_value($field, $value);
743
+				}
744
+			}
745
+		}
746
+
747
+		// enqueue preview js so that any links/buttons on the page are disabled.
748
+		if (! $send) {
749
+			// the below may seem like duplication.  However, typically if a messenger enqueues scripts/styles,
750
+			// it deregisters all existing wp scripts and styles first.  So the second hook ensures our previewer still gets setup.
751
+			add_action('admin_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
752
+			add_action('wp_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
753
+			add_action('AHEE__EE_messenger__enqueue_scripts_styles', array( $this, 'add_preview_script' ), 10);
754
+		}
755
+
756
+		return $send ? $this->_send_message() : $this->_preview();
757
+	}
758
+
759
+
760
+
761
+
762
+	/**
763
+	 * Callback for enqueue_scripts so that we setup the preview script for all previews.
764
+	 *
765
+	 * @since 4.5.0
766
+	 *
767
+	 * @return void
768
+	 */
769
+	public function add_preview_script()
770
+	{
771
+		// error message
772
+		EE_Registry::$i18n_js_strings['links_disabled'] = wp_strip_all_tags(
773
+			__('All the links on this page have been disabled because this is a generated preview message for the purpose of ensuring layout, style, and content setup.  To test generated links, you must trigger an actual message notification.', 'event_espresso')
774
+		);
775
+		wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL . 'messages/messenger/assets/js/ee-messages-preview.js', array( 'jquery' ), EVENT_ESPRESSO_VERSION, true);
776
+		wp_localize_script('ee-messages-preview-js', 'eei18n', EE_Registry::$i18n_js_strings);
777
+		wp_enqueue_script('ee-messages-preview-js');
778
+	}
779
+
780
+
781
+
782
+
783
+	/**
784
+	 * simply validates the incoming message object and then sets up the properties for the messenger
785
+	 * @param  EE_Message $message
786
+	 * @throws EE_Error
787
+	 */
788
+	protected function _validate_and_setup(EE_Message $message)
789
+	{
790
+		$template_pack = $message->get_template_pack();
791
+		$variation = $message->get_template_pack_variation();
792
+
793
+		// verify we have the required template pack value on the $message object.
794
+		if (! $template_pack instanceof EE_Messages_Template_Pack) {
795
+			throw new EE_Error(esc_html__('Incoming $message object must have an EE_Messages_Template_Pack object available.', 'event_espresso'));
796
+		}
797
+
798
+		$this->_tmp_pack = $template_pack;
799
+
800
+		$this->_variation = $variation ? $variation : 'default';
801
+
802
+		$template_fields = $this->get_template_fields();
803
+
804
+		foreach ($template_fields as $template => $value) {
805
+			if ($template !== 'extra') {
806
+				$column_value = $message->get_field_or_extra_meta('MSG_' . $template);
807
+				$message_template_value = $column_value ? $column_value : null;
808
+				$this->_set_template_value($template, $message_template_value);
809
+			}
810
+		}
811
+	}
812
+
813
+
814
+
815
+	/**
816
+	 * Utility method for child classes to get the contents of a template file and return
817
+	 *
818
+	 * We're assuming the child messenger class has already setup template args!
819
+	 * @param  bool $preview if true we use the preview wrapper otherwise we use main wrapper.
820
+	 * @return string
821
+	 * @throws \EE_Error
822
+	 */
823
+	protected function _get_main_template($preview = false)
824
+	{
825
+		$type = $preview ? 'preview' : 'main';
826
+
827
+		$wrapper_template = $this->_tmp_pack->get_wrapper($this->name, $type);
828
+
829
+		// check file exists and is readable
830
+		if (!is_readable($wrapper_template)) {
831
+			throw new EE_Error(sprintf(esc_html__('Unable to access the template file for the %s messenger main content wrapper.  The location being attempted is %s.', 'event_espresso'), ucwords($this->label['singular']), $wrapper_template));
832
+		}
833
+
834
+		// add message type to template args
835
+		$this->_template_args['message_type'] = $this->_incoming_message_type;
836
+
837
+		return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
838
+	}
839
+
840
+
841
+
842
+	/**
843
+	 * set the _test_settings_fields property
844
+	 *
845
+	 * @access protected
846
+	 * @return void
847
+	 */
848
+	protected function _set_test_settings_fields()
849
+	{
850
+		$this->_test_settings_fields = array();
851
+	}
852
+
853
+
854
+
855
+	/**
856
+	 * return the _test_settings_fields property
857
+	 * @return array
858
+	 */
859
+	public function get_test_settings_fields()
860
+	{
861
+		return $this->_test_settings_fields;
862
+	}
863
+
864
+
865
+
866
+
867
+	/**
868
+	 * This just returns any existing test settings that might be saved in the database
869
+	 *
870
+	 * @access public
871
+	 * @return array
872
+	 */
873
+	public function get_existing_test_settings()
874
+	{
875
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
876
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
877
+		$settings = $Message_Resource_Manager->get_active_messengers_option();
878
+		return isset($settings[ $this->name ]['test_settings']) ? $settings[ $this->name ]['test_settings'] : array();
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * All this does is set the existing test settings (in the db) for the messenger
885
+	 *
886
+	 * @access public
887
+	 * @param $settings
888
+	 * @return bool success/fail
889
+	 */
890
+	public function set_existing_test_settings($settings)
891
+	{
892
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
893
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
894
+		$existing = $Message_Resource_Manager->get_active_messengers_option();
895
+		$existing[ $this->name ]['test_settings'] = $settings;
896
+		return $Message_Resource_Manager->update_active_messengers_option($existing);
897
+	}
898
+
899
+
900
+
901
+	/**
902
+	 * This just returns the field label for a given field setup in the _template_fields property.
903
+	 *
904
+	 * @since   4.3.0
905
+	 *
906
+	 * @param string $field The field to retrieve the label for
907
+	 * @return string             The label
908
+	 */
909
+	public function get_field_label($field)
910
+	{
911
+		// first let's see if the field requests is in the top level array.
912
+		if (isset($this->_template_fields[ $field ]) && !empty($this->_template_fields[ $field ]['label'])) {
913
+			return $this->_template[ $field ]['label'];
914
+		}
915
+
916
+		// nope so let's look in the extra array to see if it's there HOWEVER if the field exists as a top level index in the extra array then we know the label is in the 'main' index.
917
+		if (isset($this->_template_fields['extra']) && !empty($this->_template_fields['extra'][ $field ]) && !empty($this->_template_fields['extra'][ $field ]['main']['label'])) {
918
+			return $this->_template_fields['extra'][ $field ]['main']['label'];
919
+		}
920
+
921
+		// now it's possible this field may just be existing in any of the extra array items.
922
+		if (!empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
923
+			foreach ($this->_template_fields['extra'] as $main_field => $subfields) {
924
+				if (!is_array($subfields)) {
925
+					continue;
926
+				}
927
+				if (isset($subfields[ $field ]) && !empty($subfields[ $field ]['label'])) {
928
+					return $subfields[ $field ]['label'];
929
+				}
930
+			}
931
+		}
932
+
933
+		// if we made it here then there's no label set so let's just return the $field.
934
+		return $field;
935
+	}
936
+
937
+
938
+
939
+
940
+	/**
941
+	 * This is a method called from EE_messages when this messenger is a generating messenger and the sending messenger is a different messenger.  Child messengers can set hooks for the sending messenger to callback on if necessary (i.e. swap out css files or something else).
942
+	 *
943
+	 * @since 4.5.0
944
+	 *
945
+	 * @param string $sending_messenger_name the name of the sending messenger so we only set the hooks needed.
946
+	 *
947
+	 * @return void
948
+	 */
949
+	public function do_secondary_messenger_hooks($sending_messenger_name)
950
+	{
951
+		return;
952
+	}
953 953
 }
Please login to merge, or discard this patch.
core/EE_System.core.php 2 patches
Indentation   +1212 added lines, -1212 removed lines patch added patch discarded remove patch
@@ -24,1216 +24,1216 @@
 block discarded – undo
24 24
  */
25 25
 final class EE_System implements ResettableInterface
26 26
 {
27
-    /**
28
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
29
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
30
-     */
31
-    const req_type_normal = 0;
32
-
33
-    /**
34
-     * Indicates this is a brand new installation of EE so we should install
35
-     * tables and default data etc
36
-     */
37
-    const req_type_new_activation = 1;
38
-
39
-    /**
40
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
41
-     * and we just exited maintenance mode). We MUST check the database is setup properly
42
-     * and that default data is setup too
43
-     */
44
-    const req_type_reactivation = 2;
45
-
46
-    /**
47
-     * indicates that EE has been upgraded since its previous request.
48
-     * We may have data migration scripts to call and will want to trigger maintenance mode
49
-     */
50
-    const req_type_upgrade = 3;
51
-
52
-    /**
53
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
54
-     */
55
-    const req_type_downgrade = 4;
56
-
57
-    /**
58
-     * @deprecated since version 4.6.0.dev.006
59
-     * Now whenever a new_activation is detected the request type is still just
60
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we're in maintenance mode
61
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
62
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
63
-     * (Specifically, when the migration manager indicates migrations are finished
64
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
65
-     */
66
-    const req_type_activation_but_not_installed = 5;
67
-
68
-    /**
69
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
70
-     */
71
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
72
-
73
-    /**
74
-     * @var AddonManager $addon_manager
75
-     */
76
-    private $addon_manager;
77
-
78
-    /**
79
-     * @var EE_System $_instance
80
-     */
81
-    private static $_instance;
82
-
83
-    /**
84
-     * @var EE_Registry $registry
85
-     */
86
-    private $registry;
87
-
88
-    /**
89
-     * @var LoaderInterface $loader
90
-     */
91
-    private $loader;
92
-
93
-    /**
94
-     * @var EE_Capabilities $capabilities
95
-     */
96
-    private $capabilities;
97
-
98
-    /**
99
-     * @var EE_Maintenance_Mode $maintenance_mode
100
-     */
101
-    private $maintenance_mode;
102
-
103
-    /**
104
-     * @var RequestInterface $request
105
-     */
106
-    private $request;
107
-
108
-    /**
109
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
110
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
111
-     *
112
-     * @var int $_req_type
113
-     */
114
-    private $_req_type;
115
-
116
-    /**
117
-     * Whether or not there was a non-micro version change in EE core version during this request
118
-     *
119
-     * @var boolean $_major_version_change
120
-     */
121
-    private $_major_version_change = false;
122
-
123
-    /**
124
-     * @var Router $router
125
-     */
126
-    private $router;
127
-
128
-    /**
129
-     * @param EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes
130
-     */
131
-    private $register_custom_post_types;
132
-
133
-    /**
134
-     * @param EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies
135
-     */
136
-    private $register_custom_taxonomies;
137
-
138
-    /**
139
-     * @param EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms
140
-     */
141
-    private $register_custom_taxonomy_terms;
142
-
143
-    /**
144
-     * @singleton method used to instantiate class object
145
-     * @param LoaderInterface|null     $loader
146
-     * @param EE_Maintenance_Mode|null $maintenance_mode
147
-     * @param EE_Registry|null         $registry
148
-     * @param RequestInterface|null    $request
149
-     * @param Router|null              $router
150
-     * @return EE_System
151
-     */
152
-    public static function instance(
153
-        LoaderInterface $loader = null,
154
-        EE_Maintenance_Mode $maintenance_mode = null,
155
-        EE_Registry $registry = null,
156
-        RequestInterface $request = null,
157
-        Router $router = null
158
-    ): EE_System {
159
-        // check if class object is instantiated
160
-        if (! self::$_instance instanceof EE_System) {
161
-            self::$_instance = new self($loader, $maintenance_mode, $registry, $request, $router);
162
-        }
163
-        return self::$_instance;
164
-    }
165
-
166
-
167
-    /**
168
-     * resets the instance and returns it
169
-     *
170
-     * @return EE_System
171
-     */
172
-    public static function reset(): EE_System
173
-    {
174
-        self::$_instance->_req_type = null;
175
-        // make sure none of the old hooks are left hanging around
176
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
177
-        // we need to reset the migration manager in order for it to detect DMSs properly
178
-        EE_Data_Migration_Manager::reset();
179
-        self::instance()->detect_activations_or_upgrades();
180
-        self::instance()->perform_activations_upgrades_and_migrations();
181
-        return self::instance();
182
-    }
183
-
184
-
185
-    /**
186
-     * sets hooks for running rest of system
187
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
188
-     * starting EE Addons from any other point may lead to problems
189
-     *
190
-     * @param LoaderInterface     $loader
191
-     * @param EE_Maintenance_Mode $maintenance_mode
192
-     * @param EE_Registry         $registry
193
-     * @param RequestInterface    $request
194
-     * @param Router              $router
195
-     */
196
-    private function __construct(
197
-        LoaderInterface $loader,
198
-        EE_Maintenance_Mode $maintenance_mode,
199
-        EE_Registry $registry,
200
-        RequestInterface $request,
201
-        Router $router
202
-    ) {
203
-        $this->registry         = $registry;
204
-        $this->loader           = $loader;
205
-        $this->request          = $request;
206
-        $this->router           = $router;
207
-        $this->maintenance_mode = $maintenance_mode;
208
-        do_action('AHEE__EE_System__construct__begin', $this);
209
-        add_action(
210
-            'AHEE__EE_Bootstrap__load_espresso_addons',
211
-            [$this, 'loadCapabilities'],
212
-            5
213
-        );
214
-        add_action(
215
-            'AHEE__EE_Bootstrap__load_espresso_addons',
216
-            [$this, 'loadCommandBus'],
217
-            7
218
-        );
219
-        add_action(
220
-            'AHEE__EE_Bootstrap__load_espresso_addons',
221
-            [$this, 'loadPluginApi'],
222
-            9
223
-        );
224
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
225
-        add_action(
226
-            'AHEE__EE_Bootstrap__load_espresso_addons',
227
-            [$this, 'load_espresso_addons']
228
-        );
229
-        // when an ee addon is activated, we want to call the core hook(s) again
230
-        // because the newly-activated addon didn't get a chance to run at all
231
-        add_action('activate_plugin', [$this, 'load_espresso_addons'], 1);
232
-        // detect whether install or upgrade
233
-        add_action(
234
-            'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
235
-            [$this, 'detect_activations_or_upgrades'],
236
-            3
237
-        );
238
-        // load EE_Config, EE_Textdomain, etc
239
-        add_action(
240
-            'AHEE__EE_Bootstrap__load_core_configuration',
241
-            [$this, 'load_core_configuration'],
242
-            5
243
-        );
244
-        // load specifications for matching routes to current request
245
-        add_action(
246
-            'AHEE__EE_Bootstrap__load_core_configuration',
247
-            [$this, 'loadRouteMatchSpecifications']
248
-        );
249
-        // load specifications for custom post types
250
-        add_action(
251
-            'AHEE__EE_Bootstrap__load_core_configuration',
252
-            array($this, 'loadCustomPostTypes')
253
-        );
254
-        // load specifications for custom post types
255
-        add_action(
256
-            'AHEE__EE_Bootstrap__load_core_configuration',
257
-            array($this, 'loadCustomPostTypes')
258
-        );
259
-        // load EE_Config, EE_Textdomain, etc
260
-        add_action(
261
-            'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
262
-            [$this, 'register_shortcodes_modules_and_widgets'],
263
-            7
264
-        );
265
-        // you wanna get going? I wanna get going... let's get going!
266
-        add_action(
267
-            'AHEE__EE_Bootstrap__brew_espresso',
268
-            [$this, 'brew_espresso'],
269
-            9
270
-        );
271
-        // other housekeeping
272
-        // exclude EE critical pages from wp_list_pages
273
-        add_filter(
274
-            'wp_list_pages_excludes',
275
-            [$this, 'remove_pages_from_wp_list_pages'],
276
-            10
277
-        );
278
-        // ALL EE Addons should use the following hook point to attach their initial setup too
279
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
280
-        do_action('AHEE__EE_System__construct__complete', $this);
281
-    }
282
-
283
-
284
-    /**
285
-     * load and setup EE_Capabilities
286
-     *
287
-     * @return void
288
-     */
289
-    public function loadCapabilities()
290
-    {
291
-        $this->capabilities = $this->loader->getShared('EE_Capabilities');
292
-        add_action(
293
-            'AHEE__EE_Capabilities__init_caps__before_initialization',
294
-            function () {
295
-                LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
296
-            }
297
-        );
298
-    }
299
-
300
-
301
-    /**
302
-     * create and cache the CommandBus, and also add middleware
303
-     * The CapChecker middleware requires the use of EE_Capabilities
304
-     * which is why we need to load the CommandBus after Caps are set up
305
-     *
306
-     * @return void
307
-     */
308
-    public function loadCommandBus()
309
-    {
310
-        $this->loader->getShared(
311
-            'CommandBusInterface',
312
-            [
313
-                null,
314
-                apply_filters(
315
-                    'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
316
-                    [
317
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
318
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
319
-                    ]
320
-                ),
321
-            ]
322
-        );
323
-    }
324
-
325
-
326
-    /**
327
-     * @return void
328
-     * @throws Exception
329
-     */
330
-    public function loadPluginApi()
331
-    {
332
-        $this->addon_manager = $this->loader->getShared(AddonManager::class);
333
-        $this->addon_manager->initialize();
334
-        $this->loader->getShared('EE_Request_Handler');
335
-    }
336
-
337
-
338
-    /**
339
-     * load_espresso_addons
340
-     * allow addons to load first so that they can set hooks for running DMS's, etc
341
-     * this is hooked into both:
342
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
343
-     *        which runs during the WP 'plugins_loaded' action at priority 5
344
-     *    and the WP 'activate_plugin' hook point
345
-     *
346
-     * @return void
347
-     * @throws Exception
348
-     */
349
-    public function load_espresso_addons()
350
-    {
351
-        // looking for hooks? they've been moved into the AddonManager to maintain compatibility
352
-        $this->addon_manager->loadAddons();
353
-    }
354
-
355
-
356
-    /**
357
-     * detect_activations_or_upgrades
358
-     * Checks for activation or upgrade of core first;
359
-     * then also checks if any registered addons have been activated or upgraded
360
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
361
-     * which runs during the WP 'plugins_loaded' action at priority 3
362
-     *
363
-     * @access public
364
-     * @return void
365
-     */
366
-    public function detect_activations_or_upgrades()
367
-    {
368
-        // first off: let's make sure to handle core
369
-        $this->detect_if_activation_or_upgrade();
370
-        foreach ($this->registry->addons as $addon) {
371
-            if ($addon instanceof EE_Addon) {
372
-                // detect teh request type for that addon
373
-                $addon->detect_req_type();
374
-            }
375
-        }
376
-    }
377
-
378
-
379
-    /**
380
-     * detect_if_activation_or_upgrade
381
-     * Takes care of detecting whether this is a brand new install or code upgrade,
382
-     * and either setting up the DB or setting up maintenance mode etc.
383
-     *
384
-     * @access public
385
-     * @return void
386
-     */
387
-    public function detect_if_activation_or_upgrade()
388
-    {
389
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
390
-        // check if db has been updated, or if its a brand-new installation
391
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
392
-        $request_type       = $this->detect_req_type($espresso_db_update);
393
-        // EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
394
-        switch ($request_type) {
395
-            case EE_System::req_type_new_activation:
396
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
397
-                $this->_handle_core_version_change($espresso_db_update);
398
-                break;
399
-            case EE_System::req_type_reactivation:
400
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
401
-                $this->_handle_core_version_change($espresso_db_update);
402
-                break;
403
-            case EE_System::req_type_upgrade:
404
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
405
-                // migrations may be required now that we've upgraded
406
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
407
-                $this->_handle_core_version_change($espresso_db_update);
408
-                break;
409
-            case EE_System::req_type_downgrade:
410
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
411
-                // its possible migrations are no longer required
412
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
413
-                $this->_handle_core_version_change($espresso_db_update);
414
-                break;
415
-            case EE_System::req_type_normal:
416
-            default:
417
-                break;
418
-        }
419
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
420
-    }
421
-
422
-
423
-    /**
424
-     * Updates the list of installed versions and sets hooks for
425
-     * initializing the database later during the request
426
-     *
427
-     * @param array $espresso_db_update
428
-     */
429
-    private function _handle_core_version_change(array $espresso_db_update)
430
-    {
431
-        $this->update_list_of_installed_versions($espresso_db_update);
432
-        // get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
433
-        add_action(
434
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
435
-            [$this, 'initialize_db_if_no_migrations_required']
436
-        );
437
-    }
438
-
439
-
440
-    /**
441
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
442
-     * information about what versions of EE have been installed and activated,
443
-     * NOT necessarily the state of the database
444
-     *
445
-     * @param mixed $espresso_db_update           the value of the WordPress option.
446
-     *                                            If not supplied, fetches it from the options table
447
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
448
-     */
449
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null): array
450
-    {
451
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
452
-        if (! $espresso_db_update) {
453
-            $espresso_db_update = get_option('espresso_db_update');
454
-        }
455
-        // check that option is an array
456
-        if (! is_array($espresso_db_update)) {
457
-            // if option is FALSE, then it never existed
458
-            if ($espresso_db_update === false) {
459
-                // make $espresso_db_update an array and save option with autoload OFF
460
-                $espresso_db_update = [];
461
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
462
-            } else {
463
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
464
-                $espresso_db_update = [$espresso_db_update => []];
465
-                update_option('espresso_db_update', $espresso_db_update);
466
-            }
467
-        } else {
468
-            $corrected_db_update = [];
469
-            // if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
470
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
471
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
472
-                    // the key is an int, and the value IS NOT an array
473
-                    // so it must be numerically-indexed, where values are versions installed...
474
-                    // fix it!
475
-                    $version_string                         = $should_be_array;
476
-                    $corrected_db_update[ $version_string ] = ['unknown-date'];
477
-                } else {
478
-                    // ok it checks out
479
-                    $corrected_db_update[ $should_be_version_string ] = $should_be_array;
480
-                }
481
-            }
482
-            $espresso_db_update = $corrected_db_update;
483
-            update_option('espresso_db_update', $espresso_db_update);
484
-        }
485
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
486
-        return ! empty($espresso_db_update) ? $espresso_db_update : [];
487
-    }
488
-
489
-
490
-    /**
491
-     * Does the traditional work of setting up the plugin's database and adding default data.
492
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
493
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
494
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
495
-     * so that it will be done when migrations are finished
496
-     *
497
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
498
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
499
-     *                                       This is a resource-intensive job
500
-     *                                       so we prefer to only do it when necessary
501
-     * @return void
502
-     * @throws EE_Error
503
-     * @throws ReflectionException
504
-     */
505
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
506
-    {
507
-        $request_type = $this->detect_req_type();
508
-        // only initialize system if we're not in maintenance mode.
509
-        if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
510
-            /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
511
-            $rewrite_rules = $this->loader->getShared(
512
-                'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
513
-            );
514
-            $rewrite_rules->flush();
515
-            if ($verify_schema) {
516
-                EEH_Activation::initialize_db_and_folders();
517
-            }
518
-            EEH_Activation::initialize_db_content();
519
-            EEH_Activation::system_initialization();
520
-            if ($initialize_addons_too) {
521
-                $this->initialize_addons();
522
-            }
523
-        } else {
524
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
525
-        }
526
-        if (
527
-            $request_type === EE_System::req_type_new_activation
528
-            || $request_type === EE_System::req_type_reactivation
529
-            || (
530
-                $request_type === EE_System::req_type_upgrade
531
-                && $this->is_major_version_change()
532
-            )
533
-        ) {
534
-            add_action('AHEE__EE_System__initialize_last', [$this, 'redirect_to_about_ee'], 9);
535
-        }
536
-    }
537
-
538
-
539
-    /**
540
-     * Initializes the db for all registered addons
541
-     *
542
-     * @throws EE_Error
543
-     * @throws ReflectionException
544
-     */
545
-    public function initialize_addons()
546
-    {
547
-        // foreach registered addon, make sure its db is up-to-date too
548
-        foreach ($this->registry->addons as $addon) {
549
-            if ($addon instanceof EE_Addon) {
550
-                $addon->initialize_db_if_no_migrations_required();
551
-            }
552
-        }
553
-    }
554
-
555
-
556
-    /**
557
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
558
-     *
559
-     * @param array  $version_history
560
-     * @param string $current_version_to_add version to be added to the version history
561
-     * @return    boolean success as to whether or not this option was changed
562
-     */
563
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null): bool
564
-    {
565
-        if (! $version_history) {
566
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
567
-        }
568
-        if ($current_version_to_add === null) {
569
-            $current_version_to_add = espresso_version();
570
-        }
571
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
572
-        // re-save
573
-        return update_option('espresso_db_update', $version_history);
574
-    }
575
-
576
-
577
-    /**
578
-     * Detects if the current version indicated in the has existed in the list of
579
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
580
-     *
581
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
582
-     *                                  If not supplied, fetches it from the options table.
583
-     *                                  Also, caches its result so later parts of the code can also know whether
584
-     *                                  there's been an update or not. This way we can add the current version to
585
-     *                                  espresso_db_update, but still know if this is a new install or not
586
-     * @return int one of the constants on EE_System::req_type_
587
-     */
588
-    public function detect_req_type($espresso_db_update = null): int
589
-    {
590
-        if ($this->_req_type === null) {
591
-            $espresso_db_update          = ! empty($espresso_db_update)
592
-                ? $espresso_db_update
593
-                : $this->fix_espresso_db_upgrade_option();
594
-            $this->_req_type             = EE_System::detect_req_type_given_activation_history(
595
-                $espresso_db_update,
596
-                'ee_espresso_activation',
597
-                espresso_version()
598
-            );
599
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
600
-            $this->request->setIsActivation($this->_req_type !== EE_System::req_type_normal);
601
-        }
602
-        return $this->_req_type;
603
-    }
604
-
605
-
606
-    /**
607
-     * Returns whether or not there was a non-micro version change (ie, change in either
608
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
609
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
610
-     *
611
-     * @param $activation_history
612
-     * @return bool
613
-     */
614
-    private function _detect_major_version_change($activation_history): bool
615
-    {
616
-        $previous_version       = EE_System::getMostRecentlyActiveVersion($activation_history);
617
-        $previous_version_parts = explode('.', $previous_version);
618
-        $current_version_parts  = explode('.', espresso_version());
619
-        return isset(
620
-            $previous_version_parts[0],
621
-            $previous_version_parts[1],
622
-            $current_version_parts[0],
623
-            $current_version_parts[1]
624
-        ) && (
625
-            $previous_version_parts[0] !== $current_version_parts[0]
626
-            || $previous_version_parts[1] !== $current_version_parts[1]
627
-        );
628
-    }
629
-
630
-
631
-    /**
632
-     * Returns true if either the major or minor version of EE changed during this request.
633
-     * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
634
-     *
635
-     * @return bool
636
-     */
637
-    public function is_major_version_change(): bool
638
-    {
639
-        return $this->_major_version_change;
640
-    }
641
-
642
-
643
-    /**
644
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
645
-     * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
646
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
647
-     * just activated to (for core that will always be espresso_version())
648
-     *
649
-     * @param array|null $activation_history             the option's value which stores the activation history for
650
-     *                                                 this
651
-     *                                                 ee plugin. for core that's 'espresso_db_update'
652
-     * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
653
-     *                                                 indicate that this plugin was just activated
654
-     * @param string $current_version                  the version that was just upgraded to (for core that will be
655
-     *                                                 espresso_version())
656
-     * @return int one of the constants on EE_System::req_type_
657
-     */
658
-    public static function detect_req_type_given_activation_history(
659
-        array $activation_history,
660
-        string $activation_indicator_option_name,
661
-        string $current_version
662
-    ): int {
663
-        $version_change = self::compareVersionWithPrevious($activation_history, $current_version);
664
-        $is_activation  = get_option($activation_indicator_option_name, false);
665
-        $req_type       = self::getRequestType($activation_history, $version_change, $is_activation);
666
-        if ($is_activation) {
667
-            // cleanup in aisle 6
668
-            delete_option($activation_indicator_option_name);
669
-        }
670
-        return $req_type;
671
-    }
672
-
673
-
674
-    /**
675
-     * @param array  $activation_history
676
-     * @param int    $version_change
677
-     * @param bool   $is_activation
678
-     * @return int
679
-     * @since $VID:$
680
-     */
681
-    private static function getRequestType(array $activation_history, int $version_change, bool $is_activation): int
682
-    {
683
-        // if no previous activation history exists, then this is a brand new install
684
-        if (empty($activation_history)) {
685
-            return EE_System::req_type_new_activation;
686
-        }
687
-        // current version is higher than previous version, so it's an upgrade
688
-        if ($version_change === 1) {
689
-            return EE_System::req_type_upgrade;
690
-        }
691
-        // current version is lower than previous version, so it's a downgrade
692
-        if ($version_change === -1) {
693
-            return EE_System::req_type_downgrade;
694
-        }
695
-        // version hasn't changed since last version so check if the activation indicator is set
696
-        // to determine if it's a reactivation, or just a normal request
697
-        return $is_activation
698
-            ? EE_System::req_type_reactivation
699
-            : EE_System::req_type_normal;
700
-    }
701
-
702
-
703
-    /**
704
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
705
-     * the $activation_history_for_addon
706
-     *
707
-     * @param array  $activation_history    array where keys are versions,
708
-     *                                      values are arrays of times activated (sometimes 'unknown-date')
709
-     * @param string $current_version
710
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
711
-     *                                      -1 if $version_to_upgrade_to is LOWER (downgrade);
712
-     *                                      0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
713
-     *                                      1 if $version_to_upgrade_to is HIGHER (upgrade) ;
714
-     */
715
-    private static function compareVersionWithPrevious(array $activation_history, string $current_version): int
716
-    {
717
-        // find the most recently-activated version
718
-        $most_recently_active_version = EE_System::getMostRecentlyActiveVersion($activation_history);
719
-        return version_compare($current_version, $most_recently_active_version);
720
-    }
721
-
722
-
723
-    /**
724
-     * Gets the most recently active version listed in the activation history,
725
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
726
-     *
727
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
728
-     *                                   sometimes containing 'unknown-date'
729
-     * @return string
730
-     */
731
-    private static function getMostRecentlyActiveVersion(array $activation_history): string
732
-    {
733
-        $most_recent_activation_date  = '1970-01-01 00:00:00';
734
-        $most_recently_active_version = '0.0.0.dev.000';
735
-        if (is_array($activation_history)) {
736
-            foreach ($activation_history as $version => $activation_dates) {
737
-                // check there is a record of when this version was activated.
738
-                // Otherwise, mark it as unknown
739
-                if (! $activation_dates) {
740
-                    $activation_dates = ['unknown-date'];
741
-                }
742
-                $activation_dates = is_string($activation_dates) ? [$activation_dates] : $activation_dates;
743
-                foreach ($activation_dates as $activation_date) {
744
-                    if ($activation_date !== 'unknown-date' && $activation_date > $most_recent_activation_date) {
745
-                        $most_recently_active_version = $version;
746
-                        $most_recent_activation_date  = $activation_date;
747
-                    }
748
-                }
749
-            }
750
-        }
751
-        return $most_recently_active_version;
752
-    }
753
-
754
-
755
-    /**
756
-     * This redirects to the about EE page after activation
757
-     *
758
-     * @return void
759
-     */
760
-    public function redirect_to_about_ee()
761
-    {
762
-        $notices = EE_Error::get_notices(false);
763
-        // if current user is an admin and it's not an ajax or rest request
764
-        if (
765
-            ! isset($notices['errors'])
766
-            && $this->request->isAdmin()
767
-            && apply_filters(
768
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
769
-                $this->capabilities->current_user_can('manage_options', 'espresso_about_default')
770
-            )
771
-        ) {
772
-            $query_params = ['page' => 'espresso_about'];
773
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
774
-                $query_params['new_activation'] = true;
775
-            }
776
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
777
-                $query_params['reactivation'] = true;
778
-            }
779
-            $url = add_query_arg($query_params, admin_url('admin.php'));
780
-            EEH_URL::safeRedirectAndExit($url);
781
-        }
782
-    }
783
-
784
-
785
-    /**
786
-     * load_core_configuration
787
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
788
-     * which runs during the WP 'plugins_loaded' action at priority 5
789
-     *
790
-     * @return void
791
-     * @throws ReflectionException
792
-     * @throws Exception
793
-     */
794
-    public function load_core_configuration()
795
-    {
796
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
797
-        $this->loader->getShared('EE_Load_Textdomain');
798
-        // load textdomain
799
-        EE_Load_Textdomain::load_textdomain();
800
-        // load caf stuff a chance to play during the activation process too.
801
-        $this->_maybe_brew_regular();
802
-        // load and setup EE_Config and EE_Network_Config
803
-        $config = $this->loader->getShared('EE_Config');
804
-        $this->loader->getShared('EE_Network_Config');
805
-        // setup autoloaders
806
-        // enable logging?
807
-        if ($config->admin->use_remote_logging) {
808
-            $this->loader->getShared('EE_Log');
809
-        }
810
-        // check for activation errors
811
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
812
-        if ($activation_errors) {
813
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
814
-            update_option('ee_plugin_activation_errors', false);
815
-        }
816
-        // get model names
817
-        $this->_parse_model_names();
818
-        // configure custom post type definitions
819
-        $this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions');
820
-        $this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions');
821
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
822
-    }
823
-
824
-
825
-    /**
826
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
827
-     *
828
-     * @return void
829
-     * @throws ReflectionException
830
-     */
831
-    private function _parse_model_names()
832
-    {
833
-        // get all the files in the EE_MODELS folder that end in .model.php
834
-        $models                 = glob(EE_MODELS . '*.model.php');
835
-        $model_names            = [];
836
-        $non_abstract_db_models = [];
837
-        foreach ($models as $model) {
838
-            // get model classname
839
-            $classname       = EEH_File::get_classname_from_filepath_with_standard_filename($model);
840
-            $short_name      = str_replace('EEM_', '', $classname);
841
-            $reflectionClass = new ReflectionClass($classname);
842
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
843
-                $non_abstract_db_models[ $short_name ] = $classname;
844
-            }
845
-            $model_names[ $short_name ] = $classname;
846
-        }
847
-        $this->registry->models                 = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
848
-        $this->registry->non_abstract_db_models = apply_filters(
849
-            'FHEE__EE_System__parse_implemented_model_names',
850
-            $non_abstract_db_models
851
-        );
852
-    }
853
-
854
-
855
-    /**
856
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
857
-     * that need to be setup before our EE_System launches.
858
-     *
859
-     * @return void
860
-     * @throws DomainException
861
-     * @throws InvalidArgumentException
862
-     * @throws InvalidDataTypeException
863
-     * @throws InvalidInterfaceException
864
-     * @throws InvalidClassException
865
-     * @throws InvalidFilePathException
866
-     */
867
-    private function _maybe_brew_regular()
868
-    {
869
-        /** @var Domain $domain */
870
-        $domain = DomainFactory::getEventEspressoCoreDomain();
871
-        if ($domain->isCaffeinated()) {
872
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
873
-        }
874
-    }
875
-
876
-
877
-    /**
878
-     * @throws Exception
879
-     * @since 4.9.71.p
880
-     */
881
-    public function loadRouteMatchSpecifications()
882
-    {
883
-        try {
884
-            $this->loader->getShared('EventEspresso\core\services\routing\RouteMatchSpecificationManager');
885
-            $this->loader->getShared('EventEspresso\core\services\routing\RouteCollection');
886
-            $this->router->loadPrimaryRoutes();
887
-        } catch (Exception $exception) {
888
-            new ExceptionStackTraceDisplay($exception);
889
-        }
890
-        do_action('AHEE__EE_System__loadRouteMatchSpecifications');
891
-    }
892
-
893
-
894
-    /**
895
-     * loading CPT related classes earlier so that their definitions are available
896
-     * but not performing any actual registration with WP core until load_CPTs_and_session() is called
897
-     *
898
-     * @since   4.10.21.p
899
-     */
900
-    public function loadCustomPostTypes()
901
-    {
902
-        $this->register_custom_taxonomies = $this->loader->getShared(
903
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'
904
-        );
905
-        $this->register_custom_post_types = $this->loader->getShared(
906
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'
907
-        );
908
-        $this->register_custom_taxonomy_terms = $this->loader->getShared(
909
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms'
910
-        );
911
-        // integrate WP_Query with the EE models
912
-        $this->loader->getShared('EE_CPT_Strategy');
913
-        // load legacy EE_Request_Handler in case add-ons still need it
914
-        $this->loader->getShared('EE_Request_Handler');
915
-    }
916
-
917
-
918
-    /**
919
-     * register_shortcodes_modules_and_widgets
920
-     * generate lists of shortcodes and modules, then verify paths and classes
921
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
922
-     * which runs during the WP 'plugins_loaded' action at priority 7
923
-     *
924
-     * @access public
925
-     * @return void
926
-     * @throws Exception
927
-     */
928
-    public function register_shortcodes_modules_and_widgets()
929
-    {
930
-        $this->router->registerShortcodesModulesAndWidgets();
931
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
932
-        // check for addons using old hook point
933
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
934
-            $this->_incompatible_addon_error();
935
-        }
936
-    }
937
-
938
-
939
-    /**
940
-     * _incompatible_addon_error
941
-     *
942
-     * @access public
943
-     * @return void
944
-     */
945
-    private function _incompatible_addon_error()
946
-    {
947
-        // get array of classes hooking into here
948
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
949
-            'AHEE__EE_System__register_shortcodes_modules_and_addons'
950
-        );
951
-        if (! empty($class_names)) {
952
-            $msg = esc_html__(
953
-                'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
954
-                'event_espresso'
955
-            );
956
-            $msg .= '<ul>';
957
-            foreach ($class_names as $class_name) {
958
-                $msg .= '<li><b>Event Espresso - '
959
-                        . str_replace(
960
-                            ['EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'],
961
-                            '',
962
-                            $class_name
963
-                        ) . '</b></li>';
964
-            }
965
-            $msg .= '</ul>';
966
-            $msg .= esc_html__(
967
-                'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
968
-                'event_espresso'
969
-            );
970
-            // save list of incompatible addons to wp-options for later use
971
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
972
-            if (is_admin()) {
973
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
974
-            }
975
-        }
976
-    }
977
-
978
-
979
-    /**
980
-     * brew_espresso
981
-     * begins the process of setting hooks for initializing EE in the correct order
982
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
983
-     * which runs during the WP 'plugins_loaded' action at priority 9
984
-     *
985
-     * @return void
986
-     * @throws Exception
987
-     */
988
-    public function brew_espresso()
989
-    {
990
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
991
-        // load some final core systems
992
-        add_action('init', [$this, 'set_hooks_for_core'], 1);
993
-        add_action('init', [$this, 'perform_activations_upgrades_and_migrations'], 3);
994
-        add_action('init', [$this, 'load_CPTs_and_session'], 5);
995
-        add_action('init', [$this, 'load_controllers'], 7);
996
-        add_action('init', [$this, 'core_loaded_and_ready'], 9);
997
-        add_action('init', [$this, 'initialize'], 10);
998
-        add_action('init', [$this, 'initialize_last'], 100);
999
-        $this->router->brewEspresso();
1000
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
1001
-    }
1002
-
1003
-
1004
-    /**
1005
-     *    set_hooks_for_core
1006
-     *
1007
-     * @access public
1008
-     * @return    void
1009
-     * @throws EE_Error
1010
-     */
1011
-    public function set_hooks_for_core()
1012
-    {
1013
-        $this->_deactivate_incompatible_addons();
1014
-        do_action('AHEE__EE_System__set_hooks_for_core');
1015
-        $this->loader->getShared('EventEspresso\core\domain\values\session\SessionLifespan');
1016
-        // caps need to be initialized on every request so that capability maps are set.
1017
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1018
-        $this->registry->CAP->init_caps();
1019
-    }
1020
-
1021
-
1022
-    /**
1023
-     * Using the information gathered in EE_System::_incompatible_addon_error,
1024
-     * deactivates any addons considered incompatible with the current version of EE
1025
-     */
1026
-    private function _deactivate_incompatible_addons()
1027
-    {
1028
-        $incompatible_addons = get_option('ee_incompatible_addons', []);
1029
-        if (! empty($incompatible_addons)) {
1030
-            $active_plugins = get_option('active_plugins', []);
1031
-            foreach ($active_plugins as $active_plugin) {
1032
-                foreach ($incompatible_addons as $incompatible_addon) {
1033
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
1034
-                        $this->request->unSetRequestParams(['activate'], true);
1035
-                        espresso_deactivate_plugin($active_plugin);
1036
-                    }
1037
-                }
1038
-            }
1039
-        }
1040
-    }
1041
-
1042
-
1043
-    /**
1044
-     *    perform_activations_upgrades_and_migrations
1045
-     *
1046
-     * @access public
1047
-     * @return    void
1048
-     */
1049
-    public function perform_activations_upgrades_and_migrations()
1050
-    {
1051
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1052
-    }
1053
-
1054
-
1055
-    /**
1056
-     * @return void
1057
-     * @throws DomainException
1058
-     */
1059
-    public function load_CPTs_and_session()
1060
-    {
1061
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
1062
-        $this->register_custom_taxonomies->registerCustomTaxonomies();
1063
-        $this->register_custom_post_types->registerCustomPostTypes();
1064
-        $this->register_custom_taxonomy_terms->registerCustomTaxonomyTerms();
1065
-        // load legacy Custom Post Types and Taxonomies
1066
-        $this->loader->getShared('EE_Register_CPTs');
1067
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1068
-    }
1069
-
1070
-
1071
-    /**
1072
-     * load_controllers
1073
-     * this is the best place to load any additional controllers that needs access to EE core.
1074
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1075
-     * time
1076
-     *
1077
-     * @access public
1078
-     * @return void
1079
-     * @throws Exception
1080
-     */
1081
-    public function load_controllers()
1082
-    {
1083
-        do_action('AHEE__EE_System__load_controllers__start');
1084
-        $this->router->loadControllers();
1085
-        do_action('AHEE__EE_System__load_controllers__complete');
1086
-    }
1087
-
1088
-
1089
-    /**
1090
-     * core_loaded_and_ready
1091
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1092
-     *
1093
-     * @access public
1094
-     * @return void
1095
-     * @throws Exception
1096
-     */
1097
-    public function core_loaded_and_ready()
1098
-    {
1099
-        $this->router->coreLoadedAndReady();
1100
-        do_action('AHEE__EE_System__core_loaded_and_ready');
1101
-        // always load template tags, because it's faster than checking if it's a front-end request, and many page
1102
-        // builders require these even on the front-end
1103
-        require_once EE_PUBLIC . 'template_tags.php';
1104
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1105
-    }
1106
-
1107
-
1108
-    /**
1109
-     * initialize
1110
-     * this is the best place to begin initializing client code
1111
-     *
1112
-     * @access public
1113
-     * @return void
1114
-     */
1115
-    public function initialize()
1116
-    {
1117
-        do_action('AHEE__EE_System__initialize');
1118
-        add_filter(
1119
-            'safe_style_css',
1120
-            function ($styles) {
1121
-                $styles[] = 'display';
1122
-                $styles[] = 'visibility';
1123
-                $styles[] = 'position';
1124
-                $styles[] = 'top';
1125
-                $styles[] = 'right';
1126
-                $styles[] = 'bottom';
1127
-                $styles[] = 'left';
1128
-                $styles[] = 'resize';
1129
-                $styles[] = 'max-width';
1130
-                $styles[] = 'max-height';
1131
-                return $styles;
1132
-            }
1133
-        );
1134
-    }
1135
-
1136
-
1137
-    /**
1138
-     * initialize_last
1139
-     * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1140
-     * initialize has done so
1141
-     *
1142
-     * @access public
1143
-     * @return void
1144
-     * @throws Exception
1145
-     */
1146
-    public function initialize_last()
1147
-    {
1148
-        $this->router->initializeLast();
1149
-        do_action('AHEE__EE_System__initialize_last');
1150
-        /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
1151
-        $rewrite_rules = $this->loader->getShared(
1152
-            'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
1153
-        );
1154
-        $rewrite_rules->flushRewriteRules();
1155
-        add_action('admin_bar_init', [$this, 'addEspressoToolbar']);
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     * @return void
1161
-     */
1162
-    public function addEspressoToolbar()
1163
-    {
1164
-        $this->loader->getShared(
1165
-            'EventEspresso\core\domain\services\admin\AdminToolBar',
1166
-            [$this->registry->CAP]
1167
-        );
1168
-    }
1169
-
1170
-
1171
-    /**
1172
-     * do_not_cache
1173
-     * sets no cache headers and defines no cache constants for WP plugins
1174
-     *
1175
-     * @access public
1176
-     * @return void
1177
-     */
1178
-    public static function do_not_cache()
1179
-    {
1180
-        // set no cache constants
1181
-        if (! defined('DONOTCACHEPAGE')) {
1182
-            define('DONOTCACHEPAGE', true);
1183
-        }
1184
-        if (! defined('DONOTCACHCEOBJECT')) {
1185
-            define('DONOTCACHCEOBJECT', true);
1186
-        }
1187
-        if (! defined('DONOTCACHEDB')) {
1188
-            define('DONOTCACHEDB', true);
1189
-        }
1190
-        // add no cache headers
1191
-        add_action('send_headers', ['EE_System', 'nocache_headers'], 10);
1192
-        // plus a little extra for nginx and Google Chrome
1193
-        add_filter('nocache_headers', ['EE_System', 'extra_nocache_headers'], 10, 1);
1194
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1195
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1196
-    }
1197
-
1198
-
1199
-    /**
1200
-     *    extra_nocache_headers
1201
-     *
1202
-     * @access    public
1203
-     * @param $headers
1204
-     * @return    array
1205
-     */
1206
-    public static function extra_nocache_headers($headers): array
1207
-    {
1208
-        // for NGINX
1209
-        $headers['X-Accel-Expires'] = 0;
1210
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1211
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1212
-        return $headers;
1213
-    }
1214
-
1215
-
1216
-    /**
1217
-     *    nocache_headers
1218
-     *
1219
-     * @access    public
1220
-     * @return    void
1221
-     */
1222
-    public static function nocache_headers()
1223
-    {
1224
-        nocache_headers();
1225
-    }
1226
-
1227
-
1228
-    /**
1229
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1230
-     * never returned with the function.
1231
-     *
1232
-     * @param array $exclude_array any existing pages being excluded are in this array.
1233
-     * @return array
1234
-     */
1235
-    public function remove_pages_from_wp_list_pages(array $exclude_array): array
1236
-    {
1237
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1238
-    }
27
+	/**
28
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
29
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
30
+	 */
31
+	const req_type_normal = 0;
32
+
33
+	/**
34
+	 * Indicates this is a brand new installation of EE so we should install
35
+	 * tables and default data etc
36
+	 */
37
+	const req_type_new_activation = 1;
38
+
39
+	/**
40
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
41
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
42
+	 * and that default data is setup too
43
+	 */
44
+	const req_type_reactivation = 2;
45
+
46
+	/**
47
+	 * indicates that EE has been upgraded since its previous request.
48
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
49
+	 */
50
+	const req_type_upgrade = 3;
51
+
52
+	/**
53
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
54
+	 */
55
+	const req_type_downgrade = 4;
56
+
57
+	/**
58
+	 * @deprecated since version 4.6.0.dev.006
59
+	 * Now whenever a new_activation is detected the request type is still just
60
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we're in maintenance mode
61
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
62
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
63
+	 * (Specifically, when the migration manager indicates migrations are finished
64
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
65
+	 */
66
+	const req_type_activation_but_not_installed = 5;
67
+
68
+	/**
69
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
70
+	 */
71
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
72
+
73
+	/**
74
+	 * @var AddonManager $addon_manager
75
+	 */
76
+	private $addon_manager;
77
+
78
+	/**
79
+	 * @var EE_System $_instance
80
+	 */
81
+	private static $_instance;
82
+
83
+	/**
84
+	 * @var EE_Registry $registry
85
+	 */
86
+	private $registry;
87
+
88
+	/**
89
+	 * @var LoaderInterface $loader
90
+	 */
91
+	private $loader;
92
+
93
+	/**
94
+	 * @var EE_Capabilities $capabilities
95
+	 */
96
+	private $capabilities;
97
+
98
+	/**
99
+	 * @var EE_Maintenance_Mode $maintenance_mode
100
+	 */
101
+	private $maintenance_mode;
102
+
103
+	/**
104
+	 * @var RequestInterface $request
105
+	 */
106
+	private $request;
107
+
108
+	/**
109
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
110
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
111
+	 *
112
+	 * @var int $_req_type
113
+	 */
114
+	private $_req_type;
115
+
116
+	/**
117
+	 * Whether or not there was a non-micro version change in EE core version during this request
118
+	 *
119
+	 * @var boolean $_major_version_change
120
+	 */
121
+	private $_major_version_change = false;
122
+
123
+	/**
124
+	 * @var Router $router
125
+	 */
126
+	private $router;
127
+
128
+	/**
129
+	 * @param EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes
130
+	 */
131
+	private $register_custom_post_types;
132
+
133
+	/**
134
+	 * @param EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies
135
+	 */
136
+	private $register_custom_taxonomies;
137
+
138
+	/**
139
+	 * @param EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms
140
+	 */
141
+	private $register_custom_taxonomy_terms;
142
+
143
+	/**
144
+	 * @singleton method used to instantiate class object
145
+	 * @param LoaderInterface|null     $loader
146
+	 * @param EE_Maintenance_Mode|null $maintenance_mode
147
+	 * @param EE_Registry|null         $registry
148
+	 * @param RequestInterface|null    $request
149
+	 * @param Router|null              $router
150
+	 * @return EE_System
151
+	 */
152
+	public static function instance(
153
+		LoaderInterface $loader = null,
154
+		EE_Maintenance_Mode $maintenance_mode = null,
155
+		EE_Registry $registry = null,
156
+		RequestInterface $request = null,
157
+		Router $router = null
158
+	): EE_System {
159
+		// check if class object is instantiated
160
+		if (! self::$_instance instanceof EE_System) {
161
+			self::$_instance = new self($loader, $maintenance_mode, $registry, $request, $router);
162
+		}
163
+		return self::$_instance;
164
+	}
165
+
166
+
167
+	/**
168
+	 * resets the instance and returns it
169
+	 *
170
+	 * @return EE_System
171
+	 */
172
+	public static function reset(): EE_System
173
+	{
174
+		self::$_instance->_req_type = null;
175
+		// make sure none of the old hooks are left hanging around
176
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
177
+		// we need to reset the migration manager in order for it to detect DMSs properly
178
+		EE_Data_Migration_Manager::reset();
179
+		self::instance()->detect_activations_or_upgrades();
180
+		self::instance()->perform_activations_upgrades_and_migrations();
181
+		return self::instance();
182
+	}
183
+
184
+
185
+	/**
186
+	 * sets hooks for running rest of system
187
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
188
+	 * starting EE Addons from any other point may lead to problems
189
+	 *
190
+	 * @param LoaderInterface     $loader
191
+	 * @param EE_Maintenance_Mode $maintenance_mode
192
+	 * @param EE_Registry         $registry
193
+	 * @param RequestInterface    $request
194
+	 * @param Router              $router
195
+	 */
196
+	private function __construct(
197
+		LoaderInterface $loader,
198
+		EE_Maintenance_Mode $maintenance_mode,
199
+		EE_Registry $registry,
200
+		RequestInterface $request,
201
+		Router $router
202
+	) {
203
+		$this->registry         = $registry;
204
+		$this->loader           = $loader;
205
+		$this->request          = $request;
206
+		$this->router           = $router;
207
+		$this->maintenance_mode = $maintenance_mode;
208
+		do_action('AHEE__EE_System__construct__begin', $this);
209
+		add_action(
210
+			'AHEE__EE_Bootstrap__load_espresso_addons',
211
+			[$this, 'loadCapabilities'],
212
+			5
213
+		);
214
+		add_action(
215
+			'AHEE__EE_Bootstrap__load_espresso_addons',
216
+			[$this, 'loadCommandBus'],
217
+			7
218
+		);
219
+		add_action(
220
+			'AHEE__EE_Bootstrap__load_espresso_addons',
221
+			[$this, 'loadPluginApi'],
222
+			9
223
+		);
224
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
225
+		add_action(
226
+			'AHEE__EE_Bootstrap__load_espresso_addons',
227
+			[$this, 'load_espresso_addons']
228
+		);
229
+		// when an ee addon is activated, we want to call the core hook(s) again
230
+		// because the newly-activated addon didn't get a chance to run at all
231
+		add_action('activate_plugin', [$this, 'load_espresso_addons'], 1);
232
+		// detect whether install or upgrade
233
+		add_action(
234
+			'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
235
+			[$this, 'detect_activations_or_upgrades'],
236
+			3
237
+		);
238
+		// load EE_Config, EE_Textdomain, etc
239
+		add_action(
240
+			'AHEE__EE_Bootstrap__load_core_configuration',
241
+			[$this, 'load_core_configuration'],
242
+			5
243
+		);
244
+		// load specifications for matching routes to current request
245
+		add_action(
246
+			'AHEE__EE_Bootstrap__load_core_configuration',
247
+			[$this, 'loadRouteMatchSpecifications']
248
+		);
249
+		// load specifications for custom post types
250
+		add_action(
251
+			'AHEE__EE_Bootstrap__load_core_configuration',
252
+			array($this, 'loadCustomPostTypes')
253
+		);
254
+		// load specifications for custom post types
255
+		add_action(
256
+			'AHEE__EE_Bootstrap__load_core_configuration',
257
+			array($this, 'loadCustomPostTypes')
258
+		);
259
+		// load EE_Config, EE_Textdomain, etc
260
+		add_action(
261
+			'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
262
+			[$this, 'register_shortcodes_modules_and_widgets'],
263
+			7
264
+		);
265
+		// you wanna get going? I wanna get going... let's get going!
266
+		add_action(
267
+			'AHEE__EE_Bootstrap__brew_espresso',
268
+			[$this, 'brew_espresso'],
269
+			9
270
+		);
271
+		// other housekeeping
272
+		// exclude EE critical pages from wp_list_pages
273
+		add_filter(
274
+			'wp_list_pages_excludes',
275
+			[$this, 'remove_pages_from_wp_list_pages'],
276
+			10
277
+		);
278
+		// ALL EE Addons should use the following hook point to attach their initial setup too
279
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
280
+		do_action('AHEE__EE_System__construct__complete', $this);
281
+	}
282
+
283
+
284
+	/**
285
+	 * load and setup EE_Capabilities
286
+	 *
287
+	 * @return void
288
+	 */
289
+	public function loadCapabilities()
290
+	{
291
+		$this->capabilities = $this->loader->getShared('EE_Capabilities');
292
+		add_action(
293
+			'AHEE__EE_Capabilities__init_caps__before_initialization',
294
+			function () {
295
+				LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
296
+			}
297
+		);
298
+	}
299
+
300
+
301
+	/**
302
+	 * create and cache the CommandBus, and also add middleware
303
+	 * The CapChecker middleware requires the use of EE_Capabilities
304
+	 * which is why we need to load the CommandBus after Caps are set up
305
+	 *
306
+	 * @return void
307
+	 */
308
+	public function loadCommandBus()
309
+	{
310
+		$this->loader->getShared(
311
+			'CommandBusInterface',
312
+			[
313
+				null,
314
+				apply_filters(
315
+					'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
316
+					[
317
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
318
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
319
+					]
320
+				),
321
+			]
322
+		);
323
+	}
324
+
325
+
326
+	/**
327
+	 * @return void
328
+	 * @throws Exception
329
+	 */
330
+	public function loadPluginApi()
331
+	{
332
+		$this->addon_manager = $this->loader->getShared(AddonManager::class);
333
+		$this->addon_manager->initialize();
334
+		$this->loader->getShared('EE_Request_Handler');
335
+	}
336
+
337
+
338
+	/**
339
+	 * load_espresso_addons
340
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
341
+	 * this is hooked into both:
342
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
343
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
344
+	 *    and the WP 'activate_plugin' hook point
345
+	 *
346
+	 * @return void
347
+	 * @throws Exception
348
+	 */
349
+	public function load_espresso_addons()
350
+	{
351
+		// looking for hooks? they've been moved into the AddonManager to maintain compatibility
352
+		$this->addon_manager->loadAddons();
353
+	}
354
+
355
+
356
+	/**
357
+	 * detect_activations_or_upgrades
358
+	 * Checks for activation or upgrade of core first;
359
+	 * then also checks if any registered addons have been activated or upgraded
360
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
361
+	 * which runs during the WP 'plugins_loaded' action at priority 3
362
+	 *
363
+	 * @access public
364
+	 * @return void
365
+	 */
366
+	public function detect_activations_or_upgrades()
367
+	{
368
+		// first off: let's make sure to handle core
369
+		$this->detect_if_activation_or_upgrade();
370
+		foreach ($this->registry->addons as $addon) {
371
+			if ($addon instanceof EE_Addon) {
372
+				// detect teh request type for that addon
373
+				$addon->detect_req_type();
374
+			}
375
+		}
376
+	}
377
+
378
+
379
+	/**
380
+	 * detect_if_activation_or_upgrade
381
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
382
+	 * and either setting up the DB or setting up maintenance mode etc.
383
+	 *
384
+	 * @access public
385
+	 * @return void
386
+	 */
387
+	public function detect_if_activation_or_upgrade()
388
+	{
389
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
390
+		// check if db has been updated, or if its a brand-new installation
391
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
392
+		$request_type       = $this->detect_req_type($espresso_db_update);
393
+		// EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
394
+		switch ($request_type) {
395
+			case EE_System::req_type_new_activation:
396
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
397
+				$this->_handle_core_version_change($espresso_db_update);
398
+				break;
399
+			case EE_System::req_type_reactivation:
400
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
401
+				$this->_handle_core_version_change($espresso_db_update);
402
+				break;
403
+			case EE_System::req_type_upgrade:
404
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
405
+				// migrations may be required now that we've upgraded
406
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
407
+				$this->_handle_core_version_change($espresso_db_update);
408
+				break;
409
+			case EE_System::req_type_downgrade:
410
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
411
+				// its possible migrations are no longer required
412
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
413
+				$this->_handle_core_version_change($espresso_db_update);
414
+				break;
415
+			case EE_System::req_type_normal:
416
+			default:
417
+				break;
418
+		}
419
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
420
+	}
421
+
422
+
423
+	/**
424
+	 * Updates the list of installed versions and sets hooks for
425
+	 * initializing the database later during the request
426
+	 *
427
+	 * @param array $espresso_db_update
428
+	 */
429
+	private function _handle_core_version_change(array $espresso_db_update)
430
+	{
431
+		$this->update_list_of_installed_versions($espresso_db_update);
432
+		// get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
433
+		add_action(
434
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
435
+			[$this, 'initialize_db_if_no_migrations_required']
436
+		);
437
+	}
438
+
439
+
440
+	/**
441
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
442
+	 * information about what versions of EE have been installed and activated,
443
+	 * NOT necessarily the state of the database
444
+	 *
445
+	 * @param mixed $espresso_db_update           the value of the WordPress option.
446
+	 *                                            If not supplied, fetches it from the options table
447
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
448
+	 */
449
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null): array
450
+	{
451
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
452
+		if (! $espresso_db_update) {
453
+			$espresso_db_update = get_option('espresso_db_update');
454
+		}
455
+		// check that option is an array
456
+		if (! is_array($espresso_db_update)) {
457
+			// if option is FALSE, then it never existed
458
+			if ($espresso_db_update === false) {
459
+				// make $espresso_db_update an array and save option with autoload OFF
460
+				$espresso_db_update = [];
461
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
462
+			} else {
463
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
464
+				$espresso_db_update = [$espresso_db_update => []];
465
+				update_option('espresso_db_update', $espresso_db_update);
466
+			}
467
+		} else {
468
+			$corrected_db_update = [];
469
+			// if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
470
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
471
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
472
+					// the key is an int, and the value IS NOT an array
473
+					// so it must be numerically-indexed, where values are versions installed...
474
+					// fix it!
475
+					$version_string                         = $should_be_array;
476
+					$corrected_db_update[ $version_string ] = ['unknown-date'];
477
+				} else {
478
+					// ok it checks out
479
+					$corrected_db_update[ $should_be_version_string ] = $should_be_array;
480
+				}
481
+			}
482
+			$espresso_db_update = $corrected_db_update;
483
+			update_option('espresso_db_update', $espresso_db_update);
484
+		}
485
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
486
+		return ! empty($espresso_db_update) ? $espresso_db_update : [];
487
+	}
488
+
489
+
490
+	/**
491
+	 * Does the traditional work of setting up the plugin's database and adding default data.
492
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
493
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
494
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
495
+	 * so that it will be done when migrations are finished
496
+	 *
497
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
498
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
499
+	 *                                       This is a resource-intensive job
500
+	 *                                       so we prefer to only do it when necessary
501
+	 * @return void
502
+	 * @throws EE_Error
503
+	 * @throws ReflectionException
504
+	 */
505
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
506
+	{
507
+		$request_type = $this->detect_req_type();
508
+		// only initialize system if we're not in maintenance mode.
509
+		if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
510
+			/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
511
+			$rewrite_rules = $this->loader->getShared(
512
+				'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
513
+			);
514
+			$rewrite_rules->flush();
515
+			if ($verify_schema) {
516
+				EEH_Activation::initialize_db_and_folders();
517
+			}
518
+			EEH_Activation::initialize_db_content();
519
+			EEH_Activation::system_initialization();
520
+			if ($initialize_addons_too) {
521
+				$this->initialize_addons();
522
+			}
523
+		} else {
524
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
525
+		}
526
+		if (
527
+			$request_type === EE_System::req_type_new_activation
528
+			|| $request_type === EE_System::req_type_reactivation
529
+			|| (
530
+				$request_type === EE_System::req_type_upgrade
531
+				&& $this->is_major_version_change()
532
+			)
533
+		) {
534
+			add_action('AHEE__EE_System__initialize_last', [$this, 'redirect_to_about_ee'], 9);
535
+		}
536
+	}
537
+
538
+
539
+	/**
540
+	 * Initializes the db for all registered addons
541
+	 *
542
+	 * @throws EE_Error
543
+	 * @throws ReflectionException
544
+	 */
545
+	public function initialize_addons()
546
+	{
547
+		// foreach registered addon, make sure its db is up-to-date too
548
+		foreach ($this->registry->addons as $addon) {
549
+			if ($addon instanceof EE_Addon) {
550
+				$addon->initialize_db_if_no_migrations_required();
551
+			}
552
+		}
553
+	}
554
+
555
+
556
+	/**
557
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
558
+	 *
559
+	 * @param array  $version_history
560
+	 * @param string $current_version_to_add version to be added to the version history
561
+	 * @return    boolean success as to whether or not this option was changed
562
+	 */
563
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null): bool
564
+	{
565
+		if (! $version_history) {
566
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
567
+		}
568
+		if ($current_version_to_add === null) {
569
+			$current_version_to_add = espresso_version();
570
+		}
571
+		$version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
572
+		// re-save
573
+		return update_option('espresso_db_update', $version_history);
574
+	}
575
+
576
+
577
+	/**
578
+	 * Detects if the current version indicated in the has existed in the list of
579
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
580
+	 *
581
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
582
+	 *                                  If not supplied, fetches it from the options table.
583
+	 *                                  Also, caches its result so later parts of the code can also know whether
584
+	 *                                  there's been an update or not. This way we can add the current version to
585
+	 *                                  espresso_db_update, but still know if this is a new install or not
586
+	 * @return int one of the constants on EE_System::req_type_
587
+	 */
588
+	public function detect_req_type($espresso_db_update = null): int
589
+	{
590
+		if ($this->_req_type === null) {
591
+			$espresso_db_update          = ! empty($espresso_db_update)
592
+				? $espresso_db_update
593
+				: $this->fix_espresso_db_upgrade_option();
594
+			$this->_req_type             = EE_System::detect_req_type_given_activation_history(
595
+				$espresso_db_update,
596
+				'ee_espresso_activation',
597
+				espresso_version()
598
+			);
599
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
600
+			$this->request->setIsActivation($this->_req_type !== EE_System::req_type_normal);
601
+		}
602
+		return $this->_req_type;
603
+	}
604
+
605
+
606
+	/**
607
+	 * Returns whether or not there was a non-micro version change (ie, change in either
608
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
609
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
610
+	 *
611
+	 * @param $activation_history
612
+	 * @return bool
613
+	 */
614
+	private function _detect_major_version_change($activation_history): bool
615
+	{
616
+		$previous_version       = EE_System::getMostRecentlyActiveVersion($activation_history);
617
+		$previous_version_parts = explode('.', $previous_version);
618
+		$current_version_parts  = explode('.', espresso_version());
619
+		return isset(
620
+			$previous_version_parts[0],
621
+			$previous_version_parts[1],
622
+			$current_version_parts[0],
623
+			$current_version_parts[1]
624
+		) && (
625
+			$previous_version_parts[0] !== $current_version_parts[0]
626
+			|| $previous_version_parts[1] !== $current_version_parts[1]
627
+		);
628
+	}
629
+
630
+
631
+	/**
632
+	 * Returns true if either the major or minor version of EE changed during this request.
633
+	 * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
634
+	 *
635
+	 * @return bool
636
+	 */
637
+	public function is_major_version_change(): bool
638
+	{
639
+		return $this->_major_version_change;
640
+	}
641
+
642
+
643
+	/**
644
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
645
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
646
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
647
+	 * just activated to (for core that will always be espresso_version())
648
+	 *
649
+	 * @param array|null $activation_history             the option's value which stores the activation history for
650
+	 *                                                 this
651
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
652
+	 * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
653
+	 *                                                 indicate that this plugin was just activated
654
+	 * @param string $current_version                  the version that was just upgraded to (for core that will be
655
+	 *                                                 espresso_version())
656
+	 * @return int one of the constants on EE_System::req_type_
657
+	 */
658
+	public static function detect_req_type_given_activation_history(
659
+		array $activation_history,
660
+		string $activation_indicator_option_name,
661
+		string $current_version
662
+	): int {
663
+		$version_change = self::compareVersionWithPrevious($activation_history, $current_version);
664
+		$is_activation  = get_option($activation_indicator_option_name, false);
665
+		$req_type       = self::getRequestType($activation_history, $version_change, $is_activation);
666
+		if ($is_activation) {
667
+			// cleanup in aisle 6
668
+			delete_option($activation_indicator_option_name);
669
+		}
670
+		return $req_type;
671
+	}
672
+
673
+
674
+	/**
675
+	 * @param array  $activation_history
676
+	 * @param int    $version_change
677
+	 * @param bool   $is_activation
678
+	 * @return int
679
+	 * @since $VID:$
680
+	 */
681
+	private static function getRequestType(array $activation_history, int $version_change, bool $is_activation): int
682
+	{
683
+		// if no previous activation history exists, then this is a brand new install
684
+		if (empty($activation_history)) {
685
+			return EE_System::req_type_new_activation;
686
+		}
687
+		// current version is higher than previous version, so it's an upgrade
688
+		if ($version_change === 1) {
689
+			return EE_System::req_type_upgrade;
690
+		}
691
+		// current version is lower than previous version, so it's a downgrade
692
+		if ($version_change === -1) {
693
+			return EE_System::req_type_downgrade;
694
+		}
695
+		// version hasn't changed since last version so check if the activation indicator is set
696
+		// to determine if it's a reactivation, or just a normal request
697
+		return $is_activation
698
+			? EE_System::req_type_reactivation
699
+			: EE_System::req_type_normal;
700
+	}
701
+
702
+
703
+	/**
704
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
705
+	 * the $activation_history_for_addon
706
+	 *
707
+	 * @param array  $activation_history    array where keys are versions,
708
+	 *                                      values are arrays of times activated (sometimes 'unknown-date')
709
+	 * @param string $current_version
710
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
711
+	 *                                      -1 if $version_to_upgrade_to is LOWER (downgrade);
712
+	 *                                      0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
713
+	 *                                      1 if $version_to_upgrade_to is HIGHER (upgrade) ;
714
+	 */
715
+	private static function compareVersionWithPrevious(array $activation_history, string $current_version): int
716
+	{
717
+		// find the most recently-activated version
718
+		$most_recently_active_version = EE_System::getMostRecentlyActiveVersion($activation_history);
719
+		return version_compare($current_version, $most_recently_active_version);
720
+	}
721
+
722
+
723
+	/**
724
+	 * Gets the most recently active version listed in the activation history,
725
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
726
+	 *
727
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
728
+	 *                                   sometimes containing 'unknown-date'
729
+	 * @return string
730
+	 */
731
+	private static function getMostRecentlyActiveVersion(array $activation_history): string
732
+	{
733
+		$most_recent_activation_date  = '1970-01-01 00:00:00';
734
+		$most_recently_active_version = '0.0.0.dev.000';
735
+		if (is_array($activation_history)) {
736
+			foreach ($activation_history as $version => $activation_dates) {
737
+				// check there is a record of when this version was activated.
738
+				// Otherwise, mark it as unknown
739
+				if (! $activation_dates) {
740
+					$activation_dates = ['unknown-date'];
741
+				}
742
+				$activation_dates = is_string($activation_dates) ? [$activation_dates] : $activation_dates;
743
+				foreach ($activation_dates as $activation_date) {
744
+					if ($activation_date !== 'unknown-date' && $activation_date > $most_recent_activation_date) {
745
+						$most_recently_active_version = $version;
746
+						$most_recent_activation_date  = $activation_date;
747
+					}
748
+				}
749
+			}
750
+		}
751
+		return $most_recently_active_version;
752
+	}
753
+
754
+
755
+	/**
756
+	 * This redirects to the about EE page after activation
757
+	 *
758
+	 * @return void
759
+	 */
760
+	public function redirect_to_about_ee()
761
+	{
762
+		$notices = EE_Error::get_notices(false);
763
+		// if current user is an admin and it's not an ajax or rest request
764
+		if (
765
+			! isset($notices['errors'])
766
+			&& $this->request->isAdmin()
767
+			&& apply_filters(
768
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
769
+				$this->capabilities->current_user_can('manage_options', 'espresso_about_default')
770
+			)
771
+		) {
772
+			$query_params = ['page' => 'espresso_about'];
773
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
774
+				$query_params['new_activation'] = true;
775
+			}
776
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
777
+				$query_params['reactivation'] = true;
778
+			}
779
+			$url = add_query_arg($query_params, admin_url('admin.php'));
780
+			EEH_URL::safeRedirectAndExit($url);
781
+		}
782
+	}
783
+
784
+
785
+	/**
786
+	 * load_core_configuration
787
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
788
+	 * which runs during the WP 'plugins_loaded' action at priority 5
789
+	 *
790
+	 * @return void
791
+	 * @throws ReflectionException
792
+	 * @throws Exception
793
+	 */
794
+	public function load_core_configuration()
795
+	{
796
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
797
+		$this->loader->getShared('EE_Load_Textdomain');
798
+		// load textdomain
799
+		EE_Load_Textdomain::load_textdomain();
800
+		// load caf stuff a chance to play during the activation process too.
801
+		$this->_maybe_brew_regular();
802
+		// load and setup EE_Config and EE_Network_Config
803
+		$config = $this->loader->getShared('EE_Config');
804
+		$this->loader->getShared('EE_Network_Config');
805
+		// setup autoloaders
806
+		// enable logging?
807
+		if ($config->admin->use_remote_logging) {
808
+			$this->loader->getShared('EE_Log');
809
+		}
810
+		// check for activation errors
811
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
812
+		if ($activation_errors) {
813
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
814
+			update_option('ee_plugin_activation_errors', false);
815
+		}
816
+		// get model names
817
+		$this->_parse_model_names();
818
+		// configure custom post type definitions
819
+		$this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions');
820
+		$this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions');
821
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
822
+	}
823
+
824
+
825
+	/**
826
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
827
+	 *
828
+	 * @return void
829
+	 * @throws ReflectionException
830
+	 */
831
+	private function _parse_model_names()
832
+	{
833
+		// get all the files in the EE_MODELS folder that end in .model.php
834
+		$models                 = glob(EE_MODELS . '*.model.php');
835
+		$model_names            = [];
836
+		$non_abstract_db_models = [];
837
+		foreach ($models as $model) {
838
+			// get model classname
839
+			$classname       = EEH_File::get_classname_from_filepath_with_standard_filename($model);
840
+			$short_name      = str_replace('EEM_', '', $classname);
841
+			$reflectionClass = new ReflectionClass($classname);
842
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
843
+				$non_abstract_db_models[ $short_name ] = $classname;
844
+			}
845
+			$model_names[ $short_name ] = $classname;
846
+		}
847
+		$this->registry->models                 = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
848
+		$this->registry->non_abstract_db_models = apply_filters(
849
+			'FHEE__EE_System__parse_implemented_model_names',
850
+			$non_abstract_db_models
851
+		);
852
+	}
853
+
854
+
855
+	/**
856
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
857
+	 * that need to be setup before our EE_System launches.
858
+	 *
859
+	 * @return void
860
+	 * @throws DomainException
861
+	 * @throws InvalidArgumentException
862
+	 * @throws InvalidDataTypeException
863
+	 * @throws InvalidInterfaceException
864
+	 * @throws InvalidClassException
865
+	 * @throws InvalidFilePathException
866
+	 */
867
+	private function _maybe_brew_regular()
868
+	{
869
+		/** @var Domain $domain */
870
+		$domain = DomainFactory::getEventEspressoCoreDomain();
871
+		if ($domain->isCaffeinated()) {
872
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
873
+		}
874
+	}
875
+
876
+
877
+	/**
878
+	 * @throws Exception
879
+	 * @since 4.9.71.p
880
+	 */
881
+	public function loadRouteMatchSpecifications()
882
+	{
883
+		try {
884
+			$this->loader->getShared('EventEspresso\core\services\routing\RouteMatchSpecificationManager');
885
+			$this->loader->getShared('EventEspresso\core\services\routing\RouteCollection');
886
+			$this->router->loadPrimaryRoutes();
887
+		} catch (Exception $exception) {
888
+			new ExceptionStackTraceDisplay($exception);
889
+		}
890
+		do_action('AHEE__EE_System__loadRouteMatchSpecifications');
891
+	}
892
+
893
+
894
+	/**
895
+	 * loading CPT related classes earlier so that their definitions are available
896
+	 * but not performing any actual registration with WP core until load_CPTs_and_session() is called
897
+	 *
898
+	 * @since   4.10.21.p
899
+	 */
900
+	public function loadCustomPostTypes()
901
+	{
902
+		$this->register_custom_taxonomies = $this->loader->getShared(
903
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'
904
+		);
905
+		$this->register_custom_post_types = $this->loader->getShared(
906
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'
907
+		);
908
+		$this->register_custom_taxonomy_terms = $this->loader->getShared(
909
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms'
910
+		);
911
+		// integrate WP_Query with the EE models
912
+		$this->loader->getShared('EE_CPT_Strategy');
913
+		// load legacy EE_Request_Handler in case add-ons still need it
914
+		$this->loader->getShared('EE_Request_Handler');
915
+	}
916
+
917
+
918
+	/**
919
+	 * register_shortcodes_modules_and_widgets
920
+	 * generate lists of shortcodes and modules, then verify paths and classes
921
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
922
+	 * which runs during the WP 'plugins_loaded' action at priority 7
923
+	 *
924
+	 * @access public
925
+	 * @return void
926
+	 * @throws Exception
927
+	 */
928
+	public function register_shortcodes_modules_and_widgets()
929
+	{
930
+		$this->router->registerShortcodesModulesAndWidgets();
931
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
932
+		// check for addons using old hook point
933
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
934
+			$this->_incompatible_addon_error();
935
+		}
936
+	}
937
+
938
+
939
+	/**
940
+	 * _incompatible_addon_error
941
+	 *
942
+	 * @access public
943
+	 * @return void
944
+	 */
945
+	private function _incompatible_addon_error()
946
+	{
947
+		// get array of classes hooking into here
948
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
949
+			'AHEE__EE_System__register_shortcodes_modules_and_addons'
950
+		);
951
+		if (! empty($class_names)) {
952
+			$msg = esc_html__(
953
+				'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
954
+				'event_espresso'
955
+			);
956
+			$msg .= '<ul>';
957
+			foreach ($class_names as $class_name) {
958
+				$msg .= '<li><b>Event Espresso - '
959
+						. str_replace(
960
+							['EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'],
961
+							'',
962
+							$class_name
963
+						) . '</b></li>';
964
+			}
965
+			$msg .= '</ul>';
966
+			$msg .= esc_html__(
967
+				'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
968
+				'event_espresso'
969
+			);
970
+			// save list of incompatible addons to wp-options for later use
971
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
972
+			if (is_admin()) {
973
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
974
+			}
975
+		}
976
+	}
977
+
978
+
979
+	/**
980
+	 * brew_espresso
981
+	 * begins the process of setting hooks for initializing EE in the correct order
982
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
983
+	 * which runs during the WP 'plugins_loaded' action at priority 9
984
+	 *
985
+	 * @return void
986
+	 * @throws Exception
987
+	 */
988
+	public function brew_espresso()
989
+	{
990
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
991
+		// load some final core systems
992
+		add_action('init', [$this, 'set_hooks_for_core'], 1);
993
+		add_action('init', [$this, 'perform_activations_upgrades_and_migrations'], 3);
994
+		add_action('init', [$this, 'load_CPTs_and_session'], 5);
995
+		add_action('init', [$this, 'load_controllers'], 7);
996
+		add_action('init', [$this, 'core_loaded_and_ready'], 9);
997
+		add_action('init', [$this, 'initialize'], 10);
998
+		add_action('init', [$this, 'initialize_last'], 100);
999
+		$this->router->brewEspresso();
1000
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
1001
+	}
1002
+
1003
+
1004
+	/**
1005
+	 *    set_hooks_for_core
1006
+	 *
1007
+	 * @access public
1008
+	 * @return    void
1009
+	 * @throws EE_Error
1010
+	 */
1011
+	public function set_hooks_for_core()
1012
+	{
1013
+		$this->_deactivate_incompatible_addons();
1014
+		do_action('AHEE__EE_System__set_hooks_for_core');
1015
+		$this->loader->getShared('EventEspresso\core\domain\values\session\SessionLifespan');
1016
+		// caps need to be initialized on every request so that capability maps are set.
1017
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1018
+		$this->registry->CAP->init_caps();
1019
+	}
1020
+
1021
+
1022
+	/**
1023
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
1024
+	 * deactivates any addons considered incompatible with the current version of EE
1025
+	 */
1026
+	private function _deactivate_incompatible_addons()
1027
+	{
1028
+		$incompatible_addons = get_option('ee_incompatible_addons', []);
1029
+		if (! empty($incompatible_addons)) {
1030
+			$active_plugins = get_option('active_plugins', []);
1031
+			foreach ($active_plugins as $active_plugin) {
1032
+				foreach ($incompatible_addons as $incompatible_addon) {
1033
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
1034
+						$this->request->unSetRequestParams(['activate'], true);
1035
+						espresso_deactivate_plugin($active_plugin);
1036
+					}
1037
+				}
1038
+			}
1039
+		}
1040
+	}
1041
+
1042
+
1043
+	/**
1044
+	 *    perform_activations_upgrades_and_migrations
1045
+	 *
1046
+	 * @access public
1047
+	 * @return    void
1048
+	 */
1049
+	public function perform_activations_upgrades_and_migrations()
1050
+	{
1051
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1052
+	}
1053
+
1054
+
1055
+	/**
1056
+	 * @return void
1057
+	 * @throws DomainException
1058
+	 */
1059
+	public function load_CPTs_and_session()
1060
+	{
1061
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
1062
+		$this->register_custom_taxonomies->registerCustomTaxonomies();
1063
+		$this->register_custom_post_types->registerCustomPostTypes();
1064
+		$this->register_custom_taxonomy_terms->registerCustomTaxonomyTerms();
1065
+		// load legacy Custom Post Types and Taxonomies
1066
+		$this->loader->getShared('EE_Register_CPTs');
1067
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1068
+	}
1069
+
1070
+
1071
+	/**
1072
+	 * load_controllers
1073
+	 * this is the best place to load any additional controllers that needs access to EE core.
1074
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1075
+	 * time
1076
+	 *
1077
+	 * @access public
1078
+	 * @return void
1079
+	 * @throws Exception
1080
+	 */
1081
+	public function load_controllers()
1082
+	{
1083
+		do_action('AHEE__EE_System__load_controllers__start');
1084
+		$this->router->loadControllers();
1085
+		do_action('AHEE__EE_System__load_controllers__complete');
1086
+	}
1087
+
1088
+
1089
+	/**
1090
+	 * core_loaded_and_ready
1091
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1092
+	 *
1093
+	 * @access public
1094
+	 * @return void
1095
+	 * @throws Exception
1096
+	 */
1097
+	public function core_loaded_and_ready()
1098
+	{
1099
+		$this->router->coreLoadedAndReady();
1100
+		do_action('AHEE__EE_System__core_loaded_and_ready');
1101
+		// always load template tags, because it's faster than checking if it's a front-end request, and many page
1102
+		// builders require these even on the front-end
1103
+		require_once EE_PUBLIC . 'template_tags.php';
1104
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1105
+	}
1106
+
1107
+
1108
+	/**
1109
+	 * initialize
1110
+	 * this is the best place to begin initializing client code
1111
+	 *
1112
+	 * @access public
1113
+	 * @return void
1114
+	 */
1115
+	public function initialize()
1116
+	{
1117
+		do_action('AHEE__EE_System__initialize');
1118
+		add_filter(
1119
+			'safe_style_css',
1120
+			function ($styles) {
1121
+				$styles[] = 'display';
1122
+				$styles[] = 'visibility';
1123
+				$styles[] = 'position';
1124
+				$styles[] = 'top';
1125
+				$styles[] = 'right';
1126
+				$styles[] = 'bottom';
1127
+				$styles[] = 'left';
1128
+				$styles[] = 'resize';
1129
+				$styles[] = 'max-width';
1130
+				$styles[] = 'max-height';
1131
+				return $styles;
1132
+			}
1133
+		);
1134
+	}
1135
+
1136
+
1137
+	/**
1138
+	 * initialize_last
1139
+	 * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1140
+	 * initialize has done so
1141
+	 *
1142
+	 * @access public
1143
+	 * @return void
1144
+	 * @throws Exception
1145
+	 */
1146
+	public function initialize_last()
1147
+	{
1148
+		$this->router->initializeLast();
1149
+		do_action('AHEE__EE_System__initialize_last');
1150
+		/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
1151
+		$rewrite_rules = $this->loader->getShared(
1152
+			'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
1153
+		);
1154
+		$rewrite_rules->flushRewriteRules();
1155
+		add_action('admin_bar_init', [$this, 'addEspressoToolbar']);
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 * @return void
1161
+	 */
1162
+	public function addEspressoToolbar()
1163
+	{
1164
+		$this->loader->getShared(
1165
+			'EventEspresso\core\domain\services\admin\AdminToolBar',
1166
+			[$this->registry->CAP]
1167
+		);
1168
+	}
1169
+
1170
+
1171
+	/**
1172
+	 * do_not_cache
1173
+	 * sets no cache headers and defines no cache constants for WP plugins
1174
+	 *
1175
+	 * @access public
1176
+	 * @return void
1177
+	 */
1178
+	public static function do_not_cache()
1179
+	{
1180
+		// set no cache constants
1181
+		if (! defined('DONOTCACHEPAGE')) {
1182
+			define('DONOTCACHEPAGE', true);
1183
+		}
1184
+		if (! defined('DONOTCACHCEOBJECT')) {
1185
+			define('DONOTCACHCEOBJECT', true);
1186
+		}
1187
+		if (! defined('DONOTCACHEDB')) {
1188
+			define('DONOTCACHEDB', true);
1189
+		}
1190
+		// add no cache headers
1191
+		add_action('send_headers', ['EE_System', 'nocache_headers'], 10);
1192
+		// plus a little extra for nginx and Google Chrome
1193
+		add_filter('nocache_headers', ['EE_System', 'extra_nocache_headers'], 10, 1);
1194
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1195
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1196
+	}
1197
+
1198
+
1199
+	/**
1200
+	 *    extra_nocache_headers
1201
+	 *
1202
+	 * @access    public
1203
+	 * @param $headers
1204
+	 * @return    array
1205
+	 */
1206
+	public static function extra_nocache_headers($headers): array
1207
+	{
1208
+		// for NGINX
1209
+		$headers['X-Accel-Expires'] = 0;
1210
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1211
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1212
+		return $headers;
1213
+	}
1214
+
1215
+
1216
+	/**
1217
+	 *    nocache_headers
1218
+	 *
1219
+	 * @access    public
1220
+	 * @return    void
1221
+	 */
1222
+	public static function nocache_headers()
1223
+	{
1224
+		nocache_headers();
1225
+	}
1226
+
1227
+
1228
+	/**
1229
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1230
+	 * never returned with the function.
1231
+	 *
1232
+	 * @param array $exclude_array any existing pages being excluded are in this array.
1233
+	 * @return array
1234
+	 */
1235
+	public function remove_pages_from_wp_list_pages(array $exclude_array): array
1236
+	{
1237
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1238
+	}
1239 1239
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
         Router $router = null
158 158
     ): EE_System {
159 159
         // check if class object is instantiated
160
-        if (! self::$_instance instanceof EE_System) {
160
+        if ( ! self::$_instance instanceof EE_System) {
161 161
             self::$_instance = new self($loader, $maintenance_mode, $registry, $request, $router);
162 162
         }
163 163
         return self::$_instance;
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
         $this->capabilities = $this->loader->getShared('EE_Capabilities');
292 292
         add_action(
293 293
             'AHEE__EE_Capabilities__init_caps__before_initialization',
294
-            function () {
294
+            function() {
295 295
                 LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
296 296
             }
297 297
         );
@@ -449,11 +449,11 @@  discard block
 block discarded – undo
449 449
     private function fix_espresso_db_upgrade_option($espresso_db_update = null): array
450 450
     {
451 451
         do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
452
-        if (! $espresso_db_update) {
452
+        if ( ! $espresso_db_update) {
453 453
             $espresso_db_update = get_option('espresso_db_update');
454 454
         }
455 455
         // check that option is an array
456
-        if (! is_array($espresso_db_update)) {
456
+        if ( ! is_array($espresso_db_update)) {
457 457
             // if option is FALSE, then it never existed
458 458
             if ($espresso_db_update === false) {
459 459
                 // make $espresso_db_update an array and save option with autoload OFF
@@ -473,10 +473,10 @@  discard block
 block discarded – undo
473 473
                     // so it must be numerically-indexed, where values are versions installed...
474 474
                     // fix it!
475 475
                     $version_string                         = $should_be_array;
476
-                    $corrected_db_update[ $version_string ] = ['unknown-date'];
476
+                    $corrected_db_update[$version_string] = ['unknown-date'];
477 477
                 } else {
478 478
                     // ok it checks out
479
-                    $corrected_db_update[ $should_be_version_string ] = $should_be_array;
479
+                    $corrected_db_update[$should_be_version_string] = $should_be_array;
480 480
                 }
481 481
             }
482 482
             $espresso_db_update = $corrected_db_update;
@@ -562,13 +562,13 @@  discard block
 block discarded – undo
562 562
      */
563 563
     public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null): bool
564 564
     {
565
-        if (! $version_history) {
565
+        if ( ! $version_history) {
566 566
             $version_history = $this->fix_espresso_db_upgrade_option($version_history);
567 567
         }
568 568
         if ($current_version_to_add === null) {
569 569
             $current_version_to_add = espresso_version();
570 570
         }
571
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
571
+        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
572 572
         // re-save
573 573
         return update_option('espresso_db_update', $version_history);
574 574
     }
@@ -736,7 +736,7 @@  discard block
 block discarded – undo
736 736
             foreach ($activation_history as $version => $activation_dates) {
737 737
                 // check there is a record of when this version was activated.
738 738
                 // Otherwise, mark it as unknown
739
-                if (! $activation_dates) {
739
+                if ( ! $activation_dates) {
740 740
                     $activation_dates = ['unknown-date'];
741 741
                 }
742 742
                 $activation_dates = is_string($activation_dates) ? [$activation_dates] : $activation_dates;
@@ -831,7 +831,7 @@  discard block
 block discarded – undo
831 831
     private function _parse_model_names()
832 832
     {
833 833
         // get all the files in the EE_MODELS folder that end in .model.php
834
-        $models                 = glob(EE_MODELS . '*.model.php');
834
+        $models                 = glob(EE_MODELS.'*.model.php');
835 835
         $model_names            = [];
836 836
         $non_abstract_db_models = [];
837 837
         foreach ($models as $model) {
@@ -840,9 +840,9 @@  discard block
 block discarded – undo
840 840
             $short_name      = str_replace('EEM_', '', $classname);
841 841
             $reflectionClass = new ReflectionClass($classname);
842 842
             if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
843
-                $non_abstract_db_models[ $short_name ] = $classname;
843
+                $non_abstract_db_models[$short_name] = $classname;
844 844
             }
845
-            $model_names[ $short_name ] = $classname;
845
+            $model_names[$short_name] = $classname;
846 846
         }
847 847
         $this->registry->models                 = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
848 848
         $this->registry->non_abstract_db_models = apply_filters(
@@ -869,7 +869,7 @@  discard block
 block discarded – undo
869 869
         /** @var Domain $domain */
870 870
         $domain = DomainFactory::getEventEspressoCoreDomain();
871 871
         if ($domain->isCaffeinated()) {
872
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
872
+            require_once EE_CAFF_PATH.'brewing_regular.php';
873 873
         }
874 874
     }
875 875
 
@@ -948,7 +948,7 @@  discard block
 block discarded – undo
948 948
         $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
949 949
             'AHEE__EE_System__register_shortcodes_modules_and_addons'
950 950
         );
951
-        if (! empty($class_names)) {
951
+        if ( ! empty($class_names)) {
952 952
             $msg = esc_html__(
953 953
                 'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
954 954
                 'event_espresso'
@@ -960,7 +960,7 @@  discard block
 block discarded – undo
960 960
                             ['EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'],
961 961
                             '',
962 962
                             $class_name
963
-                        ) . '</b></li>';
963
+                        ).'</b></li>';
964 964
             }
965 965
             $msg .= '</ul>';
966 966
             $msg .= esc_html__(
@@ -1026,7 +1026,7 @@  discard block
 block discarded – undo
1026 1026
     private function _deactivate_incompatible_addons()
1027 1027
     {
1028 1028
         $incompatible_addons = get_option('ee_incompatible_addons', []);
1029
-        if (! empty($incompatible_addons)) {
1029
+        if ( ! empty($incompatible_addons)) {
1030 1030
             $active_plugins = get_option('active_plugins', []);
1031 1031
             foreach ($active_plugins as $active_plugin) {
1032 1032
                 foreach ($incompatible_addons as $incompatible_addon) {
@@ -1100,7 +1100,7 @@  discard block
 block discarded – undo
1100 1100
         do_action('AHEE__EE_System__core_loaded_and_ready');
1101 1101
         // always load template tags, because it's faster than checking if it's a front-end request, and many page
1102 1102
         // builders require these even on the front-end
1103
-        require_once EE_PUBLIC . 'template_tags.php';
1103
+        require_once EE_PUBLIC.'template_tags.php';
1104 1104
         do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1105 1105
     }
1106 1106
 
@@ -1117,7 +1117,7 @@  discard block
 block discarded – undo
1117 1117
         do_action('AHEE__EE_System__initialize');
1118 1118
         add_filter(
1119 1119
             'safe_style_css',
1120
-            function ($styles) {
1120
+            function($styles) {
1121 1121
                 $styles[] = 'display';
1122 1122
                 $styles[] = 'visibility';
1123 1123
                 $styles[] = 'position';
@@ -1178,13 +1178,13 @@  discard block
 block discarded – undo
1178 1178
     public static function do_not_cache()
1179 1179
     {
1180 1180
         // set no cache constants
1181
-        if (! defined('DONOTCACHEPAGE')) {
1181
+        if ( ! defined('DONOTCACHEPAGE')) {
1182 1182
             define('DONOTCACHEPAGE', true);
1183 1183
         }
1184
-        if (! defined('DONOTCACHCEOBJECT')) {
1184
+        if ( ! defined('DONOTCACHCEOBJECT')) {
1185 1185
             define('DONOTCACHCEOBJECT', true);
1186 1186
         }
1187
-        if (! defined('DONOTCACHEDB')) {
1187
+        if ( ! defined('DONOTCACHEDB')) {
1188 1188
             define('DONOTCACHEDB', true);
1189 1189
         }
1190 1190
         // add no cache headers
Please login to merge, or discard this patch.
core/helpers/EEH_MSG_Template.helper.php 1 patch
Indentation   +1251 added lines, -1251 removed lines patch added patch discarded remove patch
@@ -13,1258 +13,1258 @@
 block discarded – undo
13 13
  */
14 14
 class EEH_MSG_Template
15 15
 {
16
-    /**
17
-     * Holds a collection of EE_Message_Template_Pack objects.
18
-     * @type EE_Messages_Template_Pack_Collection
19
-     */
20
-    protected static $_template_pack_collection;
21
-
22
-
23
-    /**
24
-     * @throws EE_Error
25
-     */
26
-    private static function _set_autoloader()
27
-    {
28
-        EED_Messages::set_autoloaders();
29
-    }
30
-
31
-
32
-    /**
33
-     * generate_new_templates
34
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
35
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
36
-     * for the event.
37
-     *
38
-     * @access protected
39
-     * @param string $messenger     the messenger we are generating templates for
40
-     * @param array  $message_types array of message types that the templates are generated for.
41
-     * @param int    $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID
42
-     *                              to use as the base for the new generated template.
43
-     * @param bool   $global        true indicates generating templates on messenger activation. false requires GRP_ID
44
-     *                              for event specific template generation.
45
-     * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array
46
-     *                for templates that are generated.  If this is an empty array then it means no templates were
47
-     *                generated which usually means there was an error.  Anything in the array with an empty value for
48
-     *                `MTP_context` means that it was not a new generated template but just reactivated (which only
49
-     *                happens for global templates that already exist in the database.
50
-     * @throws EE_Error
51
-     * @throws ReflectionException
52
-     */
53
-    public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
54
-    {
55
-        // make sure message_type is an array.
56
-        $message_types = (array) $message_types;
57
-        $templates = array();
58
-
59
-        if (empty($messenger)) {
60
-            throw new EE_Error(esc_html__('We need a messenger to generate templates!', 'event_espresso'));
61
-        }
62
-
63
-        // if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
64
-        if (empty($message_types)) {
65
-            throw new EE_Error(esc_html__('We need at least one message type to generate templates!', 'event_espresso'));
66
-        }
67
-
68
-        EEH_MSG_Template::_set_autoloader();
69
-        foreach ($message_types as $message_type) {
70
-            // if this is global template generation.
71
-            if ($global) {
72
-                // let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
73
-                if (empty($GRP_ID)) {
74
-                    $GRP_ID = EEM_Message_Template_Group::instance()->get_one(
75
-                        array(
76
-                            array(
77
-                                'MTP_messenger'    => $messenger,
78
-                                'MTP_message_type' => $message_type,
79
-                                'MTP_is_global'    => true,
80
-                            ),
81
-                        )
82
-                    );
83
-                    $GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
84
-                }
85
-                // First let's determine if we already HAVE global templates for this messenger and message_type combination.
86
-                //  If we do then NO generation!!
87
-                if (EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
88
-                    $templates[] = array(
89
-                        'GRP_ID' => $GRP_ID,
90
-                        'MTP_context' => '',
91
-                    );
92
-                    // we already have generated templates for this so let's go to the next message type.
93
-                    continue;
94
-                }
95
-            }
96
-            $new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
97
-
98
-            if (! $new_message_template_group) {
99
-                continue;
100
-            }
101
-            $templates[] = $new_message_template_group;
102
-        }
103
-
104
-        return $templates;
105
-    }
106
-
107
-
108
-    /**
109
-     * The purpose of this method is to determine if there are already generated templates in the database for the
110
-     * given variables.
111
-     *
112
-     * @param string $messenger    messenger
113
-     * @param string $message_type message type
114
-     * @param int    $GRP_ID       GRP ID ( if a custom template) (if not provided then we're just doing global
115
-     *                             template check)
116
-     * @return bool                true = generated, false = hasn't been generated.
117
-     * @throws EE_Error
118
-     */
119
-    public static function already_generated($messenger, $message_type, $GRP_ID = 0)
120
-    {
121
-        EEH_MSG_Template::_set_autoloader();
122
-        // what method we use depends on whether we have an GRP_ID or not
123
-        $count = empty($GRP_ID)
124
-            ? EEM_Message_Template::instance()->count(
125
-                array(
126
-                    array(
127
-                        'Message_Template_Group.MTP_messenger'    => $messenger,
128
-                        'Message_Template_Group.MTP_message_type' => $message_type,
129
-                        'Message_Template_Group.MTP_is_global'    => true
130
-                    )
131
-                )
132
-            )
133
-            : EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
134
-
135
-        return $count > 0;
136
-    }
137
-
138
-
139
-    /**
140
-     * Updates all message templates matching the incoming messengers and message types to active status.
141
-     *
142
-     * @static
143
-     * @param array $messenger_names    Messenger slug
144
-     * @param array $message_type_names Message type slug
145
-     * @return  int                         count of updated records.
146
-     * @throws EE_Error
147
-     */
148
-    public static function update_to_active($messenger_names, $message_type_names)
149
-    {
150
-        $messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
151
-        $message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
152
-        return EEM_Message_Template_Group::instance()->update(
153
-            array( 'MTP_is_active' => 1 ),
154
-            array(
155
-                array(
156
-                    'MTP_messenger'     => array( 'IN', $messenger_names ),
157
-                    'MTP_message_type'  => array( 'IN', $message_type_names )
158
-                )
159
-            )
160
-        );
161
-    }
162
-
163
-
164
-    /**
165
-     * Updates all message template groups matching the incoming arguments to inactive status.
166
-     *
167
-     * @static
168
-     * @param array $messenger_names    The messenger slugs.
169
-     *                                  If empty then all templates matching the message types are marked inactive.
170
-     *                                  Otherwise only templates matching the messengers and message types.
171
-     * @param array $message_type_names The message type slugs.
172
-     *                                  If empty then all templates matching the messengers are marked inactive.
173
-     *                                  Otherwise only templates matching the messengers and message types.
174
-     *
175
-     * @return int  count of updated records.
176
-     * @throws EE_Error
177
-     */
178
-    public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
179
-    {
180
-        return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
181
-            $messenger_names,
182
-            $message_type_names
183
-        );
184
-    }
185
-
186
-
187
-    /**
188
-     * The purpose of this function is to return all installed message objects
189
-     * (messengers and message type regardless of whether they are ACTIVE or not)
190
-     *
191
-     * @param string $type
192
-     * @return array array consisting of installed messenger objects and installed message type objects.
193
-     * @throws EE_Error
194
-     * @throws ReflectionException
195
-     * @deprecated 4.9.0
196
-     * @static
197
-     */
198
-    public static function get_installed_message_objects($type = 'all')
199
-    {
200
-        self::_set_autoloader();
201
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
202
-        return array(
203
-            'messenger' => $message_resource_manager->installed_messengers(),
204
-            'message_type' => $message_resource_manager->installed_message_types()
205
-        );
206
-    }
207
-
208
-
209
-    /**
210
-     * This will return an array of shortcodes => labels from the
211
-     * messenger and message_type objects associated with this
212
-     * template.
213
-     *
214
-     * @param string $message_type
215
-     * @param string $messenger
216
-     * @param array  $fields                        What fields we're returning valid shortcodes for.
217
-     *                                              If empty then we assume all fields are to be returned. Optional.
218
-     * @param string $context                       What context we're going to return shortcodes for. Optional.
219
-     * @param bool   $merged                        If TRUE then we don't return shortcodes indexed by field,
220
-     *                                              but instead an array of the unique shortcodes for all the given (
221
-     *                                              or all) fields. Optional.
222
-     * @return array                                an array of shortcodes in the format
223
-     *                                              array( '[shortcode] => 'label')
224
-     *                                              OR
225
-     *                                              FALSE if no shortcodes found.
226
-     * @throws ReflectionException
227
-     * @throws EE_Error*@since 4.3.0
228
-     *
229
-     */
230
-    public static function get_shortcodes(
231
-        $message_type,
232
-        $messenger,
233
-        $fields = array(),
234
-        $context = 'admin',
235
-        $merged = false
236
-    ) {
237
-        $messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
238
-        $mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
239
-        /** @var EE_Message_Resource_Manager $message_resource_manager */
240
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
241
-        // convert slug to object
242
-        $messenger = $message_resource_manager->get_messenger($messenger);
243
-
244
-        // if messenger isn't a EE_messenger resource then bail.
245
-        if (! $messenger instanceof EE_messenger) {
246
-            return array();
247
-        }
248
-
249
-        // validate class for getting our list of shortcodes
250
-        $classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
251
-        if (! class_exists($classname)) {
252
-            $msg[] = esc_html__('The Validator class was unable to load', 'event_espresso');
253
-            $msg[] = sprintf(
254
-                esc_html__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
255
-                $classname
256
-            );
257
-            throw new EE_Error(implode('||', $msg));
258
-        }
259
-
260
-        /** @type EE_Messages_Validator $_VLD */
261
-        $_VLD = new $classname(array(), $context);
262
-        $valid_shortcodes = $_VLD->get_validators();
263
-
264
-        // let's make sure we're only getting the shortcode part of the validators
265
-        $shortcodes = array();
266
-        foreach ($valid_shortcodes as $field => $validators) {
267
-            $shortcodes[ $field ] = $validators['shortcodes'];
268
-        }
269
-        $valid_shortcodes = $shortcodes;
270
-
271
-        // if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
272
-        if (! empty($fields)) {
273
-            $specified_shortcodes = array();
274
-            foreach ($fields as $field) {
275
-                if (isset($valid_shortcodes[ $field ])) {
276
-                    $specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
277
-                }
278
-            }
279
-            $valid_shortcodes = $specified_shortcodes;
280
-        }
281
-
282
-        // if not merged then let's replace the fields with the localized fields
283
-        if (! $merged) {
284
-            // let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
285
-            $field_settings = $messenger->get_template_fields();
286
-            $localized = array();
287
-            foreach ($valid_shortcodes as $field => $shortcodes) {
288
-                // get localized field label
289
-                if (isset($field_settings[ $field ])) {
290
-                    // possible that this is used as a main field.
291
-                    if (empty($field_settings[ $field ])) {
292
-                        if (isset($field_settings['extra'][ $field ])) {
293
-                            $_field = $field_settings['extra'][ $field ]['main']['label'];
294
-                        } else {
295
-                            $_field = $field;
296
-                        }
297
-                    } else {
298
-                        $_field = $field_settings[ $field ]['label'];
299
-                    }
300
-                } elseif (isset($field_settings['extra'])) {
301
-                    // loop through extra "main fields" and see if any of their children have our field
302
-                    foreach ($field_settings['extra'] as $fields) {
303
-                        if (isset($fields[ $field ])) {
304
-                            $_field = $fields[ $field ]['label'];
305
-                        } else {
306
-                            $_field = $field;
307
-                        }
308
-                    }
309
-                } else {
310
-                    $_field = $field;
311
-                }
312
-                if (isset($_field)) {
313
-                    $localized[ (string) $_field ] = $shortcodes;
314
-                }
315
-            }
316
-            $valid_shortcodes = $localized;
317
-        }
318
-
319
-        // if $merged then let's merge all the shortcodes into one list NOT indexed by field.
320
-        if ($merged) {
321
-            $merged_codes = array();
322
-            foreach ($valid_shortcodes as $shortcode) {
323
-                foreach ($shortcode as $code => $label) {
324
-                    if (isset($merged_codes[ $code ])) {
325
-                        continue;
326
-                    } else {
327
-                        $merged_codes[ $code ] = $label;
328
-                    }
329
-                }
330
-            }
331
-            $valid_shortcodes = $merged_codes;
332
-        }
333
-
334
-        return $valid_shortcodes;
335
-    }
336
-
337
-
338
-    /**
339
-     * Get Messenger object.
340
-     *
341
-     * @param string $messenger messenger slug for the messenger object we want to retrieve.
342
-     * @return EE_messenger
343
-     * @throws ReflectionException
344
-     * @throws EE_Error*@since 4.3.0
345
-     * @deprecated 4.9.0
346
-     */
347
-    public static function messenger_obj($messenger)
348
-    {
349
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
350
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
351
-        return $Message_Resource_Manager->get_messenger($messenger);
352
-    }
353
-
354
-
355
-    /**
356
-     * get Message type object
357
-     *
358
-     * @param string $message_type the slug for the message type object to retrieve
359
-     * @return EE_message_type
360
-     * @throws ReflectionException
361
-     * @throws EE_Error*@since 4.3.0
362
-     * @deprecated 4.9.0
363
-     */
364
-    public static function message_type_obj($message_type)
365
-    {
366
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
367
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
368
-        return $Message_Resource_Manager->get_message_type($message_type);
369
-    }
370
-
371
-
372
-    /**
373
-     * Given a message_type slug, will return whether that message type is active in the system or not.
374
-     *
375
-     * @since    4.3.0
376
-     * @param string $message_type message type to check for.
377
-     * @return boolean
378
-     * @throws EE_Error
379
-     * @throws ReflectionException
380
-     */
381
-    public static function is_mt_active($message_type)
382
-    {
383
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
384
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
385
-        $active_mts = $Message_Resource_Manager->list_of_active_message_types();
386
-        return in_array($message_type, $active_mts);
387
-    }
388
-
389
-
390
-    /**
391
-     * Given a messenger slug, will return whether that messenger is active in the system or not.
392
-     *
393
-     * @since    4.3.0
394
-     *
395
-     * @param string $messenger slug for messenger to check.
396
-     * @return boolean
397
-     * @throws EE_Error
398
-     * @throws ReflectionException
399
-     */
400
-    public static function is_messenger_active($messenger)
401
-    {
402
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
403
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
404
-        $active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
405
-        return $active_messenger instanceof EE_messenger;
406
-    }
407
-
408
-
409
-    /**
410
-     * Used to return active messengers array stored in the wp options table.
411
-     * If no value is present in the option then an empty array is returned.
412
-     *
413
-     * @deprecated 4.9
414
-     * @since      4.3.1
415
-     *
416
-     * @return array
417
-     * @throws EE_Error
418
-     * @throws ReflectionException
419
-     */
420
-    public static function get_active_messengers_in_db()
421
-    {
422
-        EE_Error::doing_it_wrong(
423
-            __METHOD__,
424
-            esc_html__('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
425
-            '4.9.0'
426
-        );
427
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
428
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
429
-        return $Message_Resource_Manager->get_active_messengers_option();
430
-    }
431
-
432
-
433
-    /**
434
-     * Used to update the active messengers array stored in the wp options table.
435
-     *
436
-     * @since      4.3.1
437
-     * @deprecated 4.9.0
438
-     *
439
-     * @param array $data_to_save Incoming data to save.
440
-     *
441
-     * @return bool FALSE if not updated, TRUE if updated.
442
-     * @throws EE_Error
443
-     * @throws ReflectionException
444
-     */
445
-    public static function update_active_messengers_in_db($data_to_save)
446
-    {
447
-        EE_Error::doing_it_wrong(
448
-            __METHOD__,
449
-            esc_html__('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
450
-            '4.9.0'
451
-        );
452
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
453
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
454
-        return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
455
-    }
456
-
457
-
458
-    /**
459
-     * This does some validation of incoming params, determines what type of url is being prepped and returns the
460
-     * appropriate url trigger
461
-     *
462
-     * @param EE_message_type $message_type
463
-     * @param EE_Message $message
464
-     * @param EE_Registration | null $registration  The registration object must be included if this
465
-     *                                              is going to be a registration trigger url.
466
-     * @param string $sending_messenger             The (optional) sending messenger for the url.
467
-     *
468
-     * @return string
469
-     * @throws EE_Error
470
-     */
471
-    public static function get_url_trigger(
472
-        EE_message_type $message_type,
473
-        EE_Message $message,
474
-        $registration = null,
475
-        $sending_messenger = ''
476
-    ) {
477
-        // first determine if the url can be to the EE_Message object.
478
-        if (! $message_type->always_generate()) {
479
-            return EEH_MSG_Template::generate_browser_trigger($message);
480
-        }
481
-
482
-        // if $registration object is not valid then exit early because there's nothing that can be generated.
483
-        if (! $registration instanceof EE_Registration) {
484
-            throw new EE_Error(
485
-                esc_html__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
486
-            );
487
-        }
488
-
489
-        // validate given context
490
-        $contexts = $message_type->get_contexts();
491
-        if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
492
-            throw new EE_Error(
493
-                sprintf(
494
-                    esc_html__('The context %s is not a valid context for %s.', 'event_espresso'),
495
-                    $message->context(),
496
-                    get_class($message_type)
497
-                )
498
-            );
499
-        }
500
-
501
-        // valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
502
-        if (! empty($sending_messenger)) {
503
-            $with_messengers = $message_type->with_messengers();
504
-            if (
505
-                ! isset($with_messengers[ $message->messenger() ])
506
-                 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])
507
-            ) {
508
-                throw new EE_Error(
509
-                    sprintf(
510
-                        esc_html__(
511
-                            'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
512
-                            'event_espresso'
513
-                        ),
514
-                        $sending_messenger,
515
-                        get_class($message_type)
516
-                    )
517
-                );
518
-            }
519
-        } else {
520
-            $sending_messenger = $message->messenger();
521
-        }
522
-        return EEH_MSG_Template::generate_url_trigger(
523
-            $sending_messenger,
524
-            $message->messenger(),
525
-            $message->context(),
526
-            $message->message_type(),
527
-            $registration,
528
-            $message->GRP_ID()
529
-        );
530
-    }
531
-
532
-
533
-    /**
534
-     * This returns the url for triggering a in browser view of a specific EE_Message object.
535
-     * @param EE_Message $message
536
-     * @return string.
537
-     */
538
-    public static function generate_browser_trigger(EE_Message $message)
539
-    {
540
-        $query_args = array(
541
-            'ee' => 'msg_browser_trigger',
542
-            'token' => $message->MSG_token()
543
-        );
544
-        return apply_filters(
545
-            'FHEE__EEH_MSG_Template__generate_browser_trigger',
546
-            add_query_arg($query_args, site_url()),
547
-            $message
548
-        );
549
-    }
550
-
551
-
552
-
553
-
554
-
555
-
556
-    /**
557
-     * This returns the url for triggering an in browser view of the error saved on the incoming message object.
558
-     * @param EE_Message $message
559
-     * @return string
560
-     */
561
-    public static function generate_error_display_trigger(EE_Message $message)
562
-    {
563
-        return apply_filters(
564
-            'FHEE__EEH_MSG_Template__generate_error_display_trigger',
565
-            add_query_arg(
566
-                array(
567
-                    'ee' => 'msg_browser_error_trigger',
568
-                    'token' => $message->MSG_token()
569
-                ),
570
-                site_url()
571
-            ),
572
-            $message
573
-        );
574
-    }
575
-
576
-
577
-    /**
578
-     * This generates a url trigger for the msg_url_trigger route using the given arguments
579
-     *
580
-     * @param string          $sending_messenger      The sending messenger slug.
581
-     * @param string          $generating_messenger   The generating messenger slug.
582
-     * @param string          $context                The context for the template.
583
-     * @param string          $message_type           The message type slug
584
-     * @param EE_Registration $registration
585
-     * @param integer         $message_template_group id   The EE_Message_Template_Group ID for the template.
586
-     * @param integer         $data_id                The id to the EE_Base_Class for getting the data used by the
587
-     *                                                trigger.
588
-     * @return string          The generated url.
589
-     * @throws EE_Error
590
-     */
591
-    public static function generate_url_trigger(
592
-        $sending_messenger,
593
-        $generating_messenger,
594
-        $context,
595
-        $message_type,
596
-        EE_Registration $registration,
597
-        $message_template_group,
598
-        $data_id = 0
599
-    ) {
600
-        $query_args = array(
601
-            'ee' => 'msg_url_trigger',
602
-            'snd_msgr' => $sending_messenger,
603
-            'gen_msgr' => $generating_messenger,
604
-            'message_type' => $message_type,
605
-            'context' => $context,
606
-            'token' => $registration->reg_url_link(),
607
-            'GRP_ID' => $message_template_group,
608
-            'id' => $data_id
609
-            );
610
-        $url = add_query_arg($query_args, get_home_url());
611
-
612
-        // made it here so now we can just get the url and filter it.  Filtered globally and by message type.
613
-        return apply_filters(
614
-            'FHEE__EEH_MSG_Template__generate_url_trigger',
615
-            $url,
616
-            $sending_messenger,
617
-            $generating_messenger,
618
-            $context,
619
-            $message_type,
620
-            $registration,
621
-            $message_template_group,
622
-            $data_id
623
-        );
624
-    }
625
-
626
-
627
-
628
-
629
-    /**
630
-     * Return the specific css for the action icon given.
631
-     *
632
-     * @param string $type  What action to return.
633
-     * @return string[]
634
-     * @since 4.9.0
635
-     */
636
-    public static function get_message_action_icon($type)
637
-    {
638
-        $action_icons = self::get_message_action_icons();
639
-        return isset($action_icons[ $type ]) ? $action_icons[ $type ] : [];
640
-    }
641
-
642
-
643
-    /**
644
-     * This is used for retrieving the css classes used for the icons representing message actions.
645
-     *
646
-     * @since 4.9.0
647
-     *
648
-     * @return array
649
-     */
650
-    public static function get_message_action_icons()
651
-    {
652
-        return apply_filters(
653
-            'FHEE__EEH_MSG_Template__message_action_icons',
654
-            array(
655
-                'view' => array(
656
-                    'label' => esc_html__('View Message', 'event_espresso'),
657
-                    'css_class' => 'dashicons dashicons-visibility',
658
-                ),
659
-                'error' => array(
660
-                    'label' => esc_html__('View Error Message', 'event_espresso'),
661
-                    'css_class' => 'dashicons dashicons-info',
662
-                ),
663
-                'see_notifications_for' => array(
664
-                    'label' => esc_html__('View Related Messages', 'event_espresso'),
665
-                    'css_class' => 'dashicons dashicons-megaphone',
666
-                ),
667
-                'generate_now' => array(
668
-                    'label' => esc_html__('Generate the message now.', 'event_espresso'),
669
-                    'css_class' => 'dashicons dashicons-admin-tools',
670
-                ),
671
-                'send_now' => array(
672
-                    'label' => esc_html__('Send Immediately', 'event_espresso'),
673
-                    'css_class' => 'dashicons dashicons-controls-forward',
674
-                ),
675
-                'queue_for_resending' => array(
676
-                    'label' => esc_html__('Queue for Resending', 'event_espresso'),
677
-                    'css_class' => 'dashicons dashicons-controls-repeat',
678
-                ),
679
-                'view_transaction' => array(
680
-                    'label' => esc_html__('View related Transaction', 'event_espresso'),
681
-                    'css_class' => 'dashicons dashicons-cart',
682
-                )
683
-            )
684
-        );
685
-    }
686
-
687
-
688
-    /**
689
-     * This returns the url for a given action related to EE_Message.
690
-     *
691
-     * @param string     $type         What type of action to return the url for.
692
-     * @param EE_Message $message      Required for generating the correct url for some types.
693
-     * @param array      $query_params Any additional query params to be included with the generated url.
694
-     *
695
-     * @return string
696
-     * @throws EE_Error
697
-     * @throws ReflectionException
698
-     * @since 4.9.0
699
-     *
700
-     */
701
-    public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
702
-    {
703
-        $action_urls = self::get_message_action_urls($message, $query_params);
704
-        return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
705
-    }
706
-
707
-
708
-    /**
709
-     * This returns all the current urls for EE_Message actions.
710
-     *
711
-     * @since 4.9.0
712
-     *
713
-     * @param EE_Message $message      The EE_Message object required to generate correct urls for some types.
714
-     * @param array      $query_params Any additional query_params to be included with the generated url.
715
-     *
716
-     * @return array
717
-     * @throws EE_Error
718
-     * @throws ReflectionException
719
-     */
720
-    public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
721
-    {
722
-        EE_Registry::instance()->load_helper('URL');
723
-        // if $message is not an instance of EE_Message then let's just do a dummy.
724
-        $message = empty($message) ? EE_Message_Factory::create() : $message;
725
-        $action_urls =  apply_filters(
726
-            'FHEE__EEH_MSG_Template__get_message_action_url',
727
-            array(
728
-                'view' => EEH_MSG_Template::generate_browser_trigger($message),
729
-                'error' => EEH_MSG_Template::generate_error_display_trigger($message),
730
-                'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
731
-                    array_merge(
732
-                        array(
733
-                            'page' => 'espresso_messages',
734
-                            'action' => 'default',
735
-                            'filterby' => 1,
736
-                        ),
737
-                        $query_params
738
-                    ),
739
-                    admin_url('admin.php')
740
-                ),
741
-                'generate_now' => EEH_URL::add_query_args_and_nonce(
742
-                    array(
743
-                        'page' => 'espresso_messages',
744
-                        'action' => 'generate_now',
745
-                        'MSG_ID' => $message->ID()
746
-                    ),
747
-                    admin_url('admin.php')
748
-                ),
749
-                'send_now' => EEH_URL::add_query_args_and_nonce(
750
-                    array(
751
-                        'page' => 'espresso_messages',
752
-                        'action' => 'send_now',
753
-                        'MSG_ID' => $message->ID()
754
-                    ),
755
-                    admin_url('admin.php')
756
-                ),
757
-                'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
758
-                    array(
759
-                        'page' => 'espresso_messages',
760
-                        'action' => 'queue_for_resending',
761
-                        'MSG_ID' => $message->ID()
762
-                    ),
763
-                    admin_url('admin.php')
764
-                ),
765
-            )
766
-        );
767
-        if (
768
-            $message->TXN_ID() > 0
769
-            && EE_Registry::instance()->CAP->current_user_can(
770
-                'ee_read_transaction',
771
-                'espresso_transactions_default',
772
-                $message->TXN_ID()
773
-            )
774
-        ) {
775
-            $action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
776
-                array(
777
-                    'page' => 'espresso_transactions',
778
-                    'action' => 'view_transaction',
779
-                    'TXN_ID' => $message->TXN_ID()
780
-                ),
781
-                admin_url('admin.php')
782
-            );
783
-        } else {
784
-            $action_urls['view_transaction'] = '';
785
-        }
786
-        return $action_urls;
787
-    }
788
-
789
-
790
-    /**
791
-     * This returns a generated link html including the icon used for the action link for EE_Message actions.
792
-     *
793
-     * @param string          $type         What type of action the link is for (if invalid type is passed in then an
794
-     *                                      empty string is returned)
795
-     * @param EE_Message|null $message      The EE_Message object (required for some actions to generate correctly)
796
-     * @param array           $query_params Any extra query params to include in the generated link.
797
-     *
798
-     * @return string
799
-     * @throws EE_Error
800
-     * @throws ReflectionException
801
-     * @since 4.9.0
802
-     *
803
-     */
804
-    public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
805
-    {
806
-        $url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
807
-        $icon_css = EEH_MSG_Template::get_message_action_icon($type);
808
-        $label = $icon_css['label'] ?? null;
809
-        $label = $label ? 'aria-label="' . $label . '"' : '';
810
-        $class = $label ? ' ee-aria-tooltip' : '';
811
-
812
-        if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
813
-            return '';
814
-        }
815
-
816
-        $icon_css['css_class'] .= esc_attr(
817
-            apply_filters(
818
-                'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
819
-                ' js-ee-message-action-link ee-message-action-link-' . $type,
820
-                $type,
821
-                $message,
822
-                $query_params
823
-            )
824
-        );
825
-
826
-        return '
16
+	/**
17
+	 * Holds a collection of EE_Message_Template_Pack objects.
18
+	 * @type EE_Messages_Template_Pack_Collection
19
+	 */
20
+	protected static $_template_pack_collection;
21
+
22
+
23
+	/**
24
+	 * @throws EE_Error
25
+	 */
26
+	private static function _set_autoloader()
27
+	{
28
+		EED_Messages::set_autoloaders();
29
+	}
30
+
31
+
32
+	/**
33
+	 * generate_new_templates
34
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
35
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
36
+	 * for the event.
37
+	 *
38
+	 * @access protected
39
+	 * @param string $messenger     the messenger we are generating templates for
40
+	 * @param array  $message_types array of message types that the templates are generated for.
41
+	 * @param int    $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID
42
+	 *                              to use as the base for the new generated template.
43
+	 * @param bool   $global        true indicates generating templates on messenger activation. false requires GRP_ID
44
+	 *                              for event specific template generation.
45
+	 * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array
46
+	 *                for templates that are generated.  If this is an empty array then it means no templates were
47
+	 *                generated which usually means there was an error.  Anything in the array with an empty value for
48
+	 *                `MTP_context` means that it was not a new generated template but just reactivated (which only
49
+	 *                happens for global templates that already exist in the database.
50
+	 * @throws EE_Error
51
+	 * @throws ReflectionException
52
+	 */
53
+	public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
54
+	{
55
+		// make sure message_type is an array.
56
+		$message_types = (array) $message_types;
57
+		$templates = array();
58
+
59
+		if (empty($messenger)) {
60
+			throw new EE_Error(esc_html__('We need a messenger to generate templates!', 'event_espresso'));
61
+		}
62
+
63
+		// if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
64
+		if (empty($message_types)) {
65
+			throw new EE_Error(esc_html__('We need at least one message type to generate templates!', 'event_espresso'));
66
+		}
67
+
68
+		EEH_MSG_Template::_set_autoloader();
69
+		foreach ($message_types as $message_type) {
70
+			// if this is global template generation.
71
+			if ($global) {
72
+				// let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
73
+				if (empty($GRP_ID)) {
74
+					$GRP_ID = EEM_Message_Template_Group::instance()->get_one(
75
+						array(
76
+							array(
77
+								'MTP_messenger'    => $messenger,
78
+								'MTP_message_type' => $message_type,
79
+								'MTP_is_global'    => true,
80
+							),
81
+						)
82
+					);
83
+					$GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
84
+				}
85
+				// First let's determine if we already HAVE global templates for this messenger and message_type combination.
86
+				//  If we do then NO generation!!
87
+				if (EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
88
+					$templates[] = array(
89
+						'GRP_ID' => $GRP_ID,
90
+						'MTP_context' => '',
91
+					);
92
+					// we already have generated templates for this so let's go to the next message type.
93
+					continue;
94
+				}
95
+			}
96
+			$new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
97
+
98
+			if (! $new_message_template_group) {
99
+				continue;
100
+			}
101
+			$templates[] = $new_message_template_group;
102
+		}
103
+
104
+		return $templates;
105
+	}
106
+
107
+
108
+	/**
109
+	 * The purpose of this method is to determine if there are already generated templates in the database for the
110
+	 * given variables.
111
+	 *
112
+	 * @param string $messenger    messenger
113
+	 * @param string $message_type message type
114
+	 * @param int    $GRP_ID       GRP ID ( if a custom template) (if not provided then we're just doing global
115
+	 *                             template check)
116
+	 * @return bool                true = generated, false = hasn't been generated.
117
+	 * @throws EE_Error
118
+	 */
119
+	public static function already_generated($messenger, $message_type, $GRP_ID = 0)
120
+	{
121
+		EEH_MSG_Template::_set_autoloader();
122
+		// what method we use depends on whether we have an GRP_ID or not
123
+		$count = empty($GRP_ID)
124
+			? EEM_Message_Template::instance()->count(
125
+				array(
126
+					array(
127
+						'Message_Template_Group.MTP_messenger'    => $messenger,
128
+						'Message_Template_Group.MTP_message_type' => $message_type,
129
+						'Message_Template_Group.MTP_is_global'    => true
130
+					)
131
+				)
132
+			)
133
+			: EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
134
+
135
+		return $count > 0;
136
+	}
137
+
138
+
139
+	/**
140
+	 * Updates all message templates matching the incoming messengers and message types to active status.
141
+	 *
142
+	 * @static
143
+	 * @param array $messenger_names    Messenger slug
144
+	 * @param array $message_type_names Message type slug
145
+	 * @return  int                         count of updated records.
146
+	 * @throws EE_Error
147
+	 */
148
+	public static function update_to_active($messenger_names, $message_type_names)
149
+	{
150
+		$messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
151
+		$message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
152
+		return EEM_Message_Template_Group::instance()->update(
153
+			array( 'MTP_is_active' => 1 ),
154
+			array(
155
+				array(
156
+					'MTP_messenger'     => array( 'IN', $messenger_names ),
157
+					'MTP_message_type'  => array( 'IN', $message_type_names )
158
+				)
159
+			)
160
+		);
161
+	}
162
+
163
+
164
+	/**
165
+	 * Updates all message template groups matching the incoming arguments to inactive status.
166
+	 *
167
+	 * @static
168
+	 * @param array $messenger_names    The messenger slugs.
169
+	 *                                  If empty then all templates matching the message types are marked inactive.
170
+	 *                                  Otherwise only templates matching the messengers and message types.
171
+	 * @param array $message_type_names The message type slugs.
172
+	 *                                  If empty then all templates matching the messengers are marked inactive.
173
+	 *                                  Otherwise only templates matching the messengers and message types.
174
+	 *
175
+	 * @return int  count of updated records.
176
+	 * @throws EE_Error
177
+	 */
178
+	public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
179
+	{
180
+		return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
181
+			$messenger_names,
182
+			$message_type_names
183
+		);
184
+	}
185
+
186
+
187
+	/**
188
+	 * The purpose of this function is to return all installed message objects
189
+	 * (messengers and message type regardless of whether they are ACTIVE or not)
190
+	 *
191
+	 * @param string $type
192
+	 * @return array array consisting of installed messenger objects and installed message type objects.
193
+	 * @throws EE_Error
194
+	 * @throws ReflectionException
195
+	 * @deprecated 4.9.0
196
+	 * @static
197
+	 */
198
+	public static function get_installed_message_objects($type = 'all')
199
+	{
200
+		self::_set_autoloader();
201
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
202
+		return array(
203
+			'messenger' => $message_resource_manager->installed_messengers(),
204
+			'message_type' => $message_resource_manager->installed_message_types()
205
+		);
206
+	}
207
+
208
+
209
+	/**
210
+	 * This will return an array of shortcodes => labels from the
211
+	 * messenger and message_type objects associated with this
212
+	 * template.
213
+	 *
214
+	 * @param string $message_type
215
+	 * @param string $messenger
216
+	 * @param array  $fields                        What fields we're returning valid shortcodes for.
217
+	 *                                              If empty then we assume all fields are to be returned. Optional.
218
+	 * @param string $context                       What context we're going to return shortcodes for. Optional.
219
+	 * @param bool   $merged                        If TRUE then we don't return shortcodes indexed by field,
220
+	 *                                              but instead an array of the unique shortcodes for all the given (
221
+	 *                                              or all) fields. Optional.
222
+	 * @return array                                an array of shortcodes in the format
223
+	 *                                              array( '[shortcode] => 'label')
224
+	 *                                              OR
225
+	 *                                              FALSE if no shortcodes found.
226
+	 * @throws ReflectionException
227
+	 * @throws EE_Error*@since 4.3.0
228
+	 *
229
+	 */
230
+	public static function get_shortcodes(
231
+		$message_type,
232
+		$messenger,
233
+		$fields = array(),
234
+		$context = 'admin',
235
+		$merged = false
236
+	) {
237
+		$messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
238
+		$mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
239
+		/** @var EE_Message_Resource_Manager $message_resource_manager */
240
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
241
+		// convert slug to object
242
+		$messenger = $message_resource_manager->get_messenger($messenger);
243
+
244
+		// if messenger isn't a EE_messenger resource then bail.
245
+		if (! $messenger instanceof EE_messenger) {
246
+			return array();
247
+		}
248
+
249
+		// validate class for getting our list of shortcodes
250
+		$classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
251
+		if (! class_exists($classname)) {
252
+			$msg[] = esc_html__('The Validator class was unable to load', 'event_espresso');
253
+			$msg[] = sprintf(
254
+				esc_html__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
255
+				$classname
256
+			);
257
+			throw new EE_Error(implode('||', $msg));
258
+		}
259
+
260
+		/** @type EE_Messages_Validator $_VLD */
261
+		$_VLD = new $classname(array(), $context);
262
+		$valid_shortcodes = $_VLD->get_validators();
263
+
264
+		// let's make sure we're only getting the shortcode part of the validators
265
+		$shortcodes = array();
266
+		foreach ($valid_shortcodes as $field => $validators) {
267
+			$shortcodes[ $field ] = $validators['shortcodes'];
268
+		}
269
+		$valid_shortcodes = $shortcodes;
270
+
271
+		// if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
272
+		if (! empty($fields)) {
273
+			$specified_shortcodes = array();
274
+			foreach ($fields as $field) {
275
+				if (isset($valid_shortcodes[ $field ])) {
276
+					$specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
277
+				}
278
+			}
279
+			$valid_shortcodes = $specified_shortcodes;
280
+		}
281
+
282
+		// if not merged then let's replace the fields with the localized fields
283
+		if (! $merged) {
284
+			// let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
285
+			$field_settings = $messenger->get_template_fields();
286
+			$localized = array();
287
+			foreach ($valid_shortcodes as $field => $shortcodes) {
288
+				// get localized field label
289
+				if (isset($field_settings[ $field ])) {
290
+					// possible that this is used as a main field.
291
+					if (empty($field_settings[ $field ])) {
292
+						if (isset($field_settings['extra'][ $field ])) {
293
+							$_field = $field_settings['extra'][ $field ]['main']['label'];
294
+						} else {
295
+							$_field = $field;
296
+						}
297
+					} else {
298
+						$_field = $field_settings[ $field ]['label'];
299
+					}
300
+				} elseif (isset($field_settings['extra'])) {
301
+					// loop through extra "main fields" and see if any of their children have our field
302
+					foreach ($field_settings['extra'] as $fields) {
303
+						if (isset($fields[ $field ])) {
304
+							$_field = $fields[ $field ]['label'];
305
+						} else {
306
+							$_field = $field;
307
+						}
308
+					}
309
+				} else {
310
+					$_field = $field;
311
+				}
312
+				if (isset($_field)) {
313
+					$localized[ (string) $_field ] = $shortcodes;
314
+				}
315
+			}
316
+			$valid_shortcodes = $localized;
317
+		}
318
+
319
+		// if $merged then let's merge all the shortcodes into one list NOT indexed by field.
320
+		if ($merged) {
321
+			$merged_codes = array();
322
+			foreach ($valid_shortcodes as $shortcode) {
323
+				foreach ($shortcode as $code => $label) {
324
+					if (isset($merged_codes[ $code ])) {
325
+						continue;
326
+					} else {
327
+						$merged_codes[ $code ] = $label;
328
+					}
329
+				}
330
+			}
331
+			$valid_shortcodes = $merged_codes;
332
+		}
333
+
334
+		return $valid_shortcodes;
335
+	}
336
+
337
+
338
+	/**
339
+	 * Get Messenger object.
340
+	 *
341
+	 * @param string $messenger messenger slug for the messenger object we want to retrieve.
342
+	 * @return EE_messenger
343
+	 * @throws ReflectionException
344
+	 * @throws EE_Error*@since 4.3.0
345
+	 * @deprecated 4.9.0
346
+	 */
347
+	public static function messenger_obj($messenger)
348
+	{
349
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
350
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
351
+		return $Message_Resource_Manager->get_messenger($messenger);
352
+	}
353
+
354
+
355
+	/**
356
+	 * get Message type object
357
+	 *
358
+	 * @param string $message_type the slug for the message type object to retrieve
359
+	 * @return EE_message_type
360
+	 * @throws ReflectionException
361
+	 * @throws EE_Error*@since 4.3.0
362
+	 * @deprecated 4.9.0
363
+	 */
364
+	public static function message_type_obj($message_type)
365
+	{
366
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
367
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
368
+		return $Message_Resource_Manager->get_message_type($message_type);
369
+	}
370
+
371
+
372
+	/**
373
+	 * Given a message_type slug, will return whether that message type is active in the system or not.
374
+	 *
375
+	 * @since    4.3.0
376
+	 * @param string $message_type message type to check for.
377
+	 * @return boolean
378
+	 * @throws EE_Error
379
+	 * @throws ReflectionException
380
+	 */
381
+	public static function is_mt_active($message_type)
382
+	{
383
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
384
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
385
+		$active_mts = $Message_Resource_Manager->list_of_active_message_types();
386
+		return in_array($message_type, $active_mts);
387
+	}
388
+
389
+
390
+	/**
391
+	 * Given a messenger slug, will return whether that messenger is active in the system or not.
392
+	 *
393
+	 * @since    4.3.0
394
+	 *
395
+	 * @param string $messenger slug for messenger to check.
396
+	 * @return boolean
397
+	 * @throws EE_Error
398
+	 * @throws ReflectionException
399
+	 */
400
+	public static function is_messenger_active($messenger)
401
+	{
402
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
403
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
404
+		$active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
405
+		return $active_messenger instanceof EE_messenger;
406
+	}
407
+
408
+
409
+	/**
410
+	 * Used to return active messengers array stored in the wp options table.
411
+	 * If no value is present in the option then an empty array is returned.
412
+	 *
413
+	 * @deprecated 4.9
414
+	 * @since      4.3.1
415
+	 *
416
+	 * @return array
417
+	 * @throws EE_Error
418
+	 * @throws ReflectionException
419
+	 */
420
+	public static function get_active_messengers_in_db()
421
+	{
422
+		EE_Error::doing_it_wrong(
423
+			__METHOD__,
424
+			esc_html__('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
425
+			'4.9.0'
426
+		);
427
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
428
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
429
+		return $Message_Resource_Manager->get_active_messengers_option();
430
+	}
431
+
432
+
433
+	/**
434
+	 * Used to update the active messengers array stored in the wp options table.
435
+	 *
436
+	 * @since      4.3.1
437
+	 * @deprecated 4.9.0
438
+	 *
439
+	 * @param array $data_to_save Incoming data to save.
440
+	 *
441
+	 * @return bool FALSE if not updated, TRUE if updated.
442
+	 * @throws EE_Error
443
+	 * @throws ReflectionException
444
+	 */
445
+	public static function update_active_messengers_in_db($data_to_save)
446
+	{
447
+		EE_Error::doing_it_wrong(
448
+			__METHOD__,
449
+			esc_html__('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
450
+			'4.9.0'
451
+		);
452
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
453
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
454
+		return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
455
+	}
456
+
457
+
458
+	/**
459
+	 * This does some validation of incoming params, determines what type of url is being prepped and returns the
460
+	 * appropriate url trigger
461
+	 *
462
+	 * @param EE_message_type $message_type
463
+	 * @param EE_Message $message
464
+	 * @param EE_Registration | null $registration  The registration object must be included if this
465
+	 *                                              is going to be a registration trigger url.
466
+	 * @param string $sending_messenger             The (optional) sending messenger for the url.
467
+	 *
468
+	 * @return string
469
+	 * @throws EE_Error
470
+	 */
471
+	public static function get_url_trigger(
472
+		EE_message_type $message_type,
473
+		EE_Message $message,
474
+		$registration = null,
475
+		$sending_messenger = ''
476
+	) {
477
+		// first determine if the url can be to the EE_Message object.
478
+		if (! $message_type->always_generate()) {
479
+			return EEH_MSG_Template::generate_browser_trigger($message);
480
+		}
481
+
482
+		// if $registration object is not valid then exit early because there's nothing that can be generated.
483
+		if (! $registration instanceof EE_Registration) {
484
+			throw new EE_Error(
485
+				esc_html__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
486
+			);
487
+		}
488
+
489
+		// validate given context
490
+		$contexts = $message_type->get_contexts();
491
+		if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
492
+			throw new EE_Error(
493
+				sprintf(
494
+					esc_html__('The context %s is not a valid context for %s.', 'event_espresso'),
495
+					$message->context(),
496
+					get_class($message_type)
497
+				)
498
+			);
499
+		}
500
+
501
+		// valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
502
+		if (! empty($sending_messenger)) {
503
+			$with_messengers = $message_type->with_messengers();
504
+			if (
505
+				! isset($with_messengers[ $message->messenger() ])
506
+				 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])
507
+			) {
508
+				throw new EE_Error(
509
+					sprintf(
510
+						esc_html__(
511
+							'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
512
+							'event_espresso'
513
+						),
514
+						$sending_messenger,
515
+						get_class($message_type)
516
+					)
517
+				);
518
+			}
519
+		} else {
520
+			$sending_messenger = $message->messenger();
521
+		}
522
+		return EEH_MSG_Template::generate_url_trigger(
523
+			$sending_messenger,
524
+			$message->messenger(),
525
+			$message->context(),
526
+			$message->message_type(),
527
+			$registration,
528
+			$message->GRP_ID()
529
+		);
530
+	}
531
+
532
+
533
+	/**
534
+	 * This returns the url for triggering a in browser view of a specific EE_Message object.
535
+	 * @param EE_Message $message
536
+	 * @return string.
537
+	 */
538
+	public static function generate_browser_trigger(EE_Message $message)
539
+	{
540
+		$query_args = array(
541
+			'ee' => 'msg_browser_trigger',
542
+			'token' => $message->MSG_token()
543
+		);
544
+		return apply_filters(
545
+			'FHEE__EEH_MSG_Template__generate_browser_trigger',
546
+			add_query_arg($query_args, site_url()),
547
+			$message
548
+		);
549
+	}
550
+
551
+
552
+
553
+
554
+
555
+
556
+	/**
557
+	 * This returns the url for triggering an in browser view of the error saved on the incoming message object.
558
+	 * @param EE_Message $message
559
+	 * @return string
560
+	 */
561
+	public static function generate_error_display_trigger(EE_Message $message)
562
+	{
563
+		return apply_filters(
564
+			'FHEE__EEH_MSG_Template__generate_error_display_trigger',
565
+			add_query_arg(
566
+				array(
567
+					'ee' => 'msg_browser_error_trigger',
568
+					'token' => $message->MSG_token()
569
+				),
570
+				site_url()
571
+			),
572
+			$message
573
+		);
574
+	}
575
+
576
+
577
+	/**
578
+	 * This generates a url trigger for the msg_url_trigger route using the given arguments
579
+	 *
580
+	 * @param string          $sending_messenger      The sending messenger slug.
581
+	 * @param string          $generating_messenger   The generating messenger slug.
582
+	 * @param string          $context                The context for the template.
583
+	 * @param string          $message_type           The message type slug
584
+	 * @param EE_Registration $registration
585
+	 * @param integer         $message_template_group id   The EE_Message_Template_Group ID for the template.
586
+	 * @param integer         $data_id                The id to the EE_Base_Class for getting the data used by the
587
+	 *                                                trigger.
588
+	 * @return string          The generated url.
589
+	 * @throws EE_Error
590
+	 */
591
+	public static function generate_url_trigger(
592
+		$sending_messenger,
593
+		$generating_messenger,
594
+		$context,
595
+		$message_type,
596
+		EE_Registration $registration,
597
+		$message_template_group,
598
+		$data_id = 0
599
+	) {
600
+		$query_args = array(
601
+			'ee' => 'msg_url_trigger',
602
+			'snd_msgr' => $sending_messenger,
603
+			'gen_msgr' => $generating_messenger,
604
+			'message_type' => $message_type,
605
+			'context' => $context,
606
+			'token' => $registration->reg_url_link(),
607
+			'GRP_ID' => $message_template_group,
608
+			'id' => $data_id
609
+			);
610
+		$url = add_query_arg($query_args, get_home_url());
611
+
612
+		// made it here so now we can just get the url and filter it.  Filtered globally and by message type.
613
+		return apply_filters(
614
+			'FHEE__EEH_MSG_Template__generate_url_trigger',
615
+			$url,
616
+			$sending_messenger,
617
+			$generating_messenger,
618
+			$context,
619
+			$message_type,
620
+			$registration,
621
+			$message_template_group,
622
+			$data_id
623
+		);
624
+	}
625
+
626
+
627
+
628
+
629
+	/**
630
+	 * Return the specific css for the action icon given.
631
+	 *
632
+	 * @param string $type  What action to return.
633
+	 * @return string[]
634
+	 * @since 4.9.0
635
+	 */
636
+	public static function get_message_action_icon($type)
637
+	{
638
+		$action_icons = self::get_message_action_icons();
639
+		return isset($action_icons[ $type ]) ? $action_icons[ $type ] : [];
640
+	}
641
+
642
+
643
+	/**
644
+	 * This is used for retrieving the css classes used for the icons representing message actions.
645
+	 *
646
+	 * @since 4.9.0
647
+	 *
648
+	 * @return array
649
+	 */
650
+	public static function get_message_action_icons()
651
+	{
652
+		return apply_filters(
653
+			'FHEE__EEH_MSG_Template__message_action_icons',
654
+			array(
655
+				'view' => array(
656
+					'label' => esc_html__('View Message', 'event_espresso'),
657
+					'css_class' => 'dashicons dashicons-visibility',
658
+				),
659
+				'error' => array(
660
+					'label' => esc_html__('View Error Message', 'event_espresso'),
661
+					'css_class' => 'dashicons dashicons-info',
662
+				),
663
+				'see_notifications_for' => array(
664
+					'label' => esc_html__('View Related Messages', 'event_espresso'),
665
+					'css_class' => 'dashicons dashicons-megaphone',
666
+				),
667
+				'generate_now' => array(
668
+					'label' => esc_html__('Generate the message now.', 'event_espresso'),
669
+					'css_class' => 'dashicons dashicons-admin-tools',
670
+				),
671
+				'send_now' => array(
672
+					'label' => esc_html__('Send Immediately', 'event_espresso'),
673
+					'css_class' => 'dashicons dashicons-controls-forward',
674
+				),
675
+				'queue_for_resending' => array(
676
+					'label' => esc_html__('Queue for Resending', 'event_espresso'),
677
+					'css_class' => 'dashicons dashicons-controls-repeat',
678
+				),
679
+				'view_transaction' => array(
680
+					'label' => esc_html__('View related Transaction', 'event_espresso'),
681
+					'css_class' => 'dashicons dashicons-cart',
682
+				)
683
+			)
684
+		);
685
+	}
686
+
687
+
688
+	/**
689
+	 * This returns the url for a given action related to EE_Message.
690
+	 *
691
+	 * @param string     $type         What type of action to return the url for.
692
+	 * @param EE_Message $message      Required for generating the correct url for some types.
693
+	 * @param array      $query_params Any additional query params to be included with the generated url.
694
+	 *
695
+	 * @return string
696
+	 * @throws EE_Error
697
+	 * @throws ReflectionException
698
+	 * @since 4.9.0
699
+	 *
700
+	 */
701
+	public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
702
+	{
703
+		$action_urls = self::get_message_action_urls($message, $query_params);
704
+		return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
705
+	}
706
+
707
+
708
+	/**
709
+	 * This returns all the current urls for EE_Message actions.
710
+	 *
711
+	 * @since 4.9.0
712
+	 *
713
+	 * @param EE_Message $message      The EE_Message object required to generate correct urls for some types.
714
+	 * @param array      $query_params Any additional query_params to be included with the generated url.
715
+	 *
716
+	 * @return array
717
+	 * @throws EE_Error
718
+	 * @throws ReflectionException
719
+	 */
720
+	public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
721
+	{
722
+		EE_Registry::instance()->load_helper('URL');
723
+		// if $message is not an instance of EE_Message then let's just do a dummy.
724
+		$message = empty($message) ? EE_Message_Factory::create() : $message;
725
+		$action_urls =  apply_filters(
726
+			'FHEE__EEH_MSG_Template__get_message_action_url',
727
+			array(
728
+				'view' => EEH_MSG_Template::generate_browser_trigger($message),
729
+				'error' => EEH_MSG_Template::generate_error_display_trigger($message),
730
+				'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
731
+					array_merge(
732
+						array(
733
+							'page' => 'espresso_messages',
734
+							'action' => 'default',
735
+							'filterby' => 1,
736
+						),
737
+						$query_params
738
+					),
739
+					admin_url('admin.php')
740
+				),
741
+				'generate_now' => EEH_URL::add_query_args_and_nonce(
742
+					array(
743
+						'page' => 'espresso_messages',
744
+						'action' => 'generate_now',
745
+						'MSG_ID' => $message->ID()
746
+					),
747
+					admin_url('admin.php')
748
+				),
749
+				'send_now' => EEH_URL::add_query_args_and_nonce(
750
+					array(
751
+						'page' => 'espresso_messages',
752
+						'action' => 'send_now',
753
+						'MSG_ID' => $message->ID()
754
+					),
755
+					admin_url('admin.php')
756
+				),
757
+				'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
758
+					array(
759
+						'page' => 'espresso_messages',
760
+						'action' => 'queue_for_resending',
761
+						'MSG_ID' => $message->ID()
762
+					),
763
+					admin_url('admin.php')
764
+				),
765
+			)
766
+		);
767
+		if (
768
+			$message->TXN_ID() > 0
769
+			&& EE_Registry::instance()->CAP->current_user_can(
770
+				'ee_read_transaction',
771
+				'espresso_transactions_default',
772
+				$message->TXN_ID()
773
+			)
774
+		) {
775
+			$action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
776
+				array(
777
+					'page' => 'espresso_transactions',
778
+					'action' => 'view_transaction',
779
+					'TXN_ID' => $message->TXN_ID()
780
+				),
781
+				admin_url('admin.php')
782
+			);
783
+		} else {
784
+			$action_urls['view_transaction'] = '';
785
+		}
786
+		return $action_urls;
787
+	}
788
+
789
+
790
+	/**
791
+	 * This returns a generated link html including the icon used for the action link for EE_Message actions.
792
+	 *
793
+	 * @param string          $type         What type of action the link is for (if invalid type is passed in then an
794
+	 *                                      empty string is returned)
795
+	 * @param EE_Message|null $message      The EE_Message object (required for some actions to generate correctly)
796
+	 * @param array           $query_params Any extra query params to include in the generated link.
797
+	 *
798
+	 * @return string
799
+	 * @throws EE_Error
800
+	 * @throws ReflectionException
801
+	 * @since 4.9.0
802
+	 *
803
+	 */
804
+	public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
805
+	{
806
+		$url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
807
+		$icon_css = EEH_MSG_Template::get_message_action_icon($type);
808
+		$label = $icon_css['label'] ?? null;
809
+		$label = $label ? 'aria-label="' . $label . '"' : '';
810
+		$class = $label ? ' ee-aria-tooltip' : '';
811
+
812
+		if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
813
+			return '';
814
+		}
815
+
816
+		$icon_css['css_class'] .= esc_attr(
817
+			apply_filters(
818
+				'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
819
+				' js-ee-message-action-link ee-message-action-link-' . $type,
820
+				$type,
821
+				$message,
822
+				$query_params
823
+			)
824
+		);
825
+
826
+		return '
827 827
             <a href="' . $url . '" ' . $label . ' class="button button--icon-only' . $class . '">
828 828
                 <span class="' . esc_attr($icon_css['css_class']) . '"></span>
829 829
             </a>';
830
-    }
831
-
832
-
833
-
834
-
835
-
836
-    /**
837
-     * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
838
-     *
839
-     * @since 4.9.0
840
-     * @return array
841
-     */
842
-    public static function reg_status_to_message_type_array()
843
-    {
844
-        return (array) apply_filters(
845
-            'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
846
-            array(
847
-                EEM_Registration::status_id_approved => 'registration',
848
-                EEM_Registration::status_id_pending_payment => 'pending_approval',
849
-                EEM_Registration::status_id_not_approved => 'not_approved_registration',
850
-                EEM_Registration::status_id_cancelled => 'cancelled_registration',
851
-                EEM_Registration::status_id_declined => 'declined_registration'
852
-            )
853
-        );
854
-    }
855
-
856
-
857
-
858
-
859
-    /**
860
-     * This returns the corresponding registration message type slug to the given reg status. If there isn't a
861
-     * match, then returns an empty string.
862
-     *
863
-     * @since 4.9.0
864
-     * @param $reg_status
865
-     * @return string
866
-     */
867
-    public static function convert_reg_status_to_message_type($reg_status)
868
-    {
869
-        $reg_status_array = self::reg_status_to_message_type_array();
870
-        return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
871
-    }
872
-
873
-
874
-    /**
875
-     * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
876
-     *
877
-     * @since 4.9.0
878
-     * @return array
879
-     */
880
-    public static function payment_status_to_message_type_array()
881
-    {
882
-        return (array) apply_filters(
883
-            'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
884
-            array(
885
-                EEM_Payment::status_id_approved => 'payment',
886
-                EEM_Payment::status_id_pending => 'payment_pending',
887
-                EEM_Payment::status_id_cancelled => 'payment_cancelled',
888
-                EEM_Payment::status_id_declined => 'payment_declined',
889
-                EEM_Payment::status_id_failed => 'payment_failed'
890
-            )
891
-        );
892
-    }
893
-
894
-
895
-
896
-
897
-    /**
898
-     * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
899
-     * an empty string is returned
900
-     *
901
-     * @since 4.9.0
902
-     * @param $payment_status
903
-     * @return string
904
-     */
905
-    public static function convert_payment_status_to_message_type($payment_status)
906
-    {
907
-        $payment_status_array = self::payment_status_to_message_type_array();
908
-        return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
909
-    }
910
-
911
-
912
-    /**
913
-     * This is used to retrieve the template pack for the given name.
914
-     *
915
-     * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
916
-     *
917
-     * @return EE_Messages_Template_Pack
918
-     */
919
-    public static function get_template_pack($template_pack_name)
920
-    {
921
-        if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
922
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
923
-        }
924
-
925
-        // first see if in collection already
926
-        $template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
927
-
928
-        if ($template_pack instanceof EE_Messages_Template_Pack) {
929
-            return $template_pack;
930
-        }
931
-
932
-        // nope...let's get it.
933
-        // not set yet so let's attempt to get it.
934
-        $pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
935
-            ' ',
936
-            '_',
937
-            ucwords(
938
-                str_replace('_', ' ', $template_pack_name)
939
-            )
940
-        );
941
-        if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
942
-            return self::get_template_pack('default');
943
-        } else {
944
-            $template_pack = new $pack_class_name();
945
-            self::$_template_pack_collection->add($template_pack);
946
-            return $template_pack;
947
-        }
948
-    }
949
-
950
-
951
-
952
-
953
-    /**
954
-     * Globs template packs installed in core and returns the template pack collection with all installed template packs
955
-     * in it.
956
-     *
957
-     * @since 4.9.0
958
-     *
959
-     * @return EE_Messages_Template_Pack_Collection
960
-     */
961
-    public static function get_template_pack_collection()
962
-    {
963
-        $new_collection = false;
964
-        if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
965
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
966
-            $new_collection = true;
967
-        }
968
-
969
-        // glob the defaults directory for messages
970
-        $templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
971
-        foreach ($templates as $template_path) {
972
-            // grab folder name
973
-            $template = basename($template_path);
974
-
975
-            if (! $new_collection) {
976
-                // already have it?
977
-                if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
978
-                    continue;
979
-                }
980
-            }
981
-
982
-            // setup classname.
983
-            $template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
984
-                ' ',
985
-                '_',
986
-                ucwords(
987
-                    str_replace(
988
-                        '_',
989
-                        ' ',
990
-                        $template
991
-                    )
992
-                )
993
-            );
994
-            if (! class_exists($template_pack_class_name)) {
995
-                continue;
996
-            }
997
-            self::$_template_pack_collection->add(new $template_pack_class_name());
998
-        }
999
-
1000
-        /**
1001
-         * Filter for plugins to add in any additional template packs
1002
-         * Note the filter name here is for backward compat, this used to be found in EED_Messages.
1003
-         */
1004
-        $additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
1005
-        foreach ((array) $additional_template_packs as $template_pack) {
1006
-            if (
1007
-                self::$_template_pack_collection->get_by_name(
1008
-                    $template_pack->dbref
1009
-                ) instanceof EE_Messages_Template_Pack
1010
-            ) {
1011
-                continue;
1012
-            }
1013
-            self::$_template_pack_collection->add($template_pack);
1014
-        }
1015
-        return self::$_template_pack_collection;
1016
-    }
1017
-
1018
-
1019
-    /**
1020
-     * This is a wrapper for the protected _create_new_templates function
1021
-     *
1022
-     * @param string $messenger_name
1023
-     * @param string $message_type_name message type that the templates are being created for
1024
-     * @param int    $GRP_ID
1025
-     * @param bool   $global
1026
-     * @return array
1027
-     * @throws EE_Error
1028
-     * @throws ReflectionException
1029
-     */
1030
-    public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1031
-    {
1032
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1033
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1034
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1035
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1036
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1037
-            return array();
1038
-        }
1039
-        // whew made it this far!  Okay, let's go ahead and create the templates then
1040
-        return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1041
-    }
1042
-
1043
-
1044
-    /**
1045
-     * @param EE_messenger     $messenger
1046
-     * @param EE_message_type  $message_type
1047
-     * @param                  $GRP_ID
1048
-     * @param                  $global
1049
-     * @return array|mixed
1050
-     * @throws EE_Error
1051
-     * @throws ReflectionException
1052
-     */
1053
-    protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1054
-    {
1055
-        // if we're creating a custom template then we don't need to use the defaults class
1056
-        if (! $global) {
1057
-            return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1058
-        }
1059
-        /** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1060
-        $Message_Template_Defaults = EE_Registry::factory(
1061
-            'EE_Messages_Template_Defaults',
1062
-            array( $messenger, $message_type, $GRP_ID )
1063
-        );
1064
-        // generate templates
1065
-        $success = $Message_Template_Defaults->create_new_templates();
1066
-
1067
-        // if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1068
-        // its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1069
-        // attempts.
1070
-        if (! $success) {
1071
-            /** @var EE_Message_Resource_Manager $message_resource_manager */
1072
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1073
-            $message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1074
-        }
1075
-
1076
-        /**
1077
-         * $success is in an array in the following format
1078
-         * array(
1079
-         *    'GRP_ID' => $new_grp_id,
1080
-         *    'MTP_context' => $first_context_in_new_templates,
1081
-         * )
1082
-         */
1083
-        return $success;
1084
-    }
1085
-
1086
-
1087
-    /**
1088
-     * This creates a custom template using the incoming GRP_ID
1089
-     *
1090
-     * @param EE_messenger    $messenger
1091
-     * @param EE_message_type $message_type
1092
-     * @param int             $GRP_ID           GRP_ID for the template_group being used as the base
1093
-     * @return  array $success              This will be an array in the format:
1094
-     *                                          array(
1095
-     *                                          'GRP_ID' => $new_grp_id,
1096
-     *                                          'MTP_context' => $first_context_in_created_template
1097
-     *                                          )
1098
-     * @throws EE_Error
1099
-     * @throws ReflectionException
1100
-     * @access private
1101
-     */
1102
-    private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1103
-    {
1104
-        // defaults
1105
-        $success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1106
-        // get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1107
-        $Message_Template_Group = empty($GRP_ID)
1108
-            ? EEM_Message_Template_Group::instance()->get_one(
1109
-                array(
1110
-                    array(
1111
-                        'MTP_messenger'    => $messenger->name,
1112
-                        'MTP_message_type' => $message_type->name,
1113
-                        'MTP_is_global'    => true
1114
-                    )
1115
-                )
1116
-            )
1117
-            : EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1118
-        // if we don't have a mtg at this point then we need to bail.
1119
-        if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1120
-            EE_Error::add_error(
1121
-                sprintf(
1122
-                    esc_html__(
1123
-                        'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1124
-                        'event_espresso'
1125
-                    ),
1126
-                    $GRP_ID
1127
-                ),
1128
-                __FILE__,
1129
-                __FUNCTION__,
1130
-                __LINE__
1131
-            );
1132
-            return $success;
1133
-        }
1134
-        // let's get all the related message_template objects for this group.
1135
-        $message_templates = $Message_Template_Group->message_templates();
1136
-        // now we have what we need to setup the new template
1137
-        $new_mtg = clone $Message_Template_Group;
1138
-        $new_mtg->set('GRP_ID', 0);
1139
-        $new_mtg->set('MTP_is_global', false);
1140
-
1141
-        /** @var RequestInterface $request */
1142
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
1143
-        $template_name = $request->isAjax() && $request->requestParamIsSet('templateName')
1144
-            ? $request->getRequestParam('templateName')
1145
-            : esc_html__('New Custom Template', 'event_espresso');
1146
-        $template_description = $request->isAjax() && $request->requestParamIsSet('templateDescription')
1147
-            ? $request->getRequestParam('templateDescription')
1148
-            : sprintf(
1149
-                esc_html__(
1150
-                    'This is a custom template that was created for the %s messenger and %s message type.',
1151
-                    'event_espresso'
1152
-                ),
1153
-                $new_mtg->messenger_obj()->label['singular'],
1154
-                $new_mtg->message_type_obj()->label['singular']
1155
-            );
1156
-        $new_mtg->set('MTP_name', $template_name);
1157
-        $new_mtg->set('MTP_description', $template_description);
1158
-        // remove ALL relations on this template group so they don't get saved!
1159
-        $new_mtg->_remove_relations('Message_Template');
1160
-        $new_mtg->save();
1161
-        $success['GRP_ID'] = $new_mtg->ID();
1162
-        $success['template_name'] = $template_name;
1163
-        // add new message templates and add relation to.
1164
-        foreach ($message_templates as $message_template) {
1165
-            if (! $message_template instanceof EE_Message_Template) {
1166
-                continue;
1167
-            }
1168
-            $new_message_template = clone $message_template;
1169
-            $new_message_template->set('MTP_ID', 0);
1170
-            $new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1171
-            $new_message_template->save();
1172
-            if (empty($success['MTP_context']) && $new_message_template->get('MTP_context') !== 'admin') {
1173
-                $success['MTP_context'] = $new_message_template->get('MTP_context');
1174
-            }
1175
-        }
1176
-        return $success;
1177
-    }
1178
-
1179
-
1180
-    /**
1181
-     * message_type_has_active_templates_for_messenger
1182
-     *
1183
-     * @param EE_messenger    $messenger
1184
-     * @param EE_message_type $message_type
1185
-     * @param bool            $global
1186
-     * @return bool
1187
-     * @throws EE_Error
1188
-     */
1189
-    public static function message_type_has_active_templates_for_messenger(
1190
-        EE_messenger $messenger,
1191
-        EE_message_type $message_type,
1192
-        $global = false
1193
-    ) {
1194
-        // is given message_type valid for given messenger (if this is not a global save)
1195
-        if ($global) {
1196
-            return true;
1197
-        }
1198
-        $active_templates = EEM_Message_Template_Group::instance()->count(
1199
-            array(
1200
-                array(
1201
-                    'MTP_is_active'    => true,
1202
-                    'MTP_messenger'    => $messenger->name,
1203
-                    'MTP_message_type' => $message_type->name
1204
-                )
1205
-            )
1206
-        );
1207
-        if ($active_templates > 0) {
1208
-            return true;
1209
-        }
1210
-        EE_Error::add_error(
1211
-            sprintf(
1212
-                esc_html__(
1213
-                    'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1214
-                    'event_espresso'
1215
-                ),
1216
-                $message_type->name,
1217
-                $messenger->name
1218
-            ),
1219
-            __FILE__,
1220
-            __FUNCTION__,
1221
-            __LINE__
1222
-        );
1223
-        return false;
1224
-    }
1225
-
1226
-
1227
-    /**
1228
-     * get_fields
1229
-     * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1230
-     *
1231
-     * @param string $messenger_name    name of EE_messenger
1232
-     * @param string $message_type_name name of EE_message_type
1233
-     * @return array
1234
-     * @throws EE_Error
1235
-     * @throws ReflectionException
1236
-     */
1237
-    public static function get_fields($messenger_name, $message_type_name)
1238
-    {
1239
-        $template_fields = array();
1240
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1241
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1242
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1243
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1244
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1245
-            return array();
1246
-        }
1247
-
1248
-        $excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1249
-
1250
-        // okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1251
-        foreach ($message_type->get_contexts() as $context => $details) {
1252
-            foreach ($messenger->get_template_fields() as $field => $value) {
1253
-                if (in_array($field, $excluded_fields_for_messenger, true)) {
1254
-                    continue;
1255
-                }
1256
-                $template_fields[ $context ][ $field ] = $value;
1257
-            }
1258
-        }
1259
-        if (empty($template_fields)) {
1260
-            EE_Error::add_error(
1261
-                esc_html__('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1262
-                __FILE__,
1263
-                __FUNCTION__,
1264
-                __LINE__
1265
-            );
1266
-            return array();
1267
-        }
1268
-        return $template_fields;
1269
-    }
830
+	}
831
+
832
+
833
+
834
+
835
+
836
+	/**
837
+	 * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
838
+	 *
839
+	 * @since 4.9.0
840
+	 * @return array
841
+	 */
842
+	public static function reg_status_to_message_type_array()
843
+	{
844
+		return (array) apply_filters(
845
+			'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
846
+			array(
847
+				EEM_Registration::status_id_approved => 'registration',
848
+				EEM_Registration::status_id_pending_payment => 'pending_approval',
849
+				EEM_Registration::status_id_not_approved => 'not_approved_registration',
850
+				EEM_Registration::status_id_cancelled => 'cancelled_registration',
851
+				EEM_Registration::status_id_declined => 'declined_registration'
852
+			)
853
+		);
854
+	}
855
+
856
+
857
+
858
+
859
+	/**
860
+	 * This returns the corresponding registration message type slug to the given reg status. If there isn't a
861
+	 * match, then returns an empty string.
862
+	 *
863
+	 * @since 4.9.0
864
+	 * @param $reg_status
865
+	 * @return string
866
+	 */
867
+	public static function convert_reg_status_to_message_type($reg_status)
868
+	{
869
+		$reg_status_array = self::reg_status_to_message_type_array();
870
+		return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
871
+	}
872
+
873
+
874
+	/**
875
+	 * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
876
+	 *
877
+	 * @since 4.9.0
878
+	 * @return array
879
+	 */
880
+	public static function payment_status_to_message_type_array()
881
+	{
882
+		return (array) apply_filters(
883
+			'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
884
+			array(
885
+				EEM_Payment::status_id_approved => 'payment',
886
+				EEM_Payment::status_id_pending => 'payment_pending',
887
+				EEM_Payment::status_id_cancelled => 'payment_cancelled',
888
+				EEM_Payment::status_id_declined => 'payment_declined',
889
+				EEM_Payment::status_id_failed => 'payment_failed'
890
+			)
891
+		);
892
+	}
893
+
894
+
895
+
896
+
897
+	/**
898
+	 * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
899
+	 * an empty string is returned
900
+	 *
901
+	 * @since 4.9.0
902
+	 * @param $payment_status
903
+	 * @return string
904
+	 */
905
+	public static function convert_payment_status_to_message_type($payment_status)
906
+	{
907
+		$payment_status_array = self::payment_status_to_message_type_array();
908
+		return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
909
+	}
910
+
911
+
912
+	/**
913
+	 * This is used to retrieve the template pack for the given name.
914
+	 *
915
+	 * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
916
+	 *
917
+	 * @return EE_Messages_Template_Pack
918
+	 */
919
+	public static function get_template_pack($template_pack_name)
920
+	{
921
+		if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
922
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
923
+		}
924
+
925
+		// first see if in collection already
926
+		$template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
927
+
928
+		if ($template_pack instanceof EE_Messages_Template_Pack) {
929
+			return $template_pack;
930
+		}
931
+
932
+		// nope...let's get it.
933
+		// not set yet so let's attempt to get it.
934
+		$pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
935
+			' ',
936
+			'_',
937
+			ucwords(
938
+				str_replace('_', ' ', $template_pack_name)
939
+			)
940
+		);
941
+		if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
942
+			return self::get_template_pack('default');
943
+		} else {
944
+			$template_pack = new $pack_class_name();
945
+			self::$_template_pack_collection->add($template_pack);
946
+			return $template_pack;
947
+		}
948
+	}
949
+
950
+
951
+
952
+
953
+	/**
954
+	 * Globs template packs installed in core and returns the template pack collection with all installed template packs
955
+	 * in it.
956
+	 *
957
+	 * @since 4.9.0
958
+	 *
959
+	 * @return EE_Messages_Template_Pack_Collection
960
+	 */
961
+	public static function get_template_pack_collection()
962
+	{
963
+		$new_collection = false;
964
+		if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
965
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
966
+			$new_collection = true;
967
+		}
968
+
969
+		// glob the defaults directory for messages
970
+		$templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
971
+		foreach ($templates as $template_path) {
972
+			// grab folder name
973
+			$template = basename($template_path);
974
+
975
+			if (! $new_collection) {
976
+				// already have it?
977
+				if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
978
+					continue;
979
+				}
980
+			}
981
+
982
+			// setup classname.
983
+			$template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
984
+				' ',
985
+				'_',
986
+				ucwords(
987
+					str_replace(
988
+						'_',
989
+						' ',
990
+						$template
991
+					)
992
+				)
993
+			);
994
+			if (! class_exists($template_pack_class_name)) {
995
+				continue;
996
+			}
997
+			self::$_template_pack_collection->add(new $template_pack_class_name());
998
+		}
999
+
1000
+		/**
1001
+		 * Filter for plugins to add in any additional template packs
1002
+		 * Note the filter name here is for backward compat, this used to be found in EED_Messages.
1003
+		 */
1004
+		$additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
1005
+		foreach ((array) $additional_template_packs as $template_pack) {
1006
+			if (
1007
+				self::$_template_pack_collection->get_by_name(
1008
+					$template_pack->dbref
1009
+				) instanceof EE_Messages_Template_Pack
1010
+			) {
1011
+				continue;
1012
+			}
1013
+			self::$_template_pack_collection->add($template_pack);
1014
+		}
1015
+		return self::$_template_pack_collection;
1016
+	}
1017
+
1018
+
1019
+	/**
1020
+	 * This is a wrapper for the protected _create_new_templates function
1021
+	 *
1022
+	 * @param string $messenger_name
1023
+	 * @param string $message_type_name message type that the templates are being created for
1024
+	 * @param int    $GRP_ID
1025
+	 * @param bool   $global
1026
+	 * @return array
1027
+	 * @throws EE_Error
1028
+	 * @throws ReflectionException
1029
+	 */
1030
+	public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1031
+	{
1032
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1033
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1034
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1035
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1036
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1037
+			return array();
1038
+		}
1039
+		// whew made it this far!  Okay, let's go ahead and create the templates then
1040
+		return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1041
+	}
1042
+
1043
+
1044
+	/**
1045
+	 * @param EE_messenger     $messenger
1046
+	 * @param EE_message_type  $message_type
1047
+	 * @param                  $GRP_ID
1048
+	 * @param                  $global
1049
+	 * @return array|mixed
1050
+	 * @throws EE_Error
1051
+	 * @throws ReflectionException
1052
+	 */
1053
+	protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1054
+	{
1055
+		// if we're creating a custom template then we don't need to use the defaults class
1056
+		if (! $global) {
1057
+			return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1058
+		}
1059
+		/** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1060
+		$Message_Template_Defaults = EE_Registry::factory(
1061
+			'EE_Messages_Template_Defaults',
1062
+			array( $messenger, $message_type, $GRP_ID )
1063
+		);
1064
+		// generate templates
1065
+		$success = $Message_Template_Defaults->create_new_templates();
1066
+
1067
+		// if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1068
+		// its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1069
+		// attempts.
1070
+		if (! $success) {
1071
+			/** @var EE_Message_Resource_Manager $message_resource_manager */
1072
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1073
+			$message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1074
+		}
1075
+
1076
+		/**
1077
+		 * $success is in an array in the following format
1078
+		 * array(
1079
+		 *    'GRP_ID' => $new_grp_id,
1080
+		 *    'MTP_context' => $first_context_in_new_templates,
1081
+		 * )
1082
+		 */
1083
+		return $success;
1084
+	}
1085
+
1086
+
1087
+	/**
1088
+	 * This creates a custom template using the incoming GRP_ID
1089
+	 *
1090
+	 * @param EE_messenger    $messenger
1091
+	 * @param EE_message_type $message_type
1092
+	 * @param int             $GRP_ID           GRP_ID for the template_group being used as the base
1093
+	 * @return  array $success              This will be an array in the format:
1094
+	 *                                          array(
1095
+	 *                                          'GRP_ID' => $new_grp_id,
1096
+	 *                                          'MTP_context' => $first_context_in_created_template
1097
+	 *                                          )
1098
+	 * @throws EE_Error
1099
+	 * @throws ReflectionException
1100
+	 * @access private
1101
+	 */
1102
+	private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1103
+	{
1104
+		// defaults
1105
+		$success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1106
+		// get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1107
+		$Message_Template_Group = empty($GRP_ID)
1108
+			? EEM_Message_Template_Group::instance()->get_one(
1109
+				array(
1110
+					array(
1111
+						'MTP_messenger'    => $messenger->name,
1112
+						'MTP_message_type' => $message_type->name,
1113
+						'MTP_is_global'    => true
1114
+					)
1115
+				)
1116
+			)
1117
+			: EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1118
+		// if we don't have a mtg at this point then we need to bail.
1119
+		if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1120
+			EE_Error::add_error(
1121
+				sprintf(
1122
+					esc_html__(
1123
+						'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1124
+						'event_espresso'
1125
+					),
1126
+					$GRP_ID
1127
+				),
1128
+				__FILE__,
1129
+				__FUNCTION__,
1130
+				__LINE__
1131
+			);
1132
+			return $success;
1133
+		}
1134
+		// let's get all the related message_template objects for this group.
1135
+		$message_templates = $Message_Template_Group->message_templates();
1136
+		// now we have what we need to setup the new template
1137
+		$new_mtg = clone $Message_Template_Group;
1138
+		$new_mtg->set('GRP_ID', 0);
1139
+		$new_mtg->set('MTP_is_global', false);
1140
+
1141
+		/** @var RequestInterface $request */
1142
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
1143
+		$template_name = $request->isAjax() && $request->requestParamIsSet('templateName')
1144
+			? $request->getRequestParam('templateName')
1145
+			: esc_html__('New Custom Template', 'event_espresso');
1146
+		$template_description = $request->isAjax() && $request->requestParamIsSet('templateDescription')
1147
+			? $request->getRequestParam('templateDescription')
1148
+			: sprintf(
1149
+				esc_html__(
1150
+					'This is a custom template that was created for the %s messenger and %s message type.',
1151
+					'event_espresso'
1152
+				),
1153
+				$new_mtg->messenger_obj()->label['singular'],
1154
+				$new_mtg->message_type_obj()->label['singular']
1155
+			);
1156
+		$new_mtg->set('MTP_name', $template_name);
1157
+		$new_mtg->set('MTP_description', $template_description);
1158
+		// remove ALL relations on this template group so they don't get saved!
1159
+		$new_mtg->_remove_relations('Message_Template');
1160
+		$new_mtg->save();
1161
+		$success['GRP_ID'] = $new_mtg->ID();
1162
+		$success['template_name'] = $template_name;
1163
+		// add new message templates and add relation to.
1164
+		foreach ($message_templates as $message_template) {
1165
+			if (! $message_template instanceof EE_Message_Template) {
1166
+				continue;
1167
+			}
1168
+			$new_message_template = clone $message_template;
1169
+			$new_message_template->set('MTP_ID', 0);
1170
+			$new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1171
+			$new_message_template->save();
1172
+			if (empty($success['MTP_context']) && $new_message_template->get('MTP_context') !== 'admin') {
1173
+				$success['MTP_context'] = $new_message_template->get('MTP_context');
1174
+			}
1175
+		}
1176
+		return $success;
1177
+	}
1178
+
1179
+
1180
+	/**
1181
+	 * message_type_has_active_templates_for_messenger
1182
+	 *
1183
+	 * @param EE_messenger    $messenger
1184
+	 * @param EE_message_type $message_type
1185
+	 * @param bool            $global
1186
+	 * @return bool
1187
+	 * @throws EE_Error
1188
+	 */
1189
+	public static function message_type_has_active_templates_for_messenger(
1190
+		EE_messenger $messenger,
1191
+		EE_message_type $message_type,
1192
+		$global = false
1193
+	) {
1194
+		// is given message_type valid for given messenger (if this is not a global save)
1195
+		if ($global) {
1196
+			return true;
1197
+		}
1198
+		$active_templates = EEM_Message_Template_Group::instance()->count(
1199
+			array(
1200
+				array(
1201
+					'MTP_is_active'    => true,
1202
+					'MTP_messenger'    => $messenger->name,
1203
+					'MTP_message_type' => $message_type->name
1204
+				)
1205
+			)
1206
+		);
1207
+		if ($active_templates > 0) {
1208
+			return true;
1209
+		}
1210
+		EE_Error::add_error(
1211
+			sprintf(
1212
+				esc_html__(
1213
+					'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1214
+					'event_espresso'
1215
+				),
1216
+				$message_type->name,
1217
+				$messenger->name
1218
+			),
1219
+			__FILE__,
1220
+			__FUNCTION__,
1221
+			__LINE__
1222
+		);
1223
+		return false;
1224
+	}
1225
+
1226
+
1227
+	/**
1228
+	 * get_fields
1229
+	 * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1230
+	 *
1231
+	 * @param string $messenger_name    name of EE_messenger
1232
+	 * @param string $message_type_name name of EE_message_type
1233
+	 * @return array
1234
+	 * @throws EE_Error
1235
+	 * @throws ReflectionException
1236
+	 */
1237
+	public static function get_fields($messenger_name, $message_type_name)
1238
+	{
1239
+		$template_fields = array();
1240
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1241
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1242
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1243
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1244
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1245
+			return array();
1246
+		}
1247
+
1248
+		$excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1249
+
1250
+		// okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1251
+		foreach ($message_type->get_contexts() as $context => $details) {
1252
+			foreach ($messenger->get_template_fields() as $field => $value) {
1253
+				if (in_array($field, $excluded_fields_for_messenger, true)) {
1254
+					continue;
1255
+				}
1256
+				$template_fields[ $context ][ $field ] = $value;
1257
+			}
1258
+		}
1259
+		if (empty($template_fields)) {
1260
+			EE_Error::add_error(
1261
+				esc_html__('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1262
+				__FILE__,
1263
+				__FUNCTION__,
1264
+				__LINE__
1265
+			);
1266
+			return array();
1267
+		}
1268
+		return $template_fields;
1269
+	}
1270 1270
 }
Please login to merge, or discard this patch.