Completed
Branch FET/update-messages-admin-requ... (ba1b5b)
by
unknown
08:27 queued 06:35
created
core/helpers/EEH_Array.helper.php 2 patches
Indentation   +217 added lines, -217 removed lines patch added patch discarded remove patch
@@ -13,221 +13,221 @@
 block discarded – undo
13 13
 {
14 14
 
15 15
 
16
-    /**
17
-     * This method basically works the same as the PHP core function array_diff except it allows you to compare arrays
18
-     * of EE_Base_Class objects NOTE: This will ONLY work on an array of EE_Base_Class objects
19
-     *
20
-     * @uses array_udiff core php function for setting up our own array comparison
21
-     * @uses self::_compare_objects as the custom method for array_udiff
22
-     * @param  array $array1 an array of objects
23
-     * @param  array $array2 an array of objects
24
-     * @return array         an array of objects found in array 1 that aren't found in array 2.
25
-     */
26
-    public static function object_array_diff($array1, $array2)
27
-    {
28
-        return array_udiff($array1, $array2, array('self', '_compare_objects'));
29
-    }
30
-
31
-    /**
32
-     * Given that $arr is an array, determines if it's associative or numerically AND sequentially indexed
33
-     *
34
-     * @param array $array
35
-     * @return boolean
36
-     */
37
-    public static function is_associative_array(array $array)
38
-    {
39
-        return array_keys($array) !== range(0, count($array) - 1);
40
-    }
41
-
42
-    /**
43
-     * Gets an item from the array and leave the array intact. Use in place of end()
44
-     * when you don't want to change the array
45
-     *
46
-     * @param array $arr
47
-     * @return mixed what ever is in the array
48
-     */
49
-    public static function get_one_item_from_array($arr)
50
-    {
51
-        $item = end($arr);
52
-        reset($arr);
53
-        return $item;
54
-    }
55
-
56
-    /**
57
-     * Detects if this is a multi-dimensional array
58
-     * meaning that at least one top-level value is an array. Eg [ [], ...]
59
-     *
60
-     * @param mixed $arr
61
-     * @return boolean
62
-     */
63
-    public static function is_multi_dimensional_array($arr)
64
-    {
65
-        if (is_array($arr)) {
66
-            foreach ($arr as $item) {
67
-                if (is_array($item)) {
68
-                    return true; // yep, there's at least 2 levels to this array
69
-                }
70
-            }
71
-        }
72
-        return false; // there's only 1 level, or it's not an array at all!
73
-    }
74
-
75
-    /**
76
-     * Shorthand for isset( $arr[ $index ] ) ? $arr[ $index ] : $default
77
-     *
78
-     * @param array $arr
79
-     * @param mixed $index
80
-     * @param mixed $default
81
-     * @return mixed
82
-     */
83
-    public static function is_set($arr, $index, $default)
84
-    {
85
-        return isset($arr[ $index ]) ? $arr[ $index ] : $default;
86
-    }
87
-
88
-    /**
89
-     * Exactly like `maybe_unserialize`, but also accounts for a WP bug: http://core.trac.wordpress.org/ticket/26118
90
-     *
91
-     * @param mixed $value usually a string, but could be an array or object
92
-     * @return mixed the UN-serialized data
93
-     */
94
-    public static function maybe_unserialize($value)
95
-    {
96
-        $data = maybe_unserialize($value);
97
-        // it's possible that this still has serialized data if it's the session.
98
-        //  WP has a bug, http://core.trac.wordpress.org/ticket/26118 that doesn't unserialize this automatically.
99
-        $token = 'C';
100
-        $data = is_string($data) ? trim($data) : $data;
101
-        if (is_string($data) && strlen($data) > 1 && $data[0] == $token && preg_match("/^{$token}:[0-9]+:/s", $data)) {
102
-            return unserialize($data);
103
-        } else {
104
-            return $data;
105
-        }
106
-    }
107
-
108
-
109
-    /**
110
-     * insert_into_array
111
-     *
112
-     * @param array        $target_array the array to insert new data into
113
-     * @param array        $array_to_insert the new data to be inserted
114
-     * @param int | string $offset a known key within $target_array where new data will be inserted
115
-     * @param bool         $add_before whether to add new data before or after the offset key
116
-     * @param bool         $preserve_keys whether or not to reset numerically indexed arrays
117
-     * @return array
118
-     */
119
-    public static function insert_into_array(
120
-        $target_array = array(),
121
-        $array_to_insert = array(),
122
-        $offset = null,
123
-        $add_before = true,
124
-        $preserve_keys = true
125
-    ) {
126
-        // ensure incoming arrays are actually arrays
127
-        $target_array = (array) $target_array;
128
-        $array_to_insert = (array) $array_to_insert;
129
-        // if no offset key was supplied
130
-        if (empty($offset)) {
131
-            // use start or end of $target_array based on whether we are adding before or not
132
-            $offset = $add_before ? 0 : count($target_array);
133
-        }
134
-        // if offset key is a string, then find the corresponding numeric location for that element
135
-        $offset = is_int($offset) ? $offset : array_search($offset, array_keys($target_array));
136
-        // add one to the offset if adding after
137
-        $offset = $add_before ? $offset : $offset + 1;
138
-        // but ensure offset does not exceed the length of the array
139
-        $offset = $offset > count($target_array) ? count($target_array) : $offset;
140
-        // reindex array ???
141
-        if ($preserve_keys) {
142
-            // take a slice of the target array from the beginning till the offset,
143
-            // then add the new data
144
-            // then add another slice that starts at the offset and goes till the end
145
-            return array_slice($target_array, 0, $offset, true) + $array_to_insert + array_slice(
146
-                $target_array,
147
-                $offset,
148
-                null,
149
-                true
150
-            );
151
-        } else {
152
-            // since we don't want to preserve keys, we can use array_splice
153
-            array_splice($target_array, $offset, 0, $array_to_insert);
154
-            return $target_array;
155
-        }
156
-    }
157
-
158
-
159
-    /**
160
-     * array_merge() is slow and should never be used while looping over data
161
-     * if you don't need to preserve keys from all arrays, then using a foreach loop is much faster
162
-     * so really this acts more like array_replace( $array1, $array2 )
163
-     * or a union with the arrays flipped ( $array2 + $array1 )
164
-     * this saves a few lines of code and improves readability
165
-     *
166
-     * @param array $array1
167
-     * @param array $array2
168
-     * @return array
169
-     */
170
-    public static function merge_arrays_and_overwrite_keys(array $array1, array $array2)
171
-    {
172
-        foreach ($array2 as $key => $value) {
173
-            $array1[ $key ] = $value;
174
-        }
175
-        return $array1;
176
-    }
177
-
178
-
179
-    /**
180
-     * given a flat array like $array = array('A', 'B', 'C')
181
-     * will convert into a multidimensional array like $array[A][B][C]
182
-     * if $final_value is provided and is anything other than null,
183
-     * then that will be set as the value for the innermost array key
184
-     * like so: $array[A][B][C] = $final_value
185
-     *
186
-     * @param array $flat_array
187
-     * @param mixed $final_value
188
-     * @return array
189
-     */
190
-    public static function convert_array_values_to_keys(array $flat_array, $final_value = null)
191
-    {
192
-        $multidimensional = array();
193
-        $reference = &$multidimensional;
194
-        foreach ($flat_array as $key) {
195
-            $reference[ $key ] = array();
196
-            $reference = &$reference[ $key ];
197
-        }
198
-        if ($final_value !== null) {
199
-            $reference = $final_value;
200
-        }
201
-        return $multidimensional;
202
-    }
203
-
204
-
205
-    /**
206
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
207
-     * @param array $array
208
-     * @return bool
209
-     */
210
-    public static function is_array_numerically_and_sequentially_indexed(array $array)
211
-    {
212
-        return empty($array) || array_keys($array) === range(0, count($array) - 1);
213
-    }
214
-
215
-
216
-    /**
217
-     * recursively walks through an array and adds slashes to all no array elements
218
-     *
219
-     * @param mixed $element
220
-     * @return array|string
221
-     * @since   $VID:$
222
-     */
223
-    public static function addSlashesRecursively($element)
224
-    {
225
-        if (is_array($element)) {
226
-            foreach ($element as $key => $value) {
227
-                $element[ $key ] = EEH_Array::addSlashesRecursively($value);
228
-            }
229
-            return $element;
230
-        }
231
-        return is_string($element) ? addslashes($element) : $element;
232
-    }
16
+	/**
17
+	 * This method basically works the same as the PHP core function array_diff except it allows you to compare arrays
18
+	 * of EE_Base_Class objects NOTE: This will ONLY work on an array of EE_Base_Class objects
19
+	 *
20
+	 * @uses array_udiff core php function for setting up our own array comparison
21
+	 * @uses self::_compare_objects as the custom method for array_udiff
22
+	 * @param  array $array1 an array of objects
23
+	 * @param  array $array2 an array of objects
24
+	 * @return array         an array of objects found in array 1 that aren't found in array 2.
25
+	 */
26
+	public static function object_array_diff($array1, $array2)
27
+	{
28
+		return array_udiff($array1, $array2, array('self', '_compare_objects'));
29
+	}
30
+
31
+	/**
32
+	 * Given that $arr is an array, determines if it's associative or numerically AND sequentially indexed
33
+	 *
34
+	 * @param array $array
35
+	 * @return boolean
36
+	 */
37
+	public static function is_associative_array(array $array)
38
+	{
39
+		return array_keys($array) !== range(0, count($array) - 1);
40
+	}
41
+
42
+	/**
43
+	 * Gets an item from the array and leave the array intact. Use in place of end()
44
+	 * when you don't want to change the array
45
+	 *
46
+	 * @param array $arr
47
+	 * @return mixed what ever is in the array
48
+	 */
49
+	public static function get_one_item_from_array($arr)
50
+	{
51
+		$item = end($arr);
52
+		reset($arr);
53
+		return $item;
54
+	}
55
+
56
+	/**
57
+	 * Detects if this is a multi-dimensional array
58
+	 * meaning that at least one top-level value is an array. Eg [ [], ...]
59
+	 *
60
+	 * @param mixed $arr
61
+	 * @return boolean
62
+	 */
63
+	public static function is_multi_dimensional_array($arr)
64
+	{
65
+		if (is_array($arr)) {
66
+			foreach ($arr as $item) {
67
+				if (is_array($item)) {
68
+					return true; // yep, there's at least 2 levels to this array
69
+				}
70
+			}
71
+		}
72
+		return false; // there's only 1 level, or it's not an array at all!
73
+	}
74
+
75
+	/**
76
+	 * Shorthand for isset( $arr[ $index ] ) ? $arr[ $index ] : $default
77
+	 *
78
+	 * @param array $arr
79
+	 * @param mixed $index
80
+	 * @param mixed $default
81
+	 * @return mixed
82
+	 */
83
+	public static function is_set($arr, $index, $default)
84
+	{
85
+		return isset($arr[ $index ]) ? $arr[ $index ] : $default;
86
+	}
87
+
88
+	/**
89
+	 * Exactly like `maybe_unserialize`, but also accounts for a WP bug: http://core.trac.wordpress.org/ticket/26118
90
+	 *
91
+	 * @param mixed $value usually a string, but could be an array or object
92
+	 * @return mixed the UN-serialized data
93
+	 */
94
+	public static function maybe_unserialize($value)
95
+	{
96
+		$data = maybe_unserialize($value);
97
+		// it's possible that this still has serialized data if it's the session.
98
+		//  WP has a bug, http://core.trac.wordpress.org/ticket/26118 that doesn't unserialize this automatically.
99
+		$token = 'C';
100
+		$data = is_string($data) ? trim($data) : $data;
101
+		if (is_string($data) && strlen($data) > 1 && $data[0] == $token && preg_match("/^{$token}:[0-9]+:/s", $data)) {
102
+			return unserialize($data);
103
+		} else {
104
+			return $data;
105
+		}
106
+	}
107
+
108
+
109
+	/**
110
+	 * insert_into_array
111
+	 *
112
+	 * @param array        $target_array the array to insert new data into
113
+	 * @param array        $array_to_insert the new data to be inserted
114
+	 * @param int | string $offset a known key within $target_array where new data will be inserted
115
+	 * @param bool         $add_before whether to add new data before or after the offset key
116
+	 * @param bool         $preserve_keys whether or not to reset numerically indexed arrays
117
+	 * @return array
118
+	 */
119
+	public static function insert_into_array(
120
+		$target_array = array(),
121
+		$array_to_insert = array(),
122
+		$offset = null,
123
+		$add_before = true,
124
+		$preserve_keys = true
125
+	) {
126
+		// ensure incoming arrays are actually arrays
127
+		$target_array = (array) $target_array;
128
+		$array_to_insert = (array) $array_to_insert;
129
+		// if no offset key was supplied
130
+		if (empty($offset)) {
131
+			// use start or end of $target_array based on whether we are adding before or not
132
+			$offset = $add_before ? 0 : count($target_array);
133
+		}
134
+		// if offset key is a string, then find the corresponding numeric location for that element
135
+		$offset = is_int($offset) ? $offset : array_search($offset, array_keys($target_array));
136
+		// add one to the offset if adding after
137
+		$offset = $add_before ? $offset : $offset + 1;
138
+		// but ensure offset does not exceed the length of the array
139
+		$offset = $offset > count($target_array) ? count($target_array) : $offset;
140
+		// reindex array ???
141
+		if ($preserve_keys) {
142
+			// take a slice of the target array from the beginning till the offset,
143
+			// then add the new data
144
+			// then add another slice that starts at the offset and goes till the end
145
+			return array_slice($target_array, 0, $offset, true) + $array_to_insert + array_slice(
146
+				$target_array,
147
+				$offset,
148
+				null,
149
+				true
150
+			);
151
+		} else {
152
+			// since we don't want to preserve keys, we can use array_splice
153
+			array_splice($target_array, $offset, 0, $array_to_insert);
154
+			return $target_array;
155
+		}
156
+	}
157
+
158
+
159
+	/**
160
+	 * array_merge() is slow and should never be used while looping over data
161
+	 * if you don't need to preserve keys from all arrays, then using a foreach loop is much faster
162
+	 * so really this acts more like array_replace( $array1, $array2 )
163
+	 * or a union with the arrays flipped ( $array2 + $array1 )
164
+	 * this saves a few lines of code and improves readability
165
+	 *
166
+	 * @param array $array1
167
+	 * @param array $array2
168
+	 * @return array
169
+	 */
170
+	public static function merge_arrays_and_overwrite_keys(array $array1, array $array2)
171
+	{
172
+		foreach ($array2 as $key => $value) {
173
+			$array1[ $key ] = $value;
174
+		}
175
+		return $array1;
176
+	}
177
+
178
+
179
+	/**
180
+	 * given a flat array like $array = array('A', 'B', 'C')
181
+	 * will convert into a multidimensional array like $array[A][B][C]
182
+	 * if $final_value is provided and is anything other than null,
183
+	 * then that will be set as the value for the innermost array key
184
+	 * like so: $array[A][B][C] = $final_value
185
+	 *
186
+	 * @param array $flat_array
187
+	 * @param mixed $final_value
188
+	 * @return array
189
+	 */
190
+	public static function convert_array_values_to_keys(array $flat_array, $final_value = null)
191
+	{
192
+		$multidimensional = array();
193
+		$reference = &$multidimensional;
194
+		foreach ($flat_array as $key) {
195
+			$reference[ $key ] = array();
196
+			$reference = &$reference[ $key ];
197
+		}
198
+		if ($final_value !== null) {
199
+			$reference = $final_value;
200
+		}
201
+		return $multidimensional;
202
+	}
203
+
204
+
205
+	/**
206
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
207
+	 * @param array $array
208
+	 * @return bool
209
+	 */
210
+	public static function is_array_numerically_and_sequentially_indexed(array $array)
211
+	{
212
+		return empty($array) || array_keys($array) === range(0, count($array) - 1);
213
+	}
214
+
215
+
216
+	/**
217
+	 * recursively walks through an array and adds slashes to all no array elements
218
+	 *
219
+	 * @param mixed $element
220
+	 * @return array|string
221
+	 * @since   $VID:$
222
+	 */
223
+	public static function addSlashesRecursively($element)
224
+	{
225
+		if (is_array($element)) {
226
+			foreach ($element as $key => $value) {
227
+				$element[ $key ] = EEH_Array::addSlashesRecursively($value);
228
+			}
229
+			return $element;
230
+		}
231
+		return is_string($element) ? addslashes($element) : $element;
232
+	}
233 233
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
      */
83 83
     public static function is_set($arr, $index, $default)
84 84
     {
85
-        return isset($arr[ $index ]) ? $arr[ $index ] : $default;
85
+        return isset($arr[$index]) ? $arr[$index] : $default;
86 86
     }
87 87
 
88 88
     /**
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
     public static function merge_arrays_and_overwrite_keys(array $array1, array $array2)
171 171
     {
172 172
         foreach ($array2 as $key => $value) {
173
-            $array1[ $key ] = $value;
173
+            $array1[$key] = $value;
174 174
         }
175 175
         return $array1;
176 176
     }
@@ -192,8 +192,8 @@  discard block
 block discarded – undo
192 192
         $multidimensional = array();
193 193
         $reference = &$multidimensional;
194 194
         foreach ($flat_array as $key) {
195
-            $reference[ $key ] = array();
196
-            $reference = &$reference[ $key ];
195
+            $reference[$key] = array();
196
+            $reference = &$reference[$key];
197 197
         }
198 198
         if ($final_value !== null) {
199 199
             $reference = $final_value;
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
     {
225 225
         if (is_array($element)) {
226 226
             foreach ($element as $key => $value) {
227
-                $element[ $key ] = EEH_Array::addSlashesRecursively($value);
227
+                $element[$key] = EEH_Array::addSlashesRecursively($value);
228 228
             }
229 229
             return $element;
230 230
         }
Please login to merge, or discard this patch.
admin_pages/events/Events_Admin_Page.core.php 1 patch
Indentation   +2809 added lines, -2809 removed lines patch added patch discarded remove patch
@@ -16,2816 +16,2816 @@
 block discarded – undo
16 16
 class Events_Admin_Page extends EE_Admin_Page_CPT
17 17
 {
18 18
 
19
-    /**
20
-     * This will hold the event object for event_details screen.
19
+	/**
20
+	 * This will hold the event object for event_details screen.
21
+	 *
22
+	 * @var EE_Event $_event
23
+	 */
24
+	protected $_event;
25
+
26
+
27
+	/**
28
+	 * This will hold the category object for category_details screen.
29
+	 *
30
+	 * @var stdClass $_category
31
+	 */
32
+	protected $_category;
33
+
34
+
35
+	/**
36
+	 * This will hold the event model instance
37
+	 *
38
+	 * @var EEM_Event $_event_model
39
+	 */
40
+	protected $_event_model;
41
+
42
+
43
+	/**
44
+	 * @var EE_Event
45
+	 */
46
+	protected $_cpt_model_obj = false;
47
+
48
+
49
+	/**
50
+	 * @var NodeGroupDao
51
+	 */
52
+	protected $model_obj_node_group_persister;
53
+
54
+
55
+	/**
56
+	 * Initialize page props for this admin page group.
57
+	 */
58
+	protected function _init_page_props()
59
+	{
60
+		$this->page_slug        = EVENTS_PG_SLUG;
61
+		$this->page_label       = EVENTS_LABEL;
62
+		$this->_admin_base_url  = EVENTS_ADMIN_URL;
63
+		$this->_admin_base_path = EVENTS_ADMIN;
64
+		$this->_cpt_model_names = [
65
+			'create_new' => 'EEM_Event',
66
+			'edit'       => 'EEM_Event',
67
+		];
68
+		$this->_cpt_edit_routes = [
69
+			'espresso_events' => 'edit',
70
+		];
71
+		add_action(
72
+			'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
73
+			[$this, 'verify_event_edit'],
74
+			10,
75
+			2
76
+		);
77
+	}
78
+
79
+
80
+	/**
81
+	 * Sets the ajax hooks used for this admin page group.
82
+	 */
83
+	protected function _ajax_hooks()
84
+	{
85
+		add_action('wp_ajax_ee_save_timezone_setting', [$this, 'saveTimezoneString']);
86
+	}
87
+
88
+
89
+	/**
90
+	 * Sets the page properties for this admin page group.
91
+	 */
92
+	protected function _define_page_props()
93
+	{
94
+		$this->_admin_page_title = EVENTS_LABEL;
95
+		$this->_labels           = [
96
+			'buttons'      => [
97
+				'add'             => esc_html__('Add New Event', 'event_espresso'),
98
+				'edit'            => esc_html__('Edit Event', 'event_espresso'),
99
+				'delete'          => esc_html__('Delete Event', 'event_espresso'),
100
+				'add_category'    => esc_html__('Add New Category', 'event_espresso'),
101
+				'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
102
+				'delete_category' => esc_html__('Delete Category', 'event_espresso'),
103
+			],
104
+			'editor_title' => [
105
+				'espresso_events' => esc_html__('Enter event title here', 'event_espresso'),
106
+			],
107
+			'publishbox'   => [
108
+				'create_new'        => esc_html__('Save New Event', 'event_espresso'),
109
+				'edit'              => esc_html__('Update Event', 'event_espresso'),
110
+				'add_category'      => esc_html__('Save New Category', 'event_espresso'),
111
+				'edit_category'     => esc_html__('Update Category', 'event_espresso'),
112
+				'template_settings' => esc_html__('Update Settings', 'event_espresso'),
113
+			],
114
+		];
115
+	}
116
+
117
+
118
+	/**
119
+	 * Sets the page routes property for this admin page group.
120
+	 */
121
+	protected function _set_page_routes()
122
+	{
123
+		// load formatter helper
124
+		// load field generator helper
125
+		// is there a evt_id in the request?
126
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
127
+		$EVT_ID = $this->request->getRequestParam('post', $EVT_ID, 'int');
128
+
129
+		$this->_page_routes = [
130
+			'default'                       => [
131
+				'func'       => '_events_overview_list_table',
132
+				'capability' => 'ee_read_events',
133
+			],
134
+			'create_new'                    => [
135
+				'func'       => '_create_new_cpt_item',
136
+				'capability' => 'ee_edit_events',
137
+			],
138
+			'edit'                          => [
139
+				'func'       => '_edit_cpt_item',
140
+				'capability' => 'ee_edit_event',
141
+				'obj_id'     => $EVT_ID,
142
+			],
143
+			'copy_event'                    => [
144
+				'func'       => '_copy_events',
145
+				'capability' => 'ee_edit_event',
146
+				'obj_id'     => $EVT_ID,
147
+				'noheader'   => true,
148
+			],
149
+			'trash_event'                   => [
150
+				'func'       => '_trash_or_restore_event',
151
+				'args'       => ['event_status' => 'trash'],
152
+				'capability' => 'ee_delete_event',
153
+				'obj_id'     => $EVT_ID,
154
+				'noheader'   => true,
155
+			],
156
+			'trash_events'                  => [
157
+				'func'       => '_trash_or_restore_events',
158
+				'args'       => ['event_status' => 'trash'],
159
+				'capability' => 'ee_delete_events',
160
+				'noheader'   => true,
161
+			],
162
+			'restore_event'                 => [
163
+				'func'       => '_trash_or_restore_event',
164
+				'args'       => ['event_status' => 'draft'],
165
+				'capability' => 'ee_delete_event',
166
+				'obj_id'     => $EVT_ID,
167
+				'noheader'   => true,
168
+			],
169
+			'restore_events'                => [
170
+				'func'       => '_trash_or_restore_events',
171
+				'args'       => ['event_status' => 'draft'],
172
+				'capability' => 'ee_delete_events',
173
+				'noheader'   => true,
174
+			],
175
+			'delete_event'                  => [
176
+				'func'       => '_delete_event',
177
+				'capability' => 'ee_delete_event',
178
+				'obj_id'     => $EVT_ID,
179
+				'noheader'   => true,
180
+			],
181
+			'delete_events'                 => [
182
+				'func'       => '_delete_events',
183
+				'capability' => 'ee_delete_events',
184
+				'noheader'   => true,
185
+			],
186
+			'view_report'                   => [
187
+				'func'       => '_view_report',
188
+				'capability' => 'ee_edit_events',
189
+			],
190
+			'default_event_settings'        => [
191
+				'func'       => '_default_event_settings',
192
+				'capability' => 'manage_options',
193
+			],
194
+			'update_default_event_settings' => [
195
+				'func'       => '_update_default_event_settings',
196
+				'capability' => 'manage_options',
197
+				'noheader'   => true,
198
+			],
199
+			'template_settings'             => [
200
+				'func'       => '_template_settings',
201
+				'capability' => 'manage_options',
202
+			],
203
+			// event category tab related
204
+			'add_category'                  => [
205
+				'func'       => '_category_details',
206
+				'capability' => 'ee_edit_event_category',
207
+				'args'       => ['add'],
208
+			],
209
+			'edit_category'                 => [
210
+				'func'       => '_category_details',
211
+				'capability' => 'ee_edit_event_category',
212
+				'args'       => ['edit'],
213
+			],
214
+			'delete_categories'             => [
215
+				'func'       => '_delete_categories',
216
+				'capability' => 'ee_delete_event_category',
217
+				'noheader'   => true,
218
+			],
219
+			'delete_category'               => [
220
+				'func'       => '_delete_categories',
221
+				'capability' => 'ee_delete_event_category',
222
+				'noheader'   => true,
223
+			],
224
+			'insert_category'               => [
225
+				'func'       => '_insert_or_update_category',
226
+				'args'       => ['new_category' => true],
227
+				'capability' => 'ee_edit_event_category',
228
+				'noheader'   => true,
229
+			],
230
+			'update_category'               => [
231
+				'func'       => '_insert_or_update_category',
232
+				'args'       => ['new_category' => false],
233
+				'capability' => 'ee_edit_event_category',
234
+				'noheader'   => true,
235
+			],
236
+			'category_list'                 => [
237
+				'func'       => '_category_list_table',
238
+				'capability' => 'ee_manage_event_categories',
239
+			],
240
+			'preview_deletion'              => [
241
+				'func'       => 'previewDeletion',
242
+				'capability' => 'ee_delete_events',
243
+			],
244
+			'confirm_deletion'              => [
245
+				'func'       => 'confirmDeletion',
246
+				'capability' => 'ee_delete_events',
247
+				'noheader'   => true,
248
+			],
249
+		];
250
+	}
251
+
252
+
253
+	/**
254
+	 * Set the _page_config property for this admin page group.
255
+	 */
256
+	protected function _set_page_config()
257
+	{
258
+		$post_id            = $this->request->getRequestParam('post', 0, 'int');
259
+		$EVT_CAT_ID         = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
260
+		$this->_page_config = [
261
+			'default'                => [
262
+				'nav'           => [
263
+					'label' => esc_html__('Overview', 'event_espresso'),
264
+					'order' => 10,
265
+				],
266
+				'list_table'    => 'Events_Admin_List_Table',
267
+				'help_tabs'     => [
268
+					'events_overview_help_tab'                       => [
269
+						'title'    => esc_html__('Events Overview', 'event_espresso'),
270
+						'filename' => 'events_overview',
271
+					],
272
+					'events_overview_table_column_headings_help_tab' => [
273
+						'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
274
+						'filename' => 'events_overview_table_column_headings',
275
+					],
276
+					'events_overview_filters_help_tab'               => [
277
+						'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
278
+						'filename' => 'events_overview_filters',
279
+					],
280
+					'events_overview_view_help_tab'                  => [
281
+						'title'    => esc_html__('Events Overview Views', 'event_espresso'),
282
+						'filename' => 'events_overview_views',
283
+					],
284
+					'events_overview_other_help_tab'                 => [
285
+						'title'    => esc_html__('Events Overview Other', 'event_espresso'),
286
+						'filename' => 'events_overview_other',
287
+					],
288
+				],
289
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
290
+				// 'help_tour'     => array(
291
+				//     'Event_Overview_Help_Tour',
292
+				//     // 'New_Features_Test_Help_Tour' for testing multiple help tour
293
+				// ),
294
+				'qtips'         => [
295
+					'EE_Event_List_Table_Tips',
296
+				],
297
+				'require_nonce' => false,
298
+			],
299
+			'create_new'             => [
300
+				'nav'           => [
301
+					'label'      => esc_html__('Add Event', 'event_espresso'),
302
+					'order'      => 5,
303
+					'persistent' => false,
304
+				],
305
+				'metaboxes'     => ['_register_event_editor_meta_boxes'],
306
+				'help_tabs'     => [
307
+					'event_editor_help_tab'                            => [
308
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
309
+						'filename' => 'event_editor',
310
+					],
311
+					'event_editor_title_richtexteditor_help_tab'       => [
312
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
313
+						'filename' => 'event_editor_title_richtexteditor',
314
+					],
315
+					'event_editor_venue_details_help_tab'              => [
316
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
317
+						'filename' => 'event_editor_venue_details',
318
+					],
319
+					'event_editor_event_datetimes_help_tab'            => [
320
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
321
+						'filename' => 'event_editor_event_datetimes',
322
+					],
323
+					'event_editor_event_tickets_help_tab'              => [
324
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
325
+						'filename' => 'event_editor_event_tickets',
326
+					],
327
+					'event_editor_event_registration_options_help_tab' => [
328
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
329
+						'filename' => 'event_editor_event_registration_options',
330
+					],
331
+					'event_editor_tags_categories_help_tab'            => [
332
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
333
+						'filename' => 'event_editor_tags_categories',
334
+					],
335
+					'event_editor_questions_registrants_help_tab'      => [
336
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
337
+						'filename' => 'event_editor_questions_registrants',
338
+					],
339
+					'event_editor_save_new_event_help_tab'             => [
340
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
341
+						'filename' => 'event_editor_save_new_event',
342
+					],
343
+					'event_editor_other_help_tab'                      => [
344
+						'title'    => esc_html__('Event Other', 'event_espresso'),
345
+						'filename' => 'event_editor_other',
346
+					],
347
+				],
348
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
349
+				// 'help_tour'     => array(
350
+				//     'Event_Editor_Help_Tour',
351
+				// ),
352
+				'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
353
+				'require_nonce' => false,
354
+			],
355
+			'edit'                   => [
356
+				'nav'           => [
357
+					'label'      => esc_html__('Edit Event', 'event_espresso'),
358
+					'order'      => 5,
359
+					'persistent' => false,
360
+					'url'        => $post_id
361
+						? EE_Admin_Page::add_query_args_and_nonce(
362
+							['post' => $post_id, 'action' => 'edit'],
363
+							$this->_current_page_view_url
364
+						)
365
+						: $this->_admin_base_url,
366
+				],
367
+				'metaboxes'     => ['_register_event_editor_meta_boxes'],
368
+				'help_tabs'     => [
369
+					'event_editor_help_tab'                            => [
370
+						'title'    => esc_html__('Event Editor', 'event_espresso'),
371
+						'filename' => 'event_editor',
372
+					],
373
+					'event_editor_title_richtexteditor_help_tab'       => [
374
+						'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
375
+						'filename' => 'event_editor_title_richtexteditor',
376
+					],
377
+					'event_editor_venue_details_help_tab'              => [
378
+						'title'    => esc_html__('Event Venue Details', 'event_espresso'),
379
+						'filename' => 'event_editor_venue_details',
380
+					],
381
+					'event_editor_event_datetimes_help_tab'            => [
382
+						'title'    => esc_html__('Event Datetimes', 'event_espresso'),
383
+						'filename' => 'event_editor_event_datetimes',
384
+					],
385
+					'event_editor_event_tickets_help_tab'              => [
386
+						'title'    => esc_html__('Event Tickets', 'event_espresso'),
387
+						'filename' => 'event_editor_event_tickets',
388
+					],
389
+					'event_editor_event_registration_options_help_tab' => [
390
+						'title'    => esc_html__('Event Registration Options', 'event_espresso'),
391
+						'filename' => 'event_editor_event_registration_options',
392
+					],
393
+					'event_editor_tags_categories_help_tab'            => [
394
+						'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
395
+						'filename' => 'event_editor_tags_categories',
396
+					],
397
+					'event_editor_questions_registrants_help_tab'      => [
398
+						'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
399
+						'filename' => 'event_editor_questions_registrants',
400
+					],
401
+					'event_editor_save_new_event_help_tab'             => [
402
+						'title'    => esc_html__('Save New Event', 'event_espresso'),
403
+						'filename' => 'event_editor_save_new_event',
404
+					],
405
+					'event_editor_other_help_tab'                      => [
406
+						'title'    => esc_html__('Event Other', 'event_espresso'),
407
+						'filename' => 'event_editor_other',
408
+					],
409
+				],
410
+				'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
411
+				'require_nonce' => false,
412
+			],
413
+			'default_event_settings' => [
414
+				'nav'           => [
415
+					'label' => esc_html__('Default Settings', 'event_espresso'),
416
+					'order' => 40,
417
+				],
418
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
419
+				'labels'        => [
420
+					'publishbox' => esc_html__('Update Settings', 'event_espresso'),
421
+				],
422
+				'help_tabs'     => [
423
+					'default_settings_help_tab'        => [
424
+						'title'    => esc_html__('Default Event Settings', 'event_espresso'),
425
+						'filename' => 'events_default_settings',
426
+					],
427
+					'default_settings_status_help_tab' => [
428
+						'title'    => esc_html__('Default Registration Status', 'event_espresso'),
429
+						'filename' => 'events_default_settings_status',
430
+					],
431
+					'default_maximum_tickets_help_tab' => [
432
+						'title'    => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
433
+						'filename' => 'events_default_settings_max_tickets',
434
+					],
435
+				],
436
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
437
+				// 'help_tour'     => array('Event_Default_Settings_Help_Tour'),
438
+				'require_nonce' => false,
439
+			],
440
+			// template settings
441
+			'template_settings'      => [
442
+				'nav'           => [
443
+					'label' => esc_html__('Templates', 'event_espresso'),
444
+					'order' => 30,
445
+				],
446
+				'metaboxes'     => $this->_default_espresso_metaboxes,
447
+				'help_tabs'     => [
448
+					'general_settings_templates_help_tab' => [
449
+						'title'    => esc_html__('Templates', 'event_espresso'),
450
+						'filename' => 'general_settings_templates',
451
+					],
452
+				],
453
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
454
+				// 'help_tour'     => array('Templates_Help_Tour'),
455
+				'require_nonce' => false,
456
+			],
457
+			// event category stuff
458
+			'add_category'           => [
459
+				'nav'           => [
460
+					'label'      => esc_html__('Add Category', 'event_espresso'),
461
+					'order'      => 15,
462
+					'persistent' => false,
463
+				],
464
+				'help_tabs'     => [
465
+					'add_category_help_tab' => [
466
+						'title'    => esc_html__('Add New Event Category', 'event_espresso'),
467
+						'filename' => 'events_add_category',
468
+					],
469
+				],
470
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
471
+				// 'help_tour'     => array('Event_Add_Category_Help_Tour'),
472
+				'metaboxes'     => ['_publish_post_box'],
473
+				'require_nonce' => false,
474
+			],
475
+			'edit_category'          => [
476
+				'nav'           => [
477
+					'label'      => esc_html__('Edit Category', 'event_espresso'),
478
+					'order'      => 15,
479
+					'persistent' => false,
480
+					'url'        => $EVT_CAT_ID
481
+						? add_query_arg(
482
+							['EVT_CAT_ID' => $EVT_CAT_ID],
483
+							$this->_current_page_view_url
484
+						)
485
+						: $this->_admin_base_url,
486
+				],
487
+				'help_tabs'     => [
488
+					'edit_category_help_tab' => [
489
+						'title'    => esc_html__('Edit Event Category', 'event_espresso'),
490
+						'filename' => 'events_edit_category',
491
+					],
492
+				],
493
+				/*'help_tour' => array('Event_Edit_Category_Help_Tour'),*/
494
+				'metaboxes'     => ['_publish_post_box'],
495
+				'require_nonce' => false,
496
+			],
497
+			'category_list'          => [
498
+				'nav'           => [
499
+					'label' => esc_html__('Categories', 'event_espresso'),
500
+					'order' => 20,
501
+				],
502
+				'list_table'    => 'Event_Categories_Admin_List_Table',
503
+				'help_tabs'     => [
504
+					'events_categories_help_tab'                       => [
505
+						'title'    => esc_html__('Event Categories', 'event_espresso'),
506
+						'filename' => 'events_categories',
507
+					],
508
+					'events_categories_table_column_headings_help_tab' => [
509
+						'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
510
+						'filename' => 'events_categories_table_column_headings',
511
+					],
512
+					'events_categories_view_help_tab'                  => [
513
+						'title'    => esc_html__('Event Categories Views', 'event_espresso'),
514
+						'filename' => 'events_categories_views',
515
+					],
516
+					'events_categories_other_help_tab'                 => [
517
+						'title'    => esc_html__('Event Categories Other', 'event_espresso'),
518
+						'filename' => 'events_categories_other',
519
+					],
520
+				],
521
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
522
+				// 'help_tour'     => array(
523
+				//     'Event_Categories_Help_Tour',
524
+				// ),
525
+				'metaboxes'     => $this->_default_espresso_metaboxes,
526
+				'require_nonce' => false,
527
+			],
528
+			'preview_deletion'       => [
529
+				'nav'           => [
530
+					'label'      => esc_html__('Preview Deletion', 'event_espresso'),
531
+					'order'      => 15,
532
+					'persistent' => false,
533
+					'url'        => '',
534
+				],
535
+				'require_nonce' => false,
536
+			],
537
+		];
538
+	}
539
+
540
+
541
+	/**
542
+	 * Used to register any global screen options if necessary for every route in this admin page group.
543
+	 */
544
+	protected function _add_screen_options()
545
+	{
546
+	}
547
+
548
+
549
+	/**
550
+	 * Implementing the screen options for the 'default' route.
551
+	 */
552
+	protected function _add_screen_options_default()
553
+	{
554
+		$this->_per_page_screen_option();
555
+	}
556
+
557
+
558
+	/**
559
+	 * Implementing screen options for the category list route.
560
+	 */
561
+	protected function _add_screen_options_category_list()
562
+	{
563
+		$page_title              = $this->_admin_page_title;
564
+		$this->_admin_page_title = esc_html__('Categories', 'event_espresso');
565
+		$this->_per_page_screen_option();
566
+		$this->_admin_page_title = $page_title;
567
+	}
568
+
569
+
570
+	/**
571
+	 * Used to register any global feature pointers for the admin page group.
572
+	 */
573
+	protected function _add_feature_pointers()
574
+	{
575
+	}
576
+
577
+
578
+	/**
579
+	 * Registers and enqueues any global scripts and styles for the entire admin page group.
580
+	 */
581
+	public function load_scripts_styles()
582
+	{
583
+		wp_register_style(
584
+			'events-admin-css',
585
+			EVENTS_ASSETS_URL . 'events-admin-page.css',
586
+			[],
587
+			EVENT_ESPRESSO_VERSION
588
+		);
589
+		wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL . 'ee-cat-admin.css', [], EVENT_ESPRESSO_VERSION);
590
+		wp_enqueue_style('events-admin-css');
591
+		wp_enqueue_style('ee-cat-admin');
592
+		// todo note: we also need to load_scripts_styles per view (i.e. default/view_report/event_details
593
+		// registers for all views
594
+		// scripts
595
+		wp_register_script(
596
+			'event_editor_js',
597
+			EVENTS_ASSETS_URL . 'event_editor.js',
598
+			['ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'],
599
+			EVENT_ESPRESSO_VERSION,
600
+			true
601
+		);
602
+	}
603
+
604
+
605
+	/**
606
+	 * Enqueuing scripts and styles specific to this view
607
+	 */
608
+	public function load_scripts_styles_create_new()
609
+	{
610
+		$this->load_scripts_styles_edit();
611
+	}
612
+
613
+
614
+	/**
615
+	 * Enqueuing scripts and styles specific to this view
616
+	 */
617
+	public function load_scripts_styles_edit()
618
+	{
619
+		// styles
620
+		wp_enqueue_style('espresso-ui-theme');
621
+		wp_register_style(
622
+			'event-editor-css',
623
+			EVENTS_ASSETS_URL . 'event-editor.css',
624
+			['ee-admin-css'],
625
+			EVENT_ESPRESSO_VERSION
626
+		);
627
+		wp_enqueue_style('event-editor-css');
628
+		// scripts
629
+		wp_register_script(
630
+			'event-datetime-metabox',
631
+			EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
632
+			['event_editor_js', 'ee-datepicker'],
633
+			EVENT_ESPRESSO_VERSION
634
+		);
635
+		wp_enqueue_script('event-datetime-metabox');
636
+	}
637
+
638
+
639
+	/**
640
+	 * Populating the _views property for the category list table view.
641
+	 */
642
+	protected function _set_list_table_views_category_list()
643
+	{
644
+		$this->_views = [
645
+			'all' => [
646
+				'slug'        => 'all',
647
+				'label'       => esc_html__('All', 'event_espresso'),
648
+				'count'       => 0,
649
+				'bulk_action' => [
650
+					'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
651
+				],
652
+			],
653
+		];
654
+	}
655
+
656
+
657
+	/**
658
+	 * For adding anything that fires on the admin_init hook for any route within this admin page group.
659
+	 */
660
+	public function admin_init()
661
+	{
662
+		EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
663
+			'Do you really want to delete this image? Please remember to update your event to complete the removal.',
664
+			'event_espresso'
665
+		);
666
+	}
667
+
668
+
669
+	/**
670
+	 * For adding anything that should be triggered on the admin_notices hook for any route within this admin page
671
+	 * group.
672
+	 */
673
+	public function admin_notices()
674
+	{
675
+	}
676
+
677
+
678
+	/**
679
+	 * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
680
+	 * this admin page group.
681
+	 */
682
+	public function admin_footer_scripts()
683
+	{
684
+	}
685
+
686
+
687
+	/**
688
+	 * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
689
+	 * warning (via EE_Error::add_error());
690
+	 *
691
+	 * @param EE_Event $event Event object
692
+	 * @param string   $req_type
693
+	 * @return void
694
+	 * @throws EE_Error
695
+	 * @throws ReflectionException
696
+	 */
697
+	public function verify_event_edit($event = null, $req_type = '')
698
+	{
699
+		// don't need to do this when processing
700
+		if (! empty($req_type)) {
701
+			return;
702
+		}
703
+		// no event?
704
+		if (empty($event)) {
705
+			// set event
706
+			$event = $this->_cpt_model_obj;
707
+		}
708
+		// STILL no event?
709
+		if (! $event instanceof EE_Event) {
710
+			return;
711
+		}
712
+		$orig_status = $event->status();
713
+		// first check if event is active.
714
+		if (
715
+			$orig_status === EEM_Event::cancelled
716
+			|| $orig_status === EEM_Event::postponed
717
+			|| $event->is_expired()
718
+			|| $event->is_inactive()
719
+		) {
720
+			return;
721
+		}
722
+		// made it here so it IS active... next check that any of the tickets are sold.
723
+		if ($event->is_sold_out(true)) {
724
+			if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
725
+				EE_Error::add_attention(
726
+					sprintf(
727
+						esc_html__(
728
+							'Please note that the Event Status has automatically been changed to %s because there are no more spaces available for this event.  However, this change is not permanent until you update the event.  You can change the status back to something else before updating if you wish.',
729
+							'event_espresso'
730
+						),
731
+						EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
732
+					)
733
+				);
734
+			}
735
+			return;
736
+		} elseif ($orig_status === EEM_Event::sold_out) {
737
+			EE_Error::add_attention(
738
+				sprintf(
739
+					esc_html__(
740
+						'Please note that the Event Status has automatically been changed to %s because more spaces have become available for this event, most likely due to abandoned transactions freeing up reserved tickets.  However, this change is not permanent until you update the event. If you wish, you can change the status back to something else before updating.',
741
+						'event_espresso'
742
+					),
743
+					EEH_Template::pretty_status($event->status(), false, 'sentence')
744
+				)
745
+			);
746
+		}
747
+		// now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
748
+		if (! $event->tickets_on_sale()) {
749
+			return;
750
+		}
751
+		// made it here so show warning
752
+		$this->_edit_event_warning();
753
+	}
754
+
755
+
756
+	/**
757
+	 * This is the text used for when an event is being edited that is public and has tickets for sale.
758
+	 * When needed, hook this into a EE_Error::add_error() notice.
759
+	 *
760
+	 * @access protected
761
+	 * @return void
762
+	 */
763
+	protected function _edit_event_warning()
764
+	{
765
+		// we don't want to add warnings during these requests
766
+		if ($this->request->getRequestParam('action') === 'editpost') {
767
+			return;
768
+		}
769
+		EE_Error::add_attention(
770
+			sprintf(
771
+				esc_html__(
772
+					'Your event is open for registration. Making changes may disrupt any transactions in progress. %sLearn more%s',
773
+					'event_espresso'
774
+				),
775
+				'<a class="espresso-help-tab-lnk">',
776
+				'</a>'
777
+			)
778
+		);
779
+	}
780
+
781
+
782
+	/**
783
+	 * When a user is creating a new event, notify them if they haven't set their timezone.
784
+	 * Otherwise, do the normal logic
785
+	 *
786
+	 * @return void
787
+	 * @throws EE_Error
788
+	 */
789
+	protected function _create_new_cpt_item()
790
+	{
791
+		$has_timezone_string = get_option('timezone_string');
792
+		// only nag them about setting their timezone if it's their first event, and they haven't already done it
793
+		if (! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
794
+			EE_Error::add_attention(
795
+				sprintf(
796
+					esc_html__(
797
+						'Your website\'s timezone is currently set to a UTC offset. We recommend updating your timezone to a city or region near you before you create an event. Change your timezone now:%1$s%2$s%3$sChange Timezone%4$s',
798
+						'event_espresso'
799
+					),
800
+					'<br>',
801
+					'<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
802
+					. EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
803
+					. '</select>',
804
+					'<button class="button button-secondary timezone-submit">',
805
+					'</button><span class="spinner"></span>'
806
+				),
807
+				__FILE__,
808
+				__FUNCTION__,
809
+				__LINE__
810
+			);
811
+		}
812
+		parent::_create_new_cpt_item();
813
+	}
814
+
815
+
816
+	/**
817
+	 * Sets the _views property for the default route in this admin page group.
818
+	 */
819
+	protected function _set_list_table_views_default()
820
+	{
821
+		$this->_views = [
822
+			'all'   => [
823
+				'slug'        => 'all',
824
+				'label'       => esc_html__('View All Events', 'event_espresso'),
825
+				'count'       => 0,
826
+				'bulk_action' => [
827
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
828
+				],
829
+			],
830
+			'draft' => [
831
+				'slug'        => 'draft',
832
+				'label'       => esc_html__('Draft', 'event_espresso'),
833
+				'count'       => 0,
834
+				'bulk_action' => [
835
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
836
+				],
837
+			],
838
+		];
839
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
840
+			$this->_views['trash'] = [
841
+				'slug'        => 'trash',
842
+				'label'       => esc_html__('Trash', 'event_espresso'),
843
+				'count'       => 0,
844
+				'bulk_action' => [
845
+					'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
846
+					'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
847
+				],
848
+			];
849
+		}
850
+	}
851
+
852
+
853
+	/**
854
+	 * Provides the legend item array for the default list table view.
855
+	 *
856
+	 * @return array
857
+	 * @throws EE_Error
858
+	 * @throws EE_Error
859
+	 */
860
+	protected function _event_legend_items()
861
+	{
862
+		$items    = [
863
+			'view_details'   => [
864
+				'class' => 'dashicons dashicons-search',
865
+				'desc'  => esc_html__('View Event', 'event_espresso'),
866
+			],
867
+			'edit_event'     => [
868
+				'class' => 'ee-icon ee-icon-calendar-edit',
869
+				'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
870
+			],
871
+			'view_attendees' => [
872
+				'class' => 'dashicons dashicons-groups',
873
+				'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
874
+			],
875
+		];
876
+		$items    = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
877
+		$statuses = [
878
+			'sold_out_status'  => [
879
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::sold_out,
880
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
881
+			],
882
+			'active_status'    => [
883
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::active,
884
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
885
+			],
886
+			'upcoming_status'  => [
887
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::upcoming,
888
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
889
+			],
890
+			'postponed_status' => [
891
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::postponed,
892
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
893
+			],
894
+			'cancelled_status' => [
895
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::cancelled,
896
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
897
+			],
898
+			'expired_status'   => [
899
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::expired,
900
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
901
+			],
902
+			'inactive_status'  => [
903
+				'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::inactive,
904
+				'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
905
+			],
906
+		];
907
+		$statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
908
+		return array_merge($items, $statuses);
909
+	}
910
+
911
+
912
+	/**
913
+	 * @return EEM_Event
914
+	 * @throws EE_Error
915
+	 * @throws ReflectionException
916
+	 */
917
+	private function _event_model()
918
+	{
919
+		if (! $this->_event_model instanceof EEM_Event) {
920
+			$this->_event_model = EE_Registry::instance()->load_model('Event');
921
+		}
922
+		return $this->_event_model;
923
+	}
924
+
925
+
926
+	/**
927
+	 * Adds extra buttons to the WP CPT permalink field row.
928
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
929
+	 *
930
+	 * @param string $return    the current html
931
+	 * @param int    $id        the post id for the page
932
+	 * @param string $new_title What the title is
933
+	 * @param string $new_slug  what the slug is
934
+	 * @return string            The new html string for the permalink area
935
+	 */
936
+	public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
937
+	{
938
+		// make sure this is only when editing
939
+		if (! empty($id)) {
940
+			$post   = get_post($id);
941
+			$return .= '<a class="button button-small" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
942
+					   . esc_html__('Shortcode', 'event_espresso')
943
+					   . '</a> ';
944
+			$return .= '<input id="shortcode" type="hidden" value="[ESPRESSO_TICKET_SELECTOR event_id='
945
+					   . $post->ID
946
+					   . ']">';
947
+		}
948
+		return $return;
949
+	}
950
+
951
+
952
+	/**
953
+	 * _events_overview_list_table
954
+	 * This contains the logic for showing the events_overview list
955
+	 *
956
+	 * @access protected
957
+	 * @return void
958
+	 * @throws EE_Error
959
+	 */
960
+	protected function _events_overview_list_table()
961
+	{
962
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
963
+		$this->_template_args['after_list_table']                           =
964
+			! empty($this->_template_args['after_list_table'])
965
+				? (array) $this->_template_args['after_list_table']
966
+				: [];
967
+		$this->_template_args['after_list_table']['view_event_list_button'] = EEH_HTML::br()
968
+			. EEH_Template::get_button_or_link(
969
+				get_post_type_archive_link('espresso_events'),
970
+				esc_html__("View Event Archive Page", "event_espresso"),
971
+				'button'
972
+			);
973
+		$this->_template_args['after_list_table']['legend']                 = $this->_display_legend(
974
+			$this->_event_legend_items()
975
+		);
976
+		$this->_admin_page_title                                            .= ' ' . $this->get_action_link_or_button(
977
+			'create_new',
978
+			'add',
979
+			[],
980
+			'add-new-h2'
981
+		);
982
+		$this->display_admin_list_table_page_with_no_sidebar();
983
+	}
984
+
985
+
986
+	/**
987
+	 * this allows for extra misc actions in the default WP publish box
988
+	 *
989
+	 * @return void
990
+	 * @throws EE_Error
991
+	 * @throws ReflectionException
992
+	 */
993
+	public function extra_misc_actions_publish_box()
994
+	{
995
+		$this->_generate_publish_box_extra_content();
996
+	}
997
+
998
+
999
+	/**
1000
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
1001
+	 * saved.
1002
+	 * Typically you would use this to save any additional data.
1003
+	 * Keep in mind also that "save_post" runs on EVERY post update to the database.
1004
+	 * ALSO very important.  When a post transitions from scheduled to published,
1005
+	 * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from
1006
+	 * other meta saves. So MAKE sure that you handle this accordingly.
1007
+	 *
1008
+	 * @access protected
1009
+	 * @abstract
1010
+	 * @param string $post_id The ID of the cpt that was saved (so you can link relationally)
1011
+	 * @param object $post    The post object of the cpt that was saved.
1012
+	 * @return void
1013
+	 * @throws EE_Error
1014
+	 * @throws ReflectionException
1015
+	 */
1016
+	protected function _insert_update_cpt_item($post_id, $post)
1017
+	{
1018
+		if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
1019
+			// get out we're not processing an event save.
1020
+			return;
1021
+		}
1022
+
1023
+		$event_values = [
1024
+			'EVT_display_desc'                => $this->request->getRequestParam('display_desc', false, 'bool'),
1025
+			'EVT_display_ticket_selector'     => $this->request->getRequestParam(
1026
+				'display_ticket_selector',
1027
+				false,
1028
+				'bool'
1029
+			),
1030
+			'EVT_additional_limit'            => min(
1031
+				apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
1032
+				$this->request->getRequestParam('additional_limit', null, 'int')
1033
+			),
1034
+			'EVT_default_registration_status' => $this->request->getRequestParam(
1035
+				'EVT_default_registration_status',
1036
+				EE_Registry::instance()->CFG->registration->default_STS_ID
1037
+			),
1038
+
1039
+			'EVT_member_only'     => $this->request->getRequestParam('member_only', false, 'bool'),
1040
+			'EVT_allow_overflow'  => $this->request->getRequestParam('EVT_allow_overflow', false, 'bool'),
1041
+			'EVT_timezone_string' => $this->request->getRequestParam('timezone_string'),
1042
+			'EVT_external_URL'    => $this->request->getRequestParam('externalURL'),
1043
+			'EVT_phone'           => $this->request->getRequestParam('event_phone'),
1044
+		];
1045
+		// update event
1046
+		$success = $this->_event_model()->update_by_ID($event_values, $post_id);
1047
+		// get event_object for other metaboxes...
1048
+		// though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id )..
1049
+		// i have to setup where conditions to override the filters in the model
1050
+		// that filter out autodraft and inherit statuses so we GET the inherit id!
1051
+		$event = $this->_event_model()->get_one(
1052
+			[
1053
+				[
1054
+					$this->_event_model()->primary_key_name() => $post_id,
1055
+					'OR'                                      => [
1056
+						'status'   => $post->post_status,
1057
+						// if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1058
+						// but the returned object here has a status of "publish", so use the original post status as well
1059
+						'status*1' => $this->request->getRequestParam('original_post_status'),
1060
+					],
1061
+				],
1062
+			]
1063
+		);
1064
+		// the following are default callbacks for event attachment updates that can be overridden by caffeinated functionality and/or addons.
1065
+		$event_update_callbacks = apply_filters(
1066
+			'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1067
+			[
1068
+				[$this, '_default_venue_update'],
1069
+				[$this, '_default_tickets_update'],
1070
+			]
1071
+		);
1072
+		$att_success            = true;
1073
+		foreach ($event_update_callbacks as $e_callback) {
1074
+			$_success = is_callable($e_callback)
1075
+				? call_user_func($e_callback, $event, $this->request->requestParams())
1076
+				: false;
1077
+			// if ANY of these updates fail then we want the appropriate global error message
1078
+			$att_success = ! $att_success ? $att_success : $_success;
1079
+		}
1080
+		// any errors?
1081
+		if ($success && false === $att_success) {
1082
+			EE_Error::add_error(
1083
+				esc_html__(
1084
+					'Event Details saved successfully but something went wrong with saving attachments.',
1085
+					'event_espresso'
1086
+				),
1087
+				__FILE__,
1088
+				__FUNCTION__,
1089
+				__LINE__
1090
+			);
1091
+		} elseif ($success === false) {
1092
+			EE_Error::add_error(
1093
+				esc_html__('Event Details did not save successfully.', 'event_espresso'),
1094
+				__FILE__,
1095
+				__FUNCTION__,
1096
+				__LINE__
1097
+			);
1098
+		}
1099
+	}
1100
+
1101
+
1102
+	/**
1103
+	 * @param int $post_id
1104
+	 * @param int $revision_id
1105
+	 * @throws EE_Error
1106
+	 * @throws EE_Error
1107
+	 * @throws ReflectionException
1108
+	 * @see parent::restore_item()
1109
+	 */
1110
+	protected function _restore_cpt_item($post_id, $revision_id)
1111
+	{
1112
+		// copy existing event meta to new post
1113
+		$post_evt = $this->_event_model()->get_one_by_ID($post_id);
1114
+		if ($post_evt instanceof EE_Event) {
1115
+			// meta revision restore
1116
+			$post_evt->restore_revision($revision_id);
1117
+			// related objs restore
1118
+			$post_evt->restore_revision($revision_id, ['Venue', 'Datetime', 'Price']);
1119
+		}
1120
+	}
1121
+
1122
+
1123
+	/**
1124
+	 * Attach the venue to the Event
1125
+	 *
1126
+	 * @param EE_Event $event Event Object to add the venue to
1127
+	 * @param array    $data  The request data from the form
1128
+	 * @return bool           Success or fail.
1129
+	 * @throws EE_Error
1130
+	 * @throws ReflectionException
1131
+	 */
1132
+	protected function _default_venue_update(EE_Event $event, $data)
1133
+	{
1134
+		require_once(EE_MODELS . 'EEM_Venue.model.php');
1135
+		$venue_model = EE_Registry::instance()->load_model('Venue');
1136
+		$venue_id    = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1137
+		// very important.  If we don't have a venue name...
1138
+		// then we'll get out because not necessary to create empty venue
1139
+		if (empty($data['venue_title'])) {
1140
+			return false;
1141
+		}
1142
+		$venue_array = [
1143
+			'VNU_wp_user'         => $event->get('EVT_wp_user'),
1144
+			'VNU_name'            => $data['venue_title'],
1145
+			'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1146
+			'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1147
+			'VNU_short_desc'      => ! empty($data['venue_short_description'])
1148
+				? $data['venue_short_description']
1149
+				: null,
1150
+			'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1151
+			'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1152
+			'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1153
+			'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1154
+			'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1155
+			'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1156
+			'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1157
+			'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1158
+			'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1159
+			'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1160
+			'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1161
+			'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1162
+			'status'              => 'publish',
1163
+		];
1164
+		// if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1165
+		if (! empty($venue_id)) {
1166
+			$update_where  = [$venue_model->primary_key_name() => $venue_id];
1167
+			$rows_affected = $venue_model->update($venue_array, [$update_where]);
1168
+			// we've gotta make sure that the venue is always attached to a revision.. add_relation_to should take care of making sure that the relation is already present.
1169
+			$event->_add_relation_to($venue_id, 'Venue');
1170
+			return $rows_affected > 0;
1171
+		}
1172
+		// we insert the venue
1173
+		$venue_id = $venue_model->insert($venue_array);
1174
+		$event->_add_relation_to($venue_id, 'Venue');
1175
+		return ! empty($venue_id);
1176
+		// when we have the ancestor come in it's already been handled by the revision save.
1177
+	}
1178
+
1179
+
1180
+	/**
1181
+	 * Handles saving everything related to Tickets (datetimes, tickets, prices)
1182
+	 *
1183
+	 * @param EE_Event $event The Event object we're attaching data to
1184
+	 * @param array    $data  The request data from the form
1185
+	 * @return array
1186
+	 * @throws EE_Error
1187
+	 * @throws ReflectionException
1188
+	 * @throws Exception
1189
+	 */
1190
+	protected function _default_tickets_update(EE_Event $event, $data)
1191
+	{
1192
+		$datetime       = null;
1193
+		$saved_tickets  = [];
1194
+		$event_timezone = $event->get_timezone();
1195
+		$date_formats   = ['Y-m-d', 'h:i a'];
1196
+		foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
1197
+			// trim all values to ensure any excess whitespace is removed.
1198
+			$datetime_data                = array_map('trim', $datetime_data);
1199
+			$datetime_data['DTT_EVT_end'] =
1200
+				isset($datetime_data['DTT_EVT_end']) && ! empty($datetime_data['DTT_EVT_end'])
1201
+					? $datetime_data['DTT_EVT_end']
1202
+					: $datetime_data['DTT_EVT_start'];
1203
+			$datetime_values              = [
1204
+				'DTT_ID'        => ! empty($datetime_data['DTT_ID']) ? $datetime_data['DTT_ID'] : null,
1205
+				'DTT_EVT_start' => $datetime_data['DTT_EVT_start'],
1206
+				'DTT_EVT_end'   => $datetime_data['DTT_EVT_end'],
1207
+				'DTT_reg_limit' => empty($datetime_data['DTT_reg_limit']) ? EE_INF : $datetime_data['DTT_reg_limit'],
1208
+				'DTT_order'     => $row,
1209
+			];
1210
+			// if we have an id then let's get existing object first and then set the new values.
1211
+			//  Otherwise we instantiate a new object for save.
1212
+			if (! empty($datetime_data['DTT_ID'])) {
1213
+				$datetime = EEM_Datetime::instance($event_timezone)->get_one_by_ID($datetime_data['DTT_ID']);
1214
+				if (! $datetime instanceof EE_Ticket) {
1215
+					throw new RuntimeException(
1216
+						sprintf(
1217
+							esc_html__(
1218
+								'Something went wrong! A valid Datetime could not be retrieved from the database using the supplied ID: %1$d',
1219
+								'event_espresso'
1220
+							),
1221
+							$datetime_data['DTT_ID']
1222
+						)
1223
+					);
1224
+				}
1225
+				$datetime->set_date_format($date_formats[0]);
1226
+				$datetime->set_time_format($date_formats[1]);
1227
+				foreach ($datetime_values as $field => $value) {
1228
+					$datetime->set($field, $value);
1229
+				}
1230
+			} else {
1231
+				$datetime = EE_Datetime::new_instance($datetime_values, $event_timezone, $date_formats);
1232
+			}
1233
+			if (! $datetime instanceof EE_Datetime) {
1234
+				throw new RuntimeException(
1235
+					sprintf(
1236
+						esc_html__(
1237
+							'Something went wrong! A valid Datetime could not be generated or retrieved using the supplied data: %1$s',
1238
+							'event_espresso'
1239
+						),
1240
+						print_r($datetime_values, true)
1241
+					)
1242
+				);
1243
+			}
1244
+			// before going any further make sure our dates are setup correctly
1245
+			// so that the end date is always equal or greater than the start date.
1246
+			if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
1247
+				$datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
1248
+				$datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
1249
+			}
1250
+			$datetime->save();
1251
+			$event->_add_relation_to($datetime, 'Datetime');
1252
+		}
1253
+		// no datetimes get deleted so we don't do any of that logic here.
1254
+		// update tickets next
1255
+		$old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : [];
1256
+
1257
+		// set up some default start and end dates in case those are not present in the incoming data
1258
+		$default_start_date = new DateTime('now', new DateTimeZone($event->get_timezone()));
1259
+		$default_start_date = $default_start_date->format($date_formats[0] . ' ' . $date_formats[1]);
1260
+		// use the start date of the first datetime for the end date
1261
+		$first_datetime   = $event->first_datetime();
1262
+		$default_end_date = $first_datetime->start_date_and_time($date_formats[0], $date_formats[1]);
1263
+
1264
+		// now process the incoming data
1265
+		foreach ($data['edit_tickets'] as $row => $ticket_data) {
1266
+			$update_prices = false;
1267
+			$ticket_price  = isset($data['edit_prices'][ $row ][1]['PRC_amount'])
1268
+				? $data['edit_prices'][ $row ][1]['PRC_amount']
1269
+				: 0;
1270
+			// trim inputs to ensure any excess whitespace is removed.
1271
+			$ticket_data   = array_map('trim', $ticket_data);
1272
+			$ticket_values = [
1273
+				'TKT_ID'          => ! empty($ticket_data['TKT_ID']) ? $ticket_data['TKT_ID'] : null,
1274
+				'TTM_ID'          => ! empty($ticket_data['TTM_ID']) ? $ticket_data['TTM_ID'] : 0,
1275
+				'TKT_name'        => ! empty($ticket_data['TKT_name']) ? $ticket_data['TKT_name'] : '',
1276
+				'TKT_description' => ! empty($ticket_data['TKT_description']) ? $ticket_data['TKT_description'] : '',
1277
+				'TKT_start_date'  => ! empty($ticket_data['TKT_start_date'])
1278
+					? $ticket_data['TKT_start_date']
1279
+					: $default_start_date,
1280
+				'TKT_end_date'    => ! empty($ticket_data['TKT_end_date'])
1281
+					? $ticket_data['TKT_end_date']
1282
+					: $default_end_date,
1283
+				'TKT_qty'         => ! empty($ticket_data['TKT_qty'])
1284
+									 || (isset($ticket_data['TKT_qty']) && (int) $ticket_data['TKT_qty'] === 0)
1285
+					? $ticket_data['TKT_qty']
1286
+					: EE_INF,
1287
+				'TKT_uses'        => ! empty($ticket_data['TKT_uses'])
1288
+									 || (isset($ticket_data['TKT_uses']) && (int) $ticket_data['TKT_uses'] === 0)
1289
+					? $ticket_data['TKT_uses']
1290
+					: EE_INF,
1291
+				'TKT_min'         => ! empty($ticket_data['TKT_min']) ? $ticket_data['TKT_min'] : 0,
1292
+				'TKT_max'         => ! empty($ticket_data['TKT_max']) ? $ticket_data['TKT_max'] : EE_INF,
1293
+				'TKT_order'       => isset($ticket_data['TKT_order']) ? $ticket_data['TKT_order'] : $row,
1294
+				'TKT_price'       => $ticket_price,
1295
+				'TKT_row'         => $row,
1296
+			];
1297
+			// if this is a default ticket, then we need to set the TKT_ID to 0 and update accordingly,
1298
+			// which means in turn that the prices will become new prices as well.
1299
+			if (isset($ticket_data['TKT_is_default']) && $ticket_data['TKT_is_default']) {
1300
+				$ticket_values['TKT_ID']         = 0;
1301
+				$ticket_values['TKT_is_default'] = 0;
1302
+				$update_prices                   = true;
1303
+			}
1304
+			// if we have a TKT_ID then we need to get that existing TKT_obj and update it
1305
+			// we actually do our saves ahead of adding any relations because its entirely possible that this
1306
+			// ticket didn't get removed or added to any datetime in the session but DID have it's items modified.
1307
+			// keep in mind that if the ticket has been sold (and we have changed pricing information),
1308
+			// then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1309
+			if (! empty($ticket_data['TKT_ID'])) {
1310
+				$existing_ticket = EEM_Ticket::instance($event_timezone)->get_one_by_ID($ticket_data['TKT_ID']);
1311
+				if (! $existing_ticket instanceof EE_Ticket) {
1312
+					throw new RuntimeException(
1313
+						sprintf(
1314
+							esc_html__(
1315
+								'Something went wrong! A valid Ticket could not be retrieved from the database using the supplied ID: %1$d',
1316
+								'event_espresso'
1317
+							),
1318
+							$ticket_data['TKT_ID']
1319
+						)
1320
+					);
1321
+				}
1322
+				$ticket_sold = $existing_ticket->count_related(
1323
+					'Registration',
1324
+					[
1325
+						[
1326
+							'STS_ID' => [
1327
+								'NOT IN',
1328
+								[EEM_Registration::status_id_incomplete],
1329
+							],
1330
+						],
1331
+					]
1332
+				) > 0;
1333
+				// let's just check the total price for the existing ticket and determine if it matches the new total price.
1334
+				// if they are different then we create a new ticket (if $ticket_sold)
1335
+				// if they aren't different then we go ahead and modify existing ticket.
1336
+				$create_new_ticket = $ticket_sold
1337
+									 && $ticket_price !== $existing_ticket->price()
1338
+									 && ! $existing_ticket->deleted();
1339
+				$existing_ticket->set_date_format($date_formats[0]);
1340
+				$existing_ticket->set_time_format($date_formats[1]);
1341
+				// set new values
1342
+				foreach ($ticket_values as $field => $value) {
1343
+					if ($field == 'TKT_qty') {
1344
+						$existing_ticket->set_qty($value);
1345
+					} elseif ($field == 'TKT_price') {
1346
+						$existing_ticket->set('TKT_price', $ticket_price);
1347
+					} else {
1348
+						$existing_ticket->set($field, $value);
1349
+					}
1350
+				}
1351
+				$ticket = $existing_ticket;
1352
+				// if $create_new_ticket is false then we can safely update the existing ticket.
1353
+				//  Otherwise we have to create a new ticket.
1354
+				if ($create_new_ticket) {
1355
+					// archive the old ticket first
1356
+					$existing_ticket->set('TKT_deleted', 1);
1357
+					$existing_ticket->save();
1358
+					// make sure this ticket is still recorded in our $saved_tickets
1359
+					// so we don't run it through the regular trash routine.
1360
+					$saved_tickets[ $existing_ticket->ID() ] = $existing_ticket;
1361
+					// create new ticket that's a copy of the existing except,
1362
+					// (a new id of course and not archived) AND has the new TKT_price associated with it.
1363
+					$new_ticket = clone $existing_ticket;
1364
+					$new_ticket->set('TKT_ID', 0);
1365
+					$new_ticket->set('TKT_deleted', 0);
1366
+					$new_ticket->set('TKT_sold', 0);
1367
+					// now we need to make sure that $new prices are created as well and attached to new ticket.
1368
+					$update_prices = true;
1369
+					$ticket        = $new_ticket;
1370
+				}
1371
+			} else {
1372
+				// no TKT_id so a new ticket
1373
+				$ticket_values['TKT_price'] = $ticket_price;
1374
+				$ticket                     = EE_Ticket::new_instance($ticket_values, $event_timezone, $date_formats);
1375
+				$update_prices              = true;
1376
+			}
1377
+			if (! $ticket instanceof EE_Ticket) {
1378
+				throw new RuntimeException(
1379
+					sprintf(
1380
+						esc_html__(
1381
+							'Something went wrong! A valid Ticket could not be generated or retrieved using the supplied data: %1$s',
1382
+							'event_espresso'
1383
+						),
1384
+						print_r($ticket_values, true)
1385
+					)
1386
+				);
1387
+			}
1388
+			// cap ticket qty by datetime reg limits
1389
+			$ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
1390
+			// update ticket.
1391
+			$ticket->save();
1392
+			// before going any further make sure our dates are setup correctly
1393
+			// so that the end date is always equal or greater than the start date.
1394
+			if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
1395
+				$ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
1396
+				$ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
1397
+				$ticket->save();
1398
+			}
1399
+			// initially let's add the ticket to the datetime
1400
+			$datetime->_add_relation_to($ticket, 'Ticket');
1401
+			$saved_tickets[ $ticket->ID() ] = $ticket;
1402
+			// add prices to ticket
1403
+			$this->_add_prices_to_ticket($data['edit_prices'][ $row ], $ticket, $update_prices);
1404
+		}
1405
+		// however now we need to handle permanently deleting tickets via the ui.
1406
+		//  Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.
1407
+		//  However, it does allow for deleting tickets that have no tickets sold,
1408
+		// in which case we want to get rid of permanently because there is no need to save in db.
1409
+		$old_tickets     = isset($old_tickets[0]) && $old_tickets[0] == '' ? [] : $old_tickets;
1410
+		$tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1411
+		foreach ($tickets_removed as $id) {
1412
+			$id = absint($id);
1413
+			// get the ticket for this id
1414
+			$ticket_to_remove = EEM_Ticket::instance()->get_one_by_ID($id);
1415
+			if (! $ticket_to_remove instanceof EE_Ticket) {
1416
+				continue;
1417
+			}
1418
+			// need to get all the related datetimes on this ticket and remove from every single one of them
1419
+			// (remember this process can ONLY kick off if there are NO tickets sold)
1420
+			$related_datetimes = $ticket_to_remove->get_many_related('Datetime');
1421
+			foreach ($related_datetimes as $related_datetime) {
1422
+				$ticket_to_remove->_remove_relation_to($related_datetime, 'Datetime');
1423
+			}
1424
+			// need to do the same for prices (except these prices can also be deleted because again,
1425
+			// tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1426
+			$ticket_to_remove->delete_related_permanently('Price');
1427
+			// finally let's delete this ticket
1428
+			// (which should not be blocked at this point b/c we've removed all our relationships)
1429
+			$ticket_to_remove->delete_permanently();
1430
+		}
1431
+		return [$datetime, $saved_tickets];
1432
+	}
1433
+
1434
+
1435
+	/**
1436
+	 * This attaches a list of given prices to a ticket.
1437
+	 * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
1438
+	 * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
1439
+	 * price info and prices are automatically "archived" via the ticket.
1440
+	 *
1441
+	 * @access  private
1442
+	 * @param array     $prices_data Array of prices from the form.
1443
+	 * @param EE_Ticket $ticket      EE_Ticket object that prices are being attached to.
1444
+	 * @param bool      $new_prices  Whether attach existing incoming prices or create new ones.
1445
+	 * @return  void
1446
+	 * @throws EE_Error
1447
+	 * @throws ReflectionException
1448
+	 */
1449
+	private function _add_prices_to_ticket($prices_data, EE_Ticket $ticket, $new_prices = false)
1450
+	{
1451
+		$timezone = $ticket->get_timezone();
1452
+		foreach ($prices_data as $row => $price_data) {
1453
+			$price_values = [
1454
+				'PRC_ID'         => ! empty($price_data['PRC_ID']) ? $price_data['PRC_ID'] : null,
1455
+				'PRT_ID'         => ! empty($price_data['PRT_ID']) ? $price_data['PRT_ID'] : null,
1456
+				'PRC_amount'     => ! empty($price_data['PRC_amount']) ? $price_data['PRC_amount'] : 0,
1457
+				'PRC_name'       => ! empty($price_data['PRC_name']) ? $price_data['PRC_name'] : '',
1458
+				'PRC_desc'       => ! empty($price_data['PRC_desc']) ? $price_data['PRC_desc'] : '',
1459
+				'PRC_is_default' => 0, // make sure prices are NOT set as default from this context
1460
+				'PRC_order'      => $row,
1461
+			];
1462
+			if ($new_prices || empty($price_values['PRC_ID'])) {
1463
+				$price_values['PRC_ID'] = 0;
1464
+				$price                  = EE_Price::new_instance($price_values, $timezone);
1465
+			} else {
1466
+				$price = EEM_Price::instance($timezone)->get_one_by_ID($price_data['PRC_ID']);
1467
+				// update this price with new values
1468
+				foreach ($price_values as $field => $new_price) {
1469
+					$price->set($field, $new_price);
1470
+				}
1471
+			}
1472
+			if (! $price instanceof EE_Price) {
1473
+				throw new RuntimeException(
1474
+					sprintf(
1475
+						esc_html__(
1476
+							'Something went wrong! A valid Price could not be generated or retrieved using the supplied data: %1$s',
1477
+							'event_espresso'
1478
+						),
1479
+						print_r($price_values, true)
1480
+					)
1481
+				);
1482
+			}
1483
+			$price->save();
1484
+			$ticket->_add_relation_to($price, 'Price');
1485
+		}
1486
+	}
1487
+
1488
+
1489
+	/**
1490
+	 * Add in our autosave ajax handlers
1491
+	 *
1492
+	 */
1493
+	protected function _ee_autosave_create_new()
1494
+	{
1495
+	}
1496
+
1497
+
1498
+	/**
1499
+	 * More autosave handlers.
1500
+	 */
1501
+	protected function _ee_autosave_edit()
1502
+	{
1503
+		// TEMPORARILY EXITING CAUSE THIS IS A TODO
1504
+	}
1505
+
1506
+
1507
+	/**
1508
+	 * @throws EE_Error
1509
+	 * @throws ReflectionException
1510
+	 */
1511
+	private function _generate_publish_box_extra_content()
1512
+	{
1513
+		// load formatter helper
1514
+		// args for getting related registrations
1515
+		$approved_query_args        = [
1516
+			[
1517
+				'REG_deleted' => 0,
1518
+				'STS_ID'      => EEM_Registration::status_id_approved,
1519
+			],
1520
+		];
1521
+		$not_approved_query_args    = [
1522
+			[
1523
+				'REG_deleted' => 0,
1524
+				'STS_ID'      => EEM_Registration::status_id_not_approved,
1525
+			],
1526
+		];
1527
+		$pending_payment_query_args = [
1528
+			[
1529
+				'REG_deleted' => 0,
1530
+				'STS_ID'      => EEM_Registration::status_id_pending_payment,
1531
+			],
1532
+		];
1533
+		// publish box
1534
+		$publish_box_extra_args = [
1535
+			'view_approved_reg_url'        => add_query_arg(
1536
+				[
1537
+					'action'      => 'default',
1538
+					'event_id'    => $this->_cpt_model_obj->ID(),
1539
+					'_reg_status' => EEM_Registration::status_id_approved,
1540
+				],
1541
+				REG_ADMIN_URL
1542
+			),
1543
+			'view_not_approved_reg_url'    => add_query_arg(
1544
+				[
1545
+					'action'      => 'default',
1546
+					'event_id'    => $this->_cpt_model_obj->ID(),
1547
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1548
+				],
1549
+				REG_ADMIN_URL
1550
+			),
1551
+			'view_pending_payment_reg_url' => add_query_arg(
1552
+				[
1553
+					'action'      => 'default',
1554
+					'event_id'    => $this->_cpt_model_obj->ID(),
1555
+					'_reg_status' => EEM_Registration::status_id_pending_payment,
1556
+				],
1557
+				REG_ADMIN_URL
1558
+			),
1559
+			'approved_regs'                => $this->_cpt_model_obj->count_related(
1560
+				'Registration',
1561
+				$approved_query_args
1562
+			),
1563
+			'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1564
+				'Registration',
1565
+				$not_approved_query_args
1566
+			),
1567
+			'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1568
+				'Registration',
1569
+				$pending_payment_query_args
1570
+			),
1571
+			'misc_pub_section_class'       => apply_filters(
1572
+				'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1573
+				'misc-pub-section'
1574
+			),
1575
+		];
1576
+		ob_start();
1577
+		do_action(
1578
+			'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1579
+			$this->_cpt_model_obj
1580
+		);
1581
+		$publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1582
+		// load template
1583
+		EEH_Template::display_template(
1584
+			EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1585
+			$publish_box_extra_args
1586
+		);
1587
+	}
1588
+
1589
+
1590
+	/**
1591
+	 * @return EE_Event
1592
+	 */
1593
+	public function get_event_object()
1594
+	{
1595
+		return $this->_cpt_model_obj;
1596
+	}
1597
+
1598
+
1599
+
1600
+
1601
+	/** METABOXES * */
1602
+	/**
1603
+	 * _register_event_editor_meta_boxes
1604
+	 * add all metaboxes related to the event_editor
1605
+	 *
1606
+	 * @return void
1607
+	 * @throws EE_Error
1608
+	 * @throws ReflectionException
1609
+	 */
1610
+	protected function _register_event_editor_meta_boxes()
1611
+	{
1612
+		$this->verify_cpt_object();
1613
+		add_meta_box(
1614
+			'espresso_event_editor_tickets',
1615
+			esc_html__('Event Datetime & Ticket', 'event_espresso'),
1616
+			[$this, 'ticket_metabox'],
1617
+			$this->page_slug,
1618
+			'normal',
1619
+			'high'
1620
+		);
1621
+		add_meta_box(
1622
+			'espresso_event_editor_event_options',
1623
+			esc_html__('Event Registration Options', 'event_espresso'),
1624
+			[$this, 'registration_options_meta_box'],
1625
+			$this->page_slug,
1626
+			'side'
1627
+		);
1628
+		// NOTE: if you're looking for other metaboxes in here,
1629
+		// where a metabox has a related management page in the admin
1630
+		// you will find it setup in the related management page's "_Hooks" file.
1631
+		// i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1632
+	}
1633
+
1634
+
1635
+	/**
1636
+	 * @throws DomainException
1637
+	 * @throws EE_Error
1638
+	 * @throws ReflectionException
1639
+	 */
1640
+	public function ticket_metabox()
1641
+	{
1642
+		$existing_datetime_ids = $existing_ticket_ids = [];
1643
+		// defaults for template args
1644
+		$template_args = [
1645
+			'existing_datetime_ids'    => '',
1646
+			'event_datetime_help_link' => '',
1647
+			'ticket_options_help_link' => '',
1648
+			'time'                     => null,
1649
+			'ticket_rows'              => '',
1650
+			'existing_ticket_ids'      => '',
1651
+			'total_ticket_rows'        => 1,
1652
+			'ticket_js_structure'      => '',
1653
+			'trash_icon'               => 'ee-lock-icon',
1654
+			'disabled'                 => '',
1655
+		];
1656
+		$event_id      = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1657
+		/**
1658
+		 * 1. Start with retrieving Datetimes
1659
+		 * 2. Fore each datetime get related tickets
1660
+		 * 3. For each ticket get related prices
1661
+		 */
1662
+		$times          = EEM_Datetime::instance()->get_all_event_dates($event_id);
1663
+		$first_datetime = reset($times);
1664
+		// do we get related tickets?
1665
+		if (
1666
+			$first_datetime instanceof EE_Datetime
1667
+			&& $first_datetime->ID() !== 0
1668
+		) {
1669
+			$existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1670
+			$template_args['time']   = $first_datetime;
1671
+			$related_tickets         = $first_datetime->tickets(
1672
+				[
1673
+					['OR' => ['TKT_deleted' => 1, 'TKT_deleted*' => 0]],
1674
+					'default_where_conditions' => 'none',
1675
+				]
1676
+			);
1677
+			if (! empty($related_tickets)) {
1678
+				$template_args['total_ticket_rows'] = count($related_tickets);
1679
+				$row                                = 0;
1680
+				foreach ($related_tickets as $ticket) {
1681
+					$existing_ticket_ids[]        = $ticket->get('TKT_ID');
1682
+					$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1683
+					$row++;
1684
+				}
1685
+			} else {
1686
+				$template_args['total_ticket_rows'] = 1;
1687
+				/** @type EE_Ticket $ticket */
1688
+				$ticket                       = EEM_Ticket::instance()->create_default_object();
1689
+				$template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1690
+			}
1691
+		} else {
1692
+			$template_args['time']        = $times[0];
1693
+			$tickets                      = EEM_Ticket::instance()->get_all_default_tickets();
1694
+			$template_args['ticket_rows'] .= $this->_get_ticket_row($tickets[1]);
1695
+			// NOTE: we're just sending the first default row
1696
+			// (decaf can't manage default tickets so this should be sufficient);
1697
+		}
1698
+		$template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1699
+			'event_editor_event_datetimes_help_tab'
1700
+		);
1701
+		$template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1702
+		$template_args['existing_datetime_ids']    = implode(',', $existing_datetime_ids);
1703
+		$template_args['existing_ticket_ids']      = implode(',', $existing_ticket_ids);
1704
+		$template_args['ticket_js_structure']      = $this->_get_ticket_row(
1705
+			EEM_Ticket::instance()->create_default_object(),
1706
+			true
1707
+		);
1708
+		$template                                  = apply_filters(
1709
+			'FHEE__Events_Admin_Page__ticket_metabox__template',
1710
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1711
+		);
1712
+		EEH_Template::display_template($template, $template_args);
1713
+	}
1714
+
1715
+
1716
+	/**
1717
+	 * Setup an individual ticket form for the decaf event editor page
1718
+	 *
1719
+	 * @access private
1720
+	 * @param EE_Ticket $ticket   the ticket object
1721
+	 * @param boolean   $skeleton whether we're generating a skeleton for js manipulation
1722
+	 * @param int       $row
1723
+	 * @return string generated html for the ticket row.
1724
+	 * @throws EE_Error
1725
+	 * @throws ReflectionException
1726
+	 */
1727
+	private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1728
+	{
1729
+		$template_args = [
1730
+			'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1731
+			'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1732
+				: '',
1733
+			'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1734
+			'TKT_ID'              => $ticket->get('TKT_ID'),
1735
+			'TKT_name'            => $ticket->get('TKT_name'),
1736
+			'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1737
+			'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1738
+			'TKT_is_default'      => $ticket->get('TKT_is_default'),
1739
+			'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1740
+			'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1741
+			'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1742
+			'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1743
+									 && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1744
+				? 'trash-icon dashicons dashicons-post-trash clickable' : 'ee-lock-icon',
1745
+			'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1746
+				: ' disabled=disabled',
1747
+		];
1748
+		$price         = $ticket->ID() !== 0
1749
+			? $ticket->get_first_related('Price', ['default_where_conditions' => 'none'])
1750
+			: null;
1751
+		$price         = $price instanceof EE_Price
1752
+			? $price
1753
+			: EEM_Price::instance()->create_default_object();
1754
+		$price_args    = [
1755
+			'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1756
+			'PRC_amount'            => $price->get('PRC_amount'),
1757
+			'PRT_ID'                => $price->get('PRT_ID'),
1758
+			'PRC_ID'                => $price->get('PRC_ID'),
1759
+			'PRC_is_default'        => $price->get('PRC_is_default'),
1760
+		];
1761
+		// make sure we have default start and end dates if skeleton
1762
+		// handle rows that should NOT be empty
1763
+		if (empty($template_args['TKT_start_date'])) {
1764
+			// if empty then the start date will be now.
1765
+			$template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1766
+		}
1767
+		if (empty($template_args['TKT_end_date'])) {
1768
+			// get the earliest datetime (if present);
1769
+			$earliest_datetime             = $this->_cpt_model_obj->ID() > 0
1770
+				? $this->_cpt_model_obj->get_first_related(
1771
+					'Datetime',
1772
+					['order_by' => ['DTT_EVT_start' => 'ASC']]
1773
+				)
1774
+				: null;
1775
+			$template_args['TKT_end_date'] = $earliest_datetime instanceof EE_Datetime
1776
+				? $earliest_datetime->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a')
1777
+				: date('Y-m-d h:i a', mktime(0, 0, 0, date('m'), date('d') + 7, date('Y')));
1778
+		}
1779
+		$template_args = array_merge($template_args, $price_args);
1780
+		$template      = apply_filters(
1781
+			'FHEE__Events_Admin_Page__get_ticket_row__template',
1782
+			EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1783
+			$ticket
1784
+		);
1785
+		return EEH_Template::display_template($template, $template_args, true);
1786
+	}
1787
+
1788
+
1789
+	/**
1790
+	 * @throws EE_Error
1791
+	 * @throws ReflectionException
1792
+	 */
1793
+	public function registration_options_meta_box()
1794
+	{
1795
+		$yes_no_values             = [
1796
+			['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
1797
+			['id' => false, 'text' => esc_html__('No', 'event_espresso')],
1798
+		];
1799
+		$default_reg_status_values = EEM_Registration::reg_status_array(
1800
+			[
1801
+				EEM_Registration::status_id_cancelled,
1802
+				EEM_Registration::status_id_declined,
1803
+				EEM_Registration::status_id_incomplete,
1804
+			],
1805
+			true
1806
+		);
1807
+		// $template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1808
+		$template_args['_event']                          = $this->_cpt_model_obj;
1809
+		$template_args['event']                           = $this->_cpt_model_obj;
1810
+		$template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
1811
+		$template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
1812
+		$template_args['default_registration_status']     = EEH_Form_Fields::select_input(
1813
+			'default_reg_status',
1814
+			$default_reg_status_values,
1815
+			$this->_cpt_model_obj->default_registration_status()
1816
+		);
1817
+		$template_args['display_description']             = EEH_Form_Fields::select_input(
1818
+			'display_desc',
1819
+			$yes_no_values,
1820
+			$this->_cpt_model_obj->display_description()
1821
+		);
1822
+		$template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
1823
+			'display_ticket_selector',
1824
+			$yes_no_values,
1825
+			$this->_cpt_model_obj->display_ticket_selector(),
1826
+			'',
1827
+			'',
1828
+			false
1829
+		);
1830
+		$template_args['additional_registration_options'] = apply_filters(
1831
+			'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1832
+			'',
1833
+			$template_args,
1834
+			$yes_no_values,
1835
+			$default_reg_status_values
1836
+		);
1837
+		EEH_Template::display_template(
1838
+			EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1839
+			$template_args
1840
+		);
1841
+	}
1842
+
1843
+
1844
+	/**
1845
+	 * _get_events()
1846
+	 * This method simply returns all the events (for the given _view and paging)
1847
+	 *
1848
+	 * @access public
1849
+	 * @param int  $per_page     count of items per page (20 default);
1850
+	 * @param int  $current_page what is the current page being viewed.
1851
+	 * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1852
+	 *                           If FALSE then we return an array of event objects
1853
+	 *                           that match the given _view and paging parameters.
1854
+	 * @return array|int         an array of event objects or a count of them.
1855
+	 * @throws Exception
1856
+	 */
1857
+	public function get_events($per_page = 10, $current_page = 1, $count = false)
1858
+	{
1859
+		$EEM_Event   = $this->_event_model();
1860
+		$offset      = ($current_page - 1) * $per_page;
1861
+		$limit       = $count ? null : $offset . ',' . $per_page;
1862
+		$orderby     = $this->request->getRequestParam('orderby', 'EVT_ID');
1863
+		$order       = $this->request->getRequestParam('order', 'DESC');
1864
+		$month_range = $this->request->getRequestParam('month_range');
1865
+		if ($month_range) {
1866
+			$pieces = explode(' ', $month_range, 3);
1867
+			// simulate the FIRST day of the month, that fixes issues for months like February
1868
+			// where PHP doesn't know what to assume for date.
1869
+			// @see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1870
+			$month_r = ! empty($pieces[0]) ? date('m', EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1871
+			$year_r  = ! empty($pieces[1]) ? $pieces[1] : '';
1872
+		}
1873
+		$where  = [];
1874
+		$status = $this->request->getRequestParam('status');
1875
+		// determine what post_status our condition will have for the query.
1876
+		switch ($status) {
1877
+			case 'month':
1878
+			case 'today':
1879
+			case null:
1880
+			case 'all':
1881
+				break;
1882
+			case 'draft':
1883
+				$where['status'] = ['IN', ['draft', 'auto-draft']];
1884
+				break;
1885
+			default:
1886
+				$where['status'] = $status;
1887
+		}
1888
+		// categories?
1889
+		$category = $this->request->getRequestParam('EVT_CAT', 0, 'int');
1890
+		if ($category) {
1891
+			$where['Term_Taxonomy.taxonomy'] = EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY;
1892
+			$where['Term_Taxonomy.term_id']  = $category;
1893
+		}
1894
+		// date where conditions
1895
+		$start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1896
+		if ($month_range) {
1897
+			$DateTime = new DateTime(
1898
+				$year_r . '-' . $month_r . '-01 00:00:00',
1899
+				new DateTimeZone('UTC')
1900
+			);
1901
+			$start    = $DateTime->getTimestamp();
1902
+			// set the datetime to be the end of the month
1903
+			$DateTime->setDate(
1904
+				$year_r,
1905
+				$month_r,
1906
+				$DateTime->format('t')
1907
+			)->setTime(23, 59, 59);
1908
+			$end                             = $DateTime->getTimestamp();
1909
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1910
+		} elseif ($status === 'today') {
1911
+			$DateTime                        =
1912
+				new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1913
+			$start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1914
+			$end                             = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1915
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1916
+		} elseif ($status === 'month') {
1917
+			$now                             = date('Y-m-01');
1918
+			$DateTime                        =
1919
+				new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1920
+			$start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1921
+			$end                             = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1922
+														->setTime(23, 59, 59)
1923
+														->format(implode(' ', $start_formats));
1924
+			$where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1925
+		}
1926
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1927
+			$where['EVT_wp_user'] = get_current_user_id();
1928
+		} else {
1929
+			if (! isset($where['status'])) {
1930
+				if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1931
+					$where['OR'] = [
1932
+						'status*restrict_private' => ['!=', 'private'],
1933
+						'AND'                     => [
1934
+							'status*inclusive' => ['=', 'private'],
1935
+							'EVT_wp_user'      => get_current_user_id(),
1936
+						],
1937
+					];
1938
+				}
1939
+			}
1940
+		}
1941
+		$wp_user = $this->request->getRequestParam('EVT_wp_user', 0, 'int');
1942
+		if (
1943
+			$wp_user
1944
+			&& $wp_user !== get_current_user_id()
1945
+			&& EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
1946
+		) {
1947
+			$where['EVT_wp_user'] = $wp_user;
1948
+		}
1949
+		// search query handling
1950
+		$search_term = $this->request->getRequestParam('s');
1951
+		if ($search_term) {
1952
+			$search_term = '%' . $search_term . '%';
1953
+			$where['OR'] = [
1954
+				'EVT_name'       => ['LIKE', $search_term],
1955
+				'EVT_desc'       => ['LIKE', $search_term],
1956
+				'EVT_short_desc' => ['LIKE', $search_term],
1957
+			];
1958
+		}
1959
+		// filter events by venue.
1960
+		$venue = $this->request->getRequestParam('venue', 0, 'int');
1961
+		if ($venue) {
1962
+			$where['Venue.VNU_ID'] = $venue;
1963
+		}
1964
+		$request_params = $this->request->requestParams();
1965
+		$where          = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $request_params);
1966
+		$query_params   = apply_filters(
1967
+			'FHEE__Events_Admin_Page__get_events__query_params',
1968
+			[
1969
+				$where,
1970
+				'limit'    => $limit,
1971
+				'order_by' => $orderby,
1972
+				'order'    => $order,
1973
+				'group_by' => 'EVT_ID',
1974
+			],
1975
+			$request_params
1976
+		);
1977
+
1978
+		// let's first check if we have special requests coming in.
1979
+		$active_status = $this->request->getRequestParam('active_status');
1980
+		if ($active_status) {
1981
+			switch ($active_status) {
1982
+				case 'upcoming':
1983
+					return $EEM_Event->get_upcoming_events($query_params, $count);
1984
+				case 'expired':
1985
+					return $EEM_Event->get_expired_events($query_params, $count);
1986
+				case 'active':
1987
+					return $EEM_Event->get_active_events($query_params, $count);
1988
+				case 'inactive':
1989
+					return $EEM_Event->get_inactive_events($query_params, $count);
1990
+			}
1991
+		}
1992
+
1993
+		return $count ? $EEM_Event->count([$where], 'EVT_ID', true) : $EEM_Event->get_all($query_params);
1994
+	}
1995
+
1996
+
1997
+	/**
1998
+	 * handling for WordPress CPT actions (trash, restore, delete)
1999
+	 *
2000
+	 * @param string $post_id
2001
+	 * @throws EE_Error
2002
+	 * @throws ReflectionException
2003
+	 */
2004
+	public function trash_cpt_item($post_id)
2005
+	{
2006
+		$this->request->setRequestParam('EVT_ID', $post_id);
2007
+		$this->_trash_or_restore_event('trash', false);
2008
+	}
2009
+
2010
+
2011
+	/**
2012
+	 * @param string $post_id
2013
+	 * @throws EE_Error
2014
+	 * @throws ReflectionException
2015
+	 */
2016
+	public function restore_cpt_item($post_id)
2017
+	{
2018
+		$this->request->setRequestParam('EVT_ID', $post_id);
2019
+		$this->_trash_or_restore_event('draft', false);
2020
+	}
2021
+
2022
+
2023
+	/**
2024
+	 * @param string $post_id
2025
+	 * @throws EE_Error
2026
+	 * @throws EE_Error
2027
+	 */
2028
+	public function delete_cpt_item($post_id)
2029
+	{
2030
+		throw new EE_Error(
2031
+			esc_html__(
2032
+				'Please contact Event Espresso support with the details of the steps taken to produce this error.',
2033
+				'event_espresso'
2034
+			)
2035
+		);
2036
+		// $this->request->setRequestParam('EVT_ID', $post_id);
2037
+		// $this->_delete_event();
2038
+	}
2039
+
2040
+
2041
+	/**
2042
+	 * _trash_or_restore_event
2043
+	 *
2044
+	 * @access protected
2045
+	 * @param string $event_status
2046
+	 * @param bool   $redirect_after
2047
+	 * @throws EE_Error
2048
+	 * @throws EE_Error
2049
+	 * @throws ReflectionException
2050
+	 */
2051
+	protected function _trash_or_restore_event($event_status = 'trash', $redirect_after = true)
2052
+	{
2053
+		// determine the event id and set to array.
2054
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
2055
+		// loop thru events
2056
+		if ($EVT_ID) {
2057
+			// clean status
2058
+			$event_status = sanitize_key($event_status);
2059
+			// grab status
2060
+			if (! empty($event_status)) {
2061
+				$success = $this->_change_event_status($EVT_ID, $event_status);
2062
+			} else {
2063
+				$success = false;
2064
+				$msg     = esc_html__(
2065
+					'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2066
+					'event_espresso'
2067
+				);
2068
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2069
+			}
2070
+		} else {
2071
+			$success = false;
2072
+			$msg     = esc_html__(
2073
+				'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
2074
+				'event_espresso'
2075
+			);
2076
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2077
+		}
2078
+		$action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2079
+		if ($redirect_after) {
2080
+			$this->_redirect_after_action($success, 'Event', $action, ['action' => 'default']);
2081
+		}
2082
+	}
2083
+
2084
+
2085
+	/**
2086
+	 * _trash_or_restore_events
2087
+	 *
2088
+	 * @access protected
2089
+	 * @param string $event_status
2090
+	 * @return void
2091
+	 * @throws EE_Error
2092
+	 * @throws EE_Error
2093
+	 * @throws ReflectionException
2094
+	 */
2095
+	protected function _trash_or_restore_events($event_status = 'trash')
2096
+	{
2097
+		// clean status
2098
+		$event_status = sanitize_key($event_status);
2099
+		// grab status
2100
+		if (! empty($event_status)) {
2101
+			$success = true;
2102
+			// determine the event id and set to array.
2103
+			$EVT_IDs = $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2104
+			// loop thru events
2105
+			foreach ($EVT_IDs as $EVT_ID) {
2106
+				if ($EVT_ID = absint($EVT_ID)) {
2107
+					$results = $this->_change_event_status($EVT_ID, $event_status);
2108
+					$success = $results !== false ? $success : false;
2109
+				} else {
2110
+					$msg = sprintf(
2111
+						esc_html__(
2112
+							'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
2113
+							'event_espresso'
2114
+						),
2115
+						$EVT_ID
2116
+					);
2117
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2118
+					$success = false;
2119
+				}
2120
+			}
2121
+		} else {
2122
+			$success = false;
2123
+			$msg     = esc_html__(
2124
+				'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2125
+				'event_espresso'
2126
+			);
2127
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2128
+		}
2129
+		// in order to force a pluralized result message we need to send back a success status greater than 1
2130
+		$success = $success ? 2 : false;
2131
+		$action  = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2132
+		$this->_redirect_after_action($success, 'Events', $action, ['action' => 'default']);
2133
+	}
2134
+
2135
+
2136
+	/**
2137
+	 * @param int    $EVT_ID
2138
+	 * @param string $event_status
2139
+	 * @return bool
2140
+	 * @throws EE_Error
2141
+	 * @throws ReflectionException
2142
+	 */
2143
+	private function _change_event_status($EVT_ID = 0, $event_status = '')
2144
+	{
2145
+		// grab event id
2146
+		if (! $EVT_ID) {
2147
+			$msg = esc_html__(
2148
+				'An error occurred. No Event ID or an invalid Event ID was received.',
2149
+				'event_espresso'
2150
+			);
2151
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2152
+			return false;
2153
+		}
2154
+		$this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2155
+		// clean status
2156
+		$event_status = sanitize_key($event_status);
2157
+		// grab status
2158
+		if (empty($event_status)) {
2159
+			$msg = esc_html__(
2160
+				'An error occurred. No Event Status or an invalid Event Status was received.',
2161
+				'event_espresso'
2162
+			);
2163
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2164
+			return false;
2165
+		}
2166
+		// was event trashed or restored ?
2167
+		switch ($event_status) {
2168
+			case 'draft':
2169
+				$action = 'restored from the trash';
2170
+				$hook   = 'AHEE_event_restored_from_trash';
2171
+				break;
2172
+			case 'trash':
2173
+				$action = 'moved to the trash';
2174
+				$hook   = 'AHEE_event_moved_to_trash';
2175
+				break;
2176
+			default:
2177
+				$action = 'updated';
2178
+				$hook   = false;
2179
+		}
2180
+		// use class to change status
2181
+		$this->_cpt_model_obj->set_status($event_status);
2182
+		$success = $this->_cpt_model_obj->save();
2183
+		if (! $success) {
2184
+			$msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2185
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2186
+			return false;
2187
+		}
2188
+		if ($hook) {
2189
+			do_action($hook);
2190
+		}
2191
+		return true;
2192
+	}
2193
+
2194
+
2195
+	/**
2196
+	 * @param array $event_ids
2197
+	 * @return array
2198
+	 * @since   4.10.23.p
2199
+	 */
2200
+	private function cleanEventIds(array $event_ids)
2201
+	{
2202
+		return array_map('absint', $event_ids);
2203
+	}
2204
+
2205
+
2206
+	/**
2207
+	 * @return array
2208
+	 * @since   4.10.23.p
2209
+	 */
2210
+	private function getEventIdsFromRequest()
2211
+	{
2212
+		return $this->request->getRequestParam('EVT_IDs', [], 'int', true, ',');
2213
+	}
2214
+
2215
+
2216
+	/**
2217
+	 * @param bool $preview_delete
2218
+	 * @throws EE_Error
2219
+	 */
2220
+	protected function _delete_event($preview_delete = true)
2221
+	{
2222
+		$this->_delete_events($preview_delete);
2223
+	}
2224
+
2225
+
2226
+	/**
2227
+	 * Gets the tree traversal batch persister.
2228
+	 *
2229
+	 * @return NodeGroupDao
2230
+	 * @throws InvalidArgumentException
2231
+	 * @throws InvalidDataTypeException
2232
+	 * @throws InvalidInterfaceException
2233
+	 * @since 4.10.12.p
2234
+	 */
2235
+	protected function getModelObjNodeGroupPersister()
2236
+	{
2237
+		if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2238
+			$this->model_obj_node_group_persister =
2239
+				$this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2240
+		}
2241
+		return $this->model_obj_node_group_persister;
2242
+	}
2243
+
2244
+
2245
+	/**
2246
+	 * @param bool $preview_delete
2247
+	 * @return void
2248
+	 * @throws EE_Error
2249
+	 */
2250
+	protected function _delete_events($preview_delete = true)
2251
+	{
2252
+		$event_ids = $this->getEventIdsFromRequest();
2253
+		if ($preview_delete) {
2254
+			$this->generateDeletionPreview($event_ids);
2255
+		} else {
2256
+			EEM_Event::instance()->delete_permanently([['EVT_ID' => ['IN', $event_ids]]]);
2257
+		}
2258
+	}
2259
+
2260
+
2261
+	/**
2262
+	 * @param array $event_ids
2263
+	 */
2264
+	protected function generateDeletionPreview(array $event_ids)
2265
+	{
2266
+		$event_ids = $this->cleanEventIds($event_ids);
2267
+		// Set a code we can use to reference this deletion task in the batch jobs and preview page.
2268
+		$deletion_job_code = $this->getModelObjNodeGroupPersister()->generateGroupCode();
2269
+		$return_url        = EE_Admin_Page::add_query_args_and_nonce(
2270
+			[
2271
+				'action'            => 'preview_deletion',
2272
+				'deletion_job_code' => $deletion_job_code,
2273
+			],
2274
+			$this->_admin_base_url
2275
+		);
2276
+		EEH_URL::safeRedirectAndExit(
2277
+			EE_Admin_Page::add_query_args_and_nonce(
2278
+				[
2279
+					'page'              => 'espresso_batch',
2280
+					'batch'             => EED_Batch::batch_job,
2281
+					'EVT_IDs'           => $event_ids,
2282
+					'deletion_job_code' => $deletion_job_code,
2283
+					'job_handler'       => urlencode('EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion'),
2284
+					'return_url'        => urlencode($return_url),
2285
+				],
2286
+				admin_url()
2287
+			)
2288
+		);
2289
+	}
2290
+
2291
+
2292
+	/**
2293
+	 * Checks for a POST submission
2294
+	 *
2295
+	 * @since 4.10.12.p
2296
+	 */
2297
+	protected function confirmDeletion()
2298
+	{
2299
+		$deletion_redirect_logic =
2300
+			$this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion');
2301
+		$deletion_redirect_logic->handle($this->get_request_data(), $this->admin_base_url());
2302
+	}
2303
+
2304
+
2305
+	/**
2306
+	 * A page for users to preview what exactly will be deleted, and confirm they want to delete it.
2307
+	 *
2308
+	 * @throws EE_Error
2309
+	 * @since 4.10.12.p
2310
+	 */
2311
+	protected function previewDeletion()
2312
+	{
2313
+		$preview_deletion_logic =
2314
+			$this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\PreviewDeletion');
2315
+		$this->set_template_args($preview_deletion_logic->handle($this->get_request_data(), $this->admin_base_url()));
2316
+		$this->display_admin_page_with_no_sidebar();
2317
+	}
2318
+
2319
+
2320
+	/**
2321
+	 * get total number of events
2322
+	 *
2323
+	 * @access public
2324
+	 * @return int
2325
+	 * @throws EE_Error
2326
+	 * @throws EE_Error
2327
+	 */
2328
+	public function total_events()
2329
+	{
2330
+		return EEM_Event::instance()->count(
2331
+			['caps' => 'read_admin'],
2332
+			'EVT_ID',
2333
+			true
2334
+		);
2335
+	}
2336
+
2337
+
2338
+	/**
2339
+	 * get total number of draft events
2340
+	 *
2341
+	 * @access public
2342
+	 * @return int
2343
+	 * @throws EE_Error
2344
+	 * @throws EE_Error
2345
+	 */
2346
+	public function total_events_draft()
2347
+	{
2348
+		return EEM_Event::instance()->count(
2349
+			[
2350
+				['status' => ['IN', ['draft', 'auto-draft']]],
2351
+				'caps' => 'read_admin',
2352
+			],
2353
+			'EVT_ID',
2354
+			true
2355
+		);
2356
+	}
2357
+
2358
+
2359
+	/**
2360
+	 * get total number of trashed events
2361
+	 *
2362
+	 * @access public
2363
+	 * @return int
2364
+	 * @throws EE_Error
2365
+	 * @throws EE_Error
2366
+	 */
2367
+	public function total_trashed_events()
2368
+	{
2369
+		return EEM_Event::instance()->count(
2370
+			[
2371
+				['status' => 'trash'],
2372
+				'caps' => 'read_admin',
2373
+			],
2374
+			'EVT_ID',
2375
+			true
2376
+		);
2377
+	}
2378
+
2379
+
2380
+	/**
2381
+	 *    _default_event_settings
2382
+	 *    This generates the Default Settings Tab
2383
+	 *
2384
+	 * @return void
2385
+	 * @throws EE_Error
2386
+	 */
2387
+	protected function _default_event_settings()
2388
+	{
2389
+		$this->_set_add_edit_form_tags('update_default_event_settings');
2390
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
2391
+		$this->_template_args['admin_page_content'] = $this->_default_event_settings_form()->get_html();
2392
+		$this->display_admin_page_with_sidebar();
2393
+	}
2394
+
2395
+
2396
+	/**
2397
+	 * Return the form for event settings.
2398
+	 *
2399
+	 * @return EE_Form_Section_Proper
2400
+	 * @throws EE_Error
2401
+	 */
2402
+	protected function _default_event_settings_form()
2403
+	{
2404
+		$registration_config              = EE_Registry::instance()->CFG->registration;
2405
+		$registration_stati_for_selection = EEM_Registration::reg_status_array(
2406
+		// exclude
2407
+			[
2408
+				EEM_Registration::status_id_cancelled,
2409
+				EEM_Registration::status_id_declined,
2410
+				EEM_Registration::status_id_incomplete,
2411
+				EEM_Registration::status_id_wait_list,
2412
+			],
2413
+			true
2414
+		);
2415
+		return new EE_Form_Section_Proper(
2416
+			[
2417
+				'name'            => 'update_default_event_settings',
2418
+				'html_id'         => 'update_default_event_settings',
2419
+				'html_class'      => 'form-table',
2420
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2421
+				'subsections'     => apply_filters(
2422
+					'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2423
+					[
2424
+						'default_reg_status'  => new EE_Select_Input(
2425
+							$registration_stati_for_selection,
2426
+							[
2427
+								'default'         => isset($registration_config->default_STS_ID)
2428
+													 && array_key_exists(
2429
+														 $registration_config->default_STS_ID,
2430
+														 $registration_stati_for_selection
2431
+													 )
2432
+									? sanitize_text_field($registration_config->default_STS_ID)
2433
+									: EEM_Registration::status_id_pending_payment,
2434
+								'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2435
+													 . EEH_Template::get_help_tab_link(
2436
+														 'default_settings_status_help_tab'
2437
+													 ),
2438
+								'html_help_text'  => esc_html__(
2439
+									'This setting allows you to preselect what the default registration status setting is when creating an event.  Note that changing this setting does NOT retroactively apply it to existing events.',
2440
+									'event_espresso'
2441
+								),
2442
+							]
2443
+						),
2444
+						'default_max_tickets' => new EE_Integer_Input(
2445
+							[
2446
+								'default'         => isset($registration_config->default_maximum_number_of_tickets)
2447
+									? $registration_config->default_maximum_number_of_tickets
2448
+									: EEM_Event::get_default_additional_limit(),
2449
+								'html_label_text' => esc_html__(
2450
+									'Default Maximum Tickets Allowed Per Order:',
2451
+									'event_espresso'
2452
+								)
2453
+								. EEH_Template::get_help_tab_link(
2454
+									'default_maximum_tickets_help_tab"'
2455
+								),
2456
+								'html_help_text'  => esc_html__(
2457
+									'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2458
+									'event_espresso'
2459
+								),
2460
+							]
2461
+						),
2462
+					]
2463
+				),
2464
+			]
2465
+		);
2466
+	}
2467
+
2468
+
2469
+	/**
2470
+	 * _update_default_event_settings
2471
+	 *
2472
+	 * @access protected
2473
+	 * @return void
2474
+	 * @throws EE_Error
2475
+	 */
2476
+	protected function _update_default_event_settings()
2477
+	{
2478
+		$registration_config = EE_Registry::instance()->CFG->registration;
2479
+		$form                = $this->_default_event_settings_form();
2480
+		if ($form->was_submitted()) {
2481
+			$form->receive_form_submission();
2482
+			if ($form->is_valid()) {
2483
+				$valid_data = $form->valid_data();
2484
+				if (isset($valid_data['default_reg_status'])) {
2485
+					$registration_config->default_STS_ID = $valid_data['default_reg_status'];
2486
+				}
2487
+				if (isset($valid_data['default_max_tickets'])) {
2488
+					$registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2489
+				}
2490
+				// update because data was valid!
2491
+				EE_Registry::instance()->CFG->update_espresso_config();
2492
+				EE_Error::overwrite_success();
2493
+				EE_Error::add_success(
2494
+					esc_html__('Default Event Settings were updated', 'event_espresso')
2495
+				);
2496
+			}
2497
+		}
2498
+		$this->_redirect_after_action(0, '', '', ['action' => 'default_event_settings'], true);
2499
+	}
2500
+
2501
+
2502
+	/*************        Templates        *************
21 2503
      *
22
-     * @var EE_Event $_event
23
-     */
24
-    protected $_event;
25
-
26
-
27
-    /**
28
-     * This will hold the category object for category_details screen.
29
-     *
30
-     * @var stdClass $_category
31
-     */
32
-    protected $_category;
33
-
34
-
35
-    /**
36
-     * This will hold the event model instance
37
-     *
38
-     * @var EEM_Event $_event_model
39
-     */
40
-    protected $_event_model;
41
-
42
-
43
-    /**
44
-     * @var EE_Event
45
-     */
46
-    protected $_cpt_model_obj = false;
47
-
48
-
49
-    /**
50
-     * @var NodeGroupDao
51
-     */
52
-    protected $model_obj_node_group_persister;
53
-
54
-
55
-    /**
56
-     * Initialize page props for this admin page group.
57
-     */
58
-    protected function _init_page_props()
59
-    {
60
-        $this->page_slug        = EVENTS_PG_SLUG;
61
-        $this->page_label       = EVENTS_LABEL;
62
-        $this->_admin_base_url  = EVENTS_ADMIN_URL;
63
-        $this->_admin_base_path = EVENTS_ADMIN;
64
-        $this->_cpt_model_names = [
65
-            'create_new' => 'EEM_Event',
66
-            'edit'       => 'EEM_Event',
67
-        ];
68
-        $this->_cpt_edit_routes = [
69
-            'espresso_events' => 'edit',
70
-        ];
71
-        add_action(
72
-            'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
73
-            [$this, 'verify_event_edit'],
74
-            10,
75
-            2
76
-        );
77
-    }
78
-
79
-
80
-    /**
81
-     * Sets the ajax hooks used for this admin page group.
82
-     */
83
-    protected function _ajax_hooks()
84
-    {
85
-        add_action('wp_ajax_ee_save_timezone_setting', [$this, 'saveTimezoneString']);
86
-    }
87
-
88
-
89
-    /**
90
-     * Sets the page properties for this admin page group.
91
-     */
92
-    protected function _define_page_props()
93
-    {
94
-        $this->_admin_page_title = EVENTS_LABEL;
95
-        $this->_labels           = [
96
-            'buttons'      => [
97
-                'add'             => esc_html__('Add New Event', 'event_espresso'),
98
-                'edit'            => esc_html__('Edit Event', 'event_espresso'),
99
-                'delete'          => esc_html__('Delete Event', 'event_espresso'),
100
-                'add_category'    => esc_html__('Add New Category', 'event_espresso'),
101
-                'edit_category'   => esc_html__('Edit Category', 'event_espresso'),
102
-                'delete_category' => esc_html__('Delete Category', 'event_espresso'),
103
-            ],
104
-            'editor_title' => [
105
-                'espresso_events' => esc_html__('Enter event title here', 'event_espresso'),
106
-            ],
107
-            'publishbox'   => [
108
-                'create_new'        => esc_html__('Save New Event', 'event_espresso'),
109
-                'edit'              => esc_html__('Update Event', 'event_espresso'),
110
-                'add_category'      => esc_html__('Save New Category', 'event_espresso'),
111
-                'edit_category'     => esc_html__('Update Category', 'event_espresso'),
112
-                'template_settings' => esc_html__('Update Settings', 'event_espresso'),
113
-            ],
114
-        ];
115
-    }
116
-
117
-
118
-    /**
119
-     * Sets the page routes property for this admin page group.
120
-     */
121
-    protected function _set_page_routes()
122
-    {
123
-        // load formatter helper
124
-        // load field generator helper
125
-        // is there a evt_id in the request?
126
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
127
-        $EVT_ID = $this->request->getRequestParam('post', $EVT_ID, 'int');
128
-
129
-        $this->_page_routes = [
130
-            'default'                       => [
131
-                'func'       => '_events_overview_list_table',
132
-                'capability' => 'ee_read_events',
133
-            ],
134
-            'create_new'                    => [
135
-                'func'       => '_create_new_cpt_item',
136
-                'capability' => 'ee_edit_events',
137
-            ],
138
-            'edit'                          => [
139
-                'func'       => '_edit_cpt_item',
140
-                'capability' => 'ee_edit_event',
141
-                'obj_id'     => $EVT_ID,
142
-            ],
143
-            'copy_event'                    => [
144
-                'func'       => '_copy_events',
145
-                'capability' => 'ee_edit_event',
146
-                'obj_id'     => $EVT_ID,
147
-                'noheader'   => true,
148
-            ],
149
-            'trash_event'                   => [
150
-                'func'       => '_trash_or_restore_event',
151
-                'args'       => ['event_status' => 'trash'],
152
-                'capability' => 'ee_delete_event',
153
-                'obj_id'     => $EVT_ID,
154
-                'noheader'   => true,
155
-            ],
156
-            'trash_events'                  => [
157
-                'func'       => '_trash_or_restore_events',
158
-                'args'       => ['event_status' => 'trash'],
159
-                'capability' => 'ee_delete_events',
160
-                'noheader'   => true,
161
-            ],
162
-            'restore_event'                 => [
163
-                'func'       => '_trash_or_restore_event',
164
-                'args'       => ['event_status' => 'draft'],
165
-                'capability' => 'ee_delete_event',
166
-                'obj_id'     => $EVT_ID,
167
-                'noheader'   => true,
168
-            ],
169
-            'restore_events'                => [
170
-                'func'       => '_trash_or_restore_events',
171
-                'args'       => ['event_status' => 'draft'],
172
-                'capability' => 'ee_delete_events',
173
-                'noheader'   => true,
174
-            ],
175
-            'delete_event'                  => [
176
-                'func'       => '_delete_event',
177
-                'capability' => 'ee_delete_event',
178
-                'obj_id'     => $EVT_ID,
179
-                'noheader'   => true,
180
-            ],
181
-            'delete_events'                 => [
182
-                'func'       => '_delete_events',
183
-                'capability' => 'ee_delete_events',
184
-                'noheader'   => true,
185
-            ],
186
-            'view_report'                   => [
187
-                'func'       => '_view_report',
188
-                'capability' => 'ee_edit_events',
189
-            ],
190
-            'default_event_settings'        => [
191
-                'func'       => '_default_event_settings',
192
-                'capability' => 'manage_options',
193
-            ],
194
-            'update_default_event_settings' => [
195
-                'func'       => '_update_default_event_settings',
196
-                'capability' => 'manage_options',
197
-                'noheader'   => true,
198
-            ],
199
-            'template_settings'             => [
200
-                'func'       => '_template_settings',
201
-                'capability' => 'manage_options',
202
-            ],
203
-            // event category tab related
204
-            'add_category'                  => [
205
-                'func'       => '_category_details',
206
-                'capability' => 'ee_edit_event_category',
207
-                'args'       => ['add'],
208
-            ],
209
-            'edit_category'                 => [
210
-                'func'       => '_category_details',
211
-                'capability' => 'ee_edit_event_category',
212
-                'args'       => ['edit'],
213
-            ],
214
-            'delete_categories'             => [
215
-                'func'       => '_delete_categories',
216
-                'capability' => 'ee_delete_event_category',
217
-                'noheader'   => true,
218
-            ],
219
-            'delete_category'               => [
220
-                'func'       => '_delete_categories',
221
-                'capability' => 'ee_delete_event_category',
222
-                'noheader'   => true,
223
-            ],
224
-            'insert_category'               => [
225
-                'func'       => '_insert_or_update_category',
226
-                'args'       => ['new_category' => true],
227
-                'capability' => 'ee_edit_event_category',
228
-                'noheader'   => true,
229
-            ],
230
-            'update_category'               => [
231
-                'func'       => '_insert_or_update_category',
232
-                'args'       => ['new_category' => false],
233
-                'capability' => 'ee_edit_event_category',
234
-                'noheader'   => true,
235
-            ],
236
-            'category_list'                 => [
237
-                'func'       => '_category_list_table',
238
-                'capability' => 'ee_manage_event_categories',
239
-            ],
240
-            'preview_deletion'              => [
241
-                'func'       => 'previewDeletion',
242
-                'capability' => 'ee_delete_events',
243
-            ],
244
-            'confirm_deletion'              => [
245
-                'func'       => 'confirmDeletion',
246
-                'capability' => 'ee_delete_events',
247
-                'noheader'   => true,
248
-            ],
249
-        ];
250
-    }
251
-
252
-
253
-    /**
254
-     * Set the _page_config property for this admin page group.
255
-     */
256
-    protected function _set_page_config()
257
-    {
258
-        $post_id            = $this->request->getRequestParam('post', 0, 'int');
259
-        $EVT_CAT_ID         = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
260
-        $this->_page_config = [
261
-            'default'                => [
262
-                'nav'           => [
263
-                    'label' => esc_html__('Overview', 'event_espresso'),
264
-                    'order' => 10,
265
-                ],
266
-                'list_table'    => 'Events_Admin_List_Table',
267
-                'help_tabs'     => [
268
-                    'events_overview_help_tab'                       => [
269
-                        'title'    => esc_html__('Events Overview', 'event_espresso'),
270
-                        'filename' => 'events_overview',
271
-                    ],
272
-                    'events_overview_table_column_headings_help_tab' => [
273
-                        'title'    => esc_html__('Events Overview Table Column Headings', 'event_espresso'),
274
-                        'filename' => 'events_overview_table_column_headings',
275
-                    ],
276
-                    'events_overview_filters_help_tab'               => [
277
-                        'title'    => esc_html__('Events Overview Filters', 'event_espresso'),
278
-                        'filename' => 'events_overview_filters',
279
-                    ],
280
-                    'events_overview_view_help_tab'                  => [
281
-                        'title'    => esc_html__('Events Overview Views', 'event_espresso'),
282
-                        'filename' => 'events_overview_views',
283
-                    ],
284
-                    'events_overview_other_help_tab'                 => [
285
-                        'title'    => esc_html__('Events Overview Other', 'event_espresso'),
286
-                        'filename' => 'events_overview_other',
287
-                    ],
288
-                ],
289
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
290
-                // 'help_tour'     => array(
291
-                //     'Event_Overview_Help_Tour',
292
-                //     // 'New_Features_Test_Help_Tour' for testing multiple help tour
293
-                // ),
294
-                'qtips'         => [
295
-                    'EE_Event_List_Table_Tips',
296
-                ],
297
-                'require_nonce' => false,
298
-            ],
299
-            'create_new'             => [
300
-                'nav'           => [
301
-                    'label'      => esc_html__('Add Event', 'event_espresso'),
302
-                    'order'      => 5,
303
-                    'persistent' => false,
304
-                ],
305
-                'metaboxes'     => ['_register_event_editor_meta_boxes'],
306
-                'help_tabs'     => [
307
-                    'event_editor_help_tab'                            => [
308
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
309
-                        'filename' => 'event_editor',
310
-                    ],
311
-                    'event_editor_title_richtexteditor_help_tab'       => [
312
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
313
-                        'filename' => 'event_editor_title_richtexteditor',
314
-                    ],
315
-                    'event_editor_venue_details_help_tab'              => [
316
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
317
-                        'filename' => 'event_editor_venue_details',
318
-                    ],
319
-                    'event_editor_event_datetimes_help_tab'            => [
320
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
321
-                        'filename' => 'event_editor_event_datetimes',
322
-                    ],
323
-                    'event_editor_event_tickets_help_tab'              => [
324
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
325
-                        'filename' => 'event_editor_event_tickets',
326
-                    ],
327
-                    'event_editor_event_registration_options_help_tab' => [
328
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
329
-                        'filename' => 'event_editor_event_registration_options',
330
-                    ],
331
-                    'event_editor_tags_categories_help_tab'            => [
332
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
333
-                        'filename' => 'event_editor_tags_categories',
334
-                    ],
335
-                    'event_editor_questions_registrants_help_tab'      => [
336
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
337
-                        'filename' => 'event_editor_questions_registrants',
338
-                    ],
339
-                    'event_editor_save_new_event_help_tab'             => [
340
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
341
-                        'filename' => 'event_editor_save_new_event',
342
-                    ],
343
-                    'event_editor_other_help_tab'                      => [
344
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
345
-                        'filename' => 'event_editor_other',
346
-                    ],
347
-                ],
348
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
349
-                // 'help_tour'     => array(
350
-                //     'Event_Editor_Help_Tour',
351
-                // ),
352
-                'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
353
-                'require_nonce' => false,
354
-            ],
355
-            'edit'                   => [
356
-                'nav'           => [
357
-                    'label'      => esc_html__('Edit Event', 'event_espresso'),
358
-                    'order'      => 5,
359
-                    'persistent' => false,
360
-                    'url'        => $post_id
361
-                        ? EE_Admin_Page::add_query_args_and_nonce(
362
-                            ['post' => $post_id, 'action' => 'edit'],
363
-                            $this->_current_page_view_url
364
-                        )
365
-                        : $this->_admin_base_url,
366
-                ],
367
-                'metaboxes'     => ['_register_event_editor_meta_boxes'],
368
-                'help_tabs'     => [
369
-                    'event_editor_help_tab'                            => [
370
-                        'title'    => esc_html__('Event Editor', 'event_espresso'),
371
-                        'filename' => 'event_editor',
372
-                    ],
373
-                    'event_editor_title_richtexteditor_help_tab'       => [
374
-                        'title'    => esc_html__('Event Title & Rich Text Editor', 'event_espresso'),
375
-                        'filename' => 'event_editor_title_richtexteditor',
376
-                    ],
377
-                    'event_editor_venue_details_help_tab'              => [
378
-                        'title'    => esc_html__('Event Venue Details', 'event_espresso'),
379
-                        'filename' => 'event_editor_venue_details',
380
-                    ],
381
-                    'event_editor_event_datetimes_help_tab'            => [
382
-                        'title'    => esc_html__('Event Datetimes', 'event_espresso'),
383
-                        'filename' => 'event_editor_event_datetimes',
384
-                    ],
385
-                    'event_editor_event_tickets_help_tab'              => [
386
-                        'title'    => esc_html__('Event Tickets', 'event_espresso'),
387
-                        'filename' => 'event_editor_event_tickets',
388
-                    ],
389
-                    'event_editor_event_registration_options_help_tab' => [
390
-                        'title'    => esc_html__('Event Registration Options', 'event_espresso'),
391
-                        'filename' => 'event_editor_event_registration_options',
392
-                    ],
393
-                    'event_editor_tags_categories_help_tab'            => [
394
-                        'title'    => esc_html__('Event Tags & Categories', 'event_espresso'),
395
-                        'filename' => 'event_editor_tags_categories',
396
-                    ],
397
-                    'event_editor_questions_registrants_help_tab'      => [
398
-                        'title'    => esc_html__('Questions for Registrants', 'event_espresso'),
399
-                        'filename' => 'event_editor_questions_registrants',
400
-                    ],
401
-                    'event_editor_save_new_event_help_tab'             => [
402
-                        'title'    => esc_html__('Save New Event', 'event_espresso'),
403
-                        'filename' => 'event_editor_save_new_event',
404
-                    ],
405
-                    'event_editor_other_help_tab'                      => [
406
-                        'title'    => esc_html__('Event Other', 'event_espresso'),
407
-                        'filename' => 'event_editor_other',
408
-                    ],
409
-                ],
410
-                'qtips'         => ['EE_Event_Editor_Decaf_Tips'],
411
-                'require_nonce' => false,
412
-            ],
413
-            'default_event_settings' => [
414
-                'nav'           => [
415
-                    'label' => esc_html__('Default Settings', 'event_espresso'),
416
-                    'order' => 40,
417
-                ],
418
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
419
-                'labels'        => [
420
-                    'publishbox' => esc_html__('Update Settings', 'event_espresso'),
421
-                ],
422
-                'help_tabs'     => [
423
-                    'default_settings_help_tab'        => [
424
-                        'title'    => esc_html__('Default Event Settings', 'event_espresso'),
425
-                        'filename' => 'events_default_settings',
426
-                    ],
427
-                    'default_settings_status_help_tab' => [
428
-                        'title'    => esc_html__('Default Registration Status', 'event_espresso'),
429
-                        'filename' => 'events_default_settings_status',
430
-                    ],
431
-                    'default_maximum_tickets_help_tab' => [
432
-                        'title'    => esc_html__('Default Maximum Tickets Per Order', 'event_espresso'),
433
-                        'filename' => 'events_default_settings_max_tickets',
434
-                    ],
435
-                ],
436
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
437
-                // 'help_tour'     => array('Event_Default_Settings_Help_Tour'),
438
-                'require_nonce' => false,
439
-            ],
440
-            // template settings
441
-            'template_settings'      => [
442
-                'nav'           => [
443
-                    'label' => esc_html__('Templates', 'event_espresso'),
444
-                    'order' => 30,
445
-                ],
446
-                'metaboxes'     => $this->_default_espresso_metaboxes,
447
-                'help_tabs'     => [
448
-                    'general_settings_templates_help_tab' => [
449
-                        'title'    => esc_html__('Templates', 'event_espresso'),
450
-                        'filename' => 'general_settings_templates',
451
-                    ],
452
-                ],
453
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
454
-                // 'help_tour'     => array('Templates_Help_Tour'),
455
-                'require_nonce' => false,
456
-            ],
457
-            // event category stuff
458
-            'add_category'           => [
459
-                'nav'           => [
460
-                    'label'      => esc_html__('Add Category', 'event_espresso'),
461
-                    'order'      => 15,
462
-                    'persistent' => false,
463
-                ],
464
-                'help_tabs'     => [
465
-                    'add_category_help_tab' => [
466
-                        'title'    => esc_html__('Add New Event Category', 'event_espresso'),
467
-                        'filename' => 'events_add_category',
468
-                    ],
469
-                ],
470
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
471
-                // 'help_tour'     => array('Event_Add_Category_Help_Tour'),
472
-                'metaboxes'     => ['_publish_post_box'],
473
-                'require_nonce' => false,
474
-            ],
475
-            'edit_category'          => [
476
-                'nav'           => [
477
-                    'label'      => esc_html__('Edit Category', 'event_espresso'),
478
-                    'order'      => 15,
479
-                    'persistent' => false,
480
-                    'url'        => $EVT_CAT_ID
481
-                        ? add_query_arg(
482
-                            ['EVT_CAT_ID' => $EVT_CAT_ID],
483
-                            $this->_current_page_view_url
484
-                        )
485
-                        : $this->_admin_base_url,
486
-                ],
487
-                'help_tabs'     => [
488
-                    'edit_category_help_tab' => [
489
-                        'title'    => esc_html__('Edit Event Category', 'event_espresso'),
490
-                        'filename' => 'events_edit_category',
491
-                    ],
492
-                ],
493
-                /*'help_tour' => array('Event_Edit_Category_Help_Tour'),*/
494
-                'metaboxes'     => ['_publish_post_box'],
495
-                'require_nonce' => false,
496
-            ],
497
-            'category_list'          => [
498
-                'nav'           => [
499
-                    'label' => esc_html__('Categories', 'event_espresso'),
500
-                    'order' => 20,
501
-                ],
502
-                'list_table'    => 'Event_Categories_Admin_List_Table',
503
-                'help_tabs'     => [
504
-                    'events_categories_help_tab'                       => [
505
-                        'title'    => esc_html__('Event Categories', 'event_espresso'),
506
-                        'filename' => 'events_categories',
507
-                    ],
508
-                    'events_categories_table_column_headings_help_tab' => [
509
-                        'title'    => esc_html__('Event Categories Table Column Headings', 'event_espresso'),
510
-                        'filename' => 'events_categories_table_column_headings',
511
-                    ],
512
-                    'events_categories_view_help_tab'                  => [
513
-                        'title'    => esc_html__('Event Categories Views', 'event_espresso'),
514
-                        'filename' => 'events_categories_views',
515
-                    ],
516
-                    'events_categories_other_help_tab'                 => [
517
-                        'title'    => esc_html__('Event Categories Other', 'event_espresso'),
518
-                        'filename' => 'events_categories_other',
519
-                    ],
520
-                ],
521
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
522
-                // 'help_tour'     => array(
523
-                //     'Event_Categories_Help_Tour',
524
-                // ),
525
-                'metaboxes'     => $this->_default_espresso_metaboxes,
526
-                'require_nonce' => false,
527
-            ],
528
-            'preview_deletion'       => [
529
-                'nav'           => [
530
-                    'label'      => esc_html__('Preview Deletion', 'event_espresso'),
531
-                    'order'      => 15,
532
-                    'persistent' => false,
533
-                    'url'        => '',
534
-                ],
535
-                'require_nonce' => false,
536
-            ],
537
-        ];
538
-    }
539
-
540
-
541
-    /**
542
-     * Used to register any global screen options if necessary for every route in this admin page group.
543
-     */
544
-    protected function _add_screen_options()
545
-    {
546
-    }
547
-
548
-
549
-    /**
550
-     * Implementing the screen options for the 'default' route.
551
-     */
552
-    protected function _add_screen_options_default()
553
-    {
554
-        $this->_per_page_screen_option();
555
-    }
556
-
557
-
558
-    /**
559
-     * Implementing screen options for the category list route.
560
-     */
561
-    protected function _add_screen_options_category_list()
562
-    {
563
-        $page_title              = $this->_admin_page_title;
564
-        $this->_admin_page_title = esc_html__('Categories', 'event_espresso');
565
-        $this->_per_page_screen_option();
566
-        $this->_admin_page_title = $page_title;
567
-    }
568
-
569
-
570
-    /**
571
-     * Used to register any global feature pointers for the admin page group.
572
-     */
573
-    protected function _add_feature_pointers()
574
-    {
575
-    }
576
-
577
-
578
-    /**
579
-     * Registers and enqueues any global scripts and styles for the entire admin page group.
580
-     */
581
-    public function load_scripts_styles()
582
-    {
583
-        wp_register_style(
584
-            'events-admin-css',
585
-            EVENTS_ASSETS_URL . 'events-admin-page.css',
586
-            [],
587
-            EVENT_ESPRESSO_VERSION
588
-        );
589
-        wp_register_style('ee-cat-admin', EVENTS_ASSETS_URL . 'ee-cat-admin.css', [], EVENT_ESPRESSO_VERSION);
590
-        wp_enqueue_style('events-admin-css');
591
-        wp_enqueue_style('ee-cat-admin');
592
-        // todo note: we also need to load_scripts_styles per view (i.e. default/view_report/event_details
593
-        // registers for all views
594
-        // scripts
595
-        wp_register_script(
596
-            'event_editor_js',
597
-            EVENTS_ASSETS_URL . 'event_editor.js',
598
-            ['ee_admin_js', 'jquery-ui-slider', 'jquery-ui-timepicker-addon'],
599
-            EVENT_ESPRESSO_VERSION,
600
-            true
601
-        );
602
-    }
603
-
604
-
605
-    /**
606
-     * Enqueuing scripts and styles specific to this view
607
-     */
608
-    public function load_scripts_styles_create_new()
609
-    {
610
-        $this->load_scripts_styles_edit();
611
-    }
612
-
613
-
614
-    /**
615
-     * Enqueuing scripts and styles specific to this view
616
-     */
617
-    public function load_scripts_styles_edit()
618
-    {
619
-        // styles
620
-        wp_enqueue_style('espresso-ui-theme');
621
-        wp_register_style(
622
-            'event-editor-css',
623
-            EVENTS_ASSETS_URL . 'event-editor.css',
624
-            ['ee-admin-css'],
625
-            EVENT_ESPRESSO_VERSION
626
-        );
627
-        wp_enqueue_style('event-editor-css');
628
-        // scripts
629
-        wp_register_script(
630
-            'event-datetime-metabox',
631
-            EVENTS_ASSETS_URL . 'event-datetime-metabox.js',
632
-            ['event_editor_js', 'ee-datepicker'],
633
-            EVENT_ESPRESSO_VERSION
634
-        );
635
-        wp_enqueue_script('event-datetime-metabox');
636
-    }
637
-
638
-
639
-    /**
640
-     * Populating the _views property for the category list table view.
641
-     */
642
-    protected function _set_list_table_views_category_list()
643
-    {
644
-        $this->_views = [
645
-            'all' => [
646
-                'slug'        => 'all',
647
-                'label'       => esc_html__('All', 'event_espresso'),
648
-                'count'       => 0,
649
-                'bulk_action' => [
650
-                    'delete_categories' => esc_html__('Delete Permanently', 'event_espresso'),
651
-                ],
652
-            ],
653
-        ];
654
-    }
655
-
656
-
657
-    /**
658
-     * For adding anything that fires on the admin_init hook for any route within this admin page group.
659
-     */
660
-    public function admin_init()
661
-    {
662
-        EE_Registry::$i18n_js_strings['image_confirm'] = esc_html__(
663
-            'Do you really want to delete this image? Please remember to update your event to complete the removal.',
664
-            'event_espresso'
665
-        );
666
-    }
667
-
668
-
669
-    /**
670
-     * For adding anything that should be triggered on the admin_notices hook for any route within this admin page
671
-     * group.
672
-     */
673
-    public function admin_notices()
674
-    {
675
-    }
676
-
677
-
678
-    /**
679
-     * For adding anything that should be triggered on the `admin_print_footer_scripts` hook for any route within
680
-     * this admin page group.
681
-     */
682
-    public function admin_footer_scripts()
683
-    {
684
-    }
685
-
686
-
687
-    /**
688
-     * Call this function to verify if an event is public and has tickets for sale.  If it does, then we need to show a
689
-     * warning (via EE_Error::add_error());
690
-     *
691
-     * @param EE_Event $event Event object
692
-     * @param string   $req_type
693
-     * @return void
694
-     * @throws EE_Error
695
-     * @throws ReflectionException
696
-     */
697
-    public function verify_event_edit($event = null, $req_type = '')
698
-    {
699
-        // don't need to do this when processing
700
-        if (! empty($req_type)) {
701
-            return;
702
-        }
703
-        // no event?
704
-        if (empty($event)) {
705
-            // set event
706
-            $event = $this->_cpt_model_obj;
707
-        }
708
-        // STILL no event?
709
-        if (! $event instanceof EE_Event) {
710
-            return;
711
-        }
712
-        $orig_status = $event->status();
713
-        // first check if event is active.
714
-        if (
715
-            $orig_status === EEM_Event::cancelled
716
-            || $orig_status === EEM_Event::postponed
717
-            || $event->is_expired()
718
-            || $event->is_inactive()
719
-        ) {
720
-            return;
721
-        }
722
-        // made it here so it IS active... next check that any of the tickets are sold.
723
-        if ($event->is_sold_out(true)) {
724
-            if ($orig_status !== EEM_Event::sold_out && $event->status() !== $orig_status) {
725
-                EE_Error::add_attention(
726
-                    sprintf(
727
-                        esc_html__(
728
-                            'Please note that the Event Status has automatically been changed to %s because there are no more spaces available for this event.  However, this change is not permanent until you update the event.  You can change the status back to something else before updating if you wish.',
729
-                            'event_espresso'
730
-                        ),
731
-                        EEH_Template::pretty_status(EEM_Event::sold_out, false, 'sentence')
732
-                    )
733
-                );
734
-            }
735
-            return;
736
-        } elseif ($orig_status === EEM_Event::sold_out) {
737
-            EE_Error::add_attention(
738
-                sprintf(
739
-                    esc_html__(
740
-                        'Please note that the Event Status has automatically been changed to %s because more spaces have become available for this event, most likely due to abandoned transactions freeing up reserved tickets.  However, this change is not permanent until you update the event. If you wish, you can change the status back to something else before updating.',
741
-                        'event_espresso'
742
-                    ),
743
-                    EEH_Template::pretty_status($event->status(), false, 'sentence')
744
-                )
745
-            );
746
-        }
747
-        // now we need to determine if the event has any tickets on sale.  If not then we dont' show the error
748
-        if (! $event->tickets_on_sale()) {
749
-            return;
750
-        }
751
-        // made it here so show warning
752
-        $this->_edit_event_warning();
753
-    }
754
-
755
-
756
-    /**
757
-     * This is the text used for when an event is being edited that is public and has tickets for sale.
758
-     * When needed, hook this into a EE_Error::add_error() notice.
759
-     *
760
-     * @access protected
761
-     * @return void
762
-     */
763
-    protected function _edit_event_warning()
764
-    {
765
-        // we don't want to add warnings during these requests
766
-        if ($this->request->getRequestParam('action') === 'editpost') {
767
-            return;
768
-        }
769
-        EE_Error::add_attention(
770
-            sprintf(
771
-                esc_html__(
772
-                    'Your event is open for registration. Making changes may disrupt any transactions in progress. %sLearn more%s',
773
-                    'event_espresso'
774
-                ),
775
-                '<a class="espresso-help-tab-lnk">',
776
-                '</a>'
777
-            )
778
-        );
779
-    }
780
-
781
-
782
-    /**
783
-     * When a user is creating a new event, notify them if they haven't set their timezone.
784
-     * Otherwise, do the normal logic
785
-     *
786
-     * @return void
787
-     * @throws EE_Error
788
-     */
789
-    protected function _create_new_cpt_item()
790
-    {
791
-        $has_timezone_string = get_option('timezone_string');
792
-        // only nag them about setting their timezone if it's their first event, and they haven't already done it
793
-        if (! $has_timezone_string && ! EEM_Event::instance()->exists([])) {
794
-            EE_Error::add_attention(
795
-                sprintf(
796
-                    esc_html__(
797
-                        'Your website\'s timezone is currently set to a UTC offset. We recommend updating your timezone to a city or region near you before you create an event. Change your timezone now:%1$s%2$s%3$sChange Timezone%4$s',
798
-                        'event_espresso'
799
-                    ),
800
-                    '<br>',
801
-                    '<select id="timezone_string" name="timezone_string" aria-describedby="timezone-description">'
802
-                    . EEH_DTT_Helper::wp_timezone_choice('', EEH_DTT_Helper::get_user_locale())
803
-                    . '</select>',
804
-                    '<button class="button button-secondary timezone-submit">',
805
-                    '</button><span class="spinner"></span>'
806
-                ),
807
-                __FILE__,
808
-                __FUNCTION__,
809
-                __LINE__
810
-            );
811
-        }
812
-        parent::_create_new_cpt_item();
813
-    }
814
-
815
-
816
-    /**
817
-     * Sets the _views property for the default route in this admin page group.
818
-     */
819
-    protected function _set_list_table_views_default()
820
-    {
821
-        $this->_views = [
822
-            'all'   => [
823
-                'slug'        => 'all',
824
-                'label'       => esc_html__('View All Events', 'event_espresso'),
825
-                'count'       => 0,
826
-                'bulk_action' => [
827
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
828
-                ],
829
-            ],
830
-            'draft' => [
831
-                'slug'        => 'draft',
832
-                'label'       => esc_html__('Draft', 'event_espresso'),
833
-                'count'       => 0,
834
-                'bulk_action' => [
835
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
836
-                ],
837
-            ],
838
-        ];
839
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_events', 'espresso_events_trash_events')) {
840
-            $this->_views['trash'] = [
841
-                'slug'        => 'trash',
842
-                'label'       => esc_html__('Trash', 'event_espresso'),
843
-                'count'       => 0,
844
-                'bulk_action' => [
845
-                    'restore_events' => esc_html__('Restore From Trash', 'event_espresso'),
846
-                    'delete_events'  => esc_html__('Delete Permanently', 'event_espresso'),
847
-                ],
848
-            ];
849
-        }
850
-    }
851
-
852
-
853
-    /**
854
-     * Provides the legend item array for the default list table view.
855
-     *
856
-     * @return array
857
-     * @throws EE_Error
858
-     * @throws EE_Error
859
-     */
860
-    protected function _event_legend_items()
861
-    {
862
-        $items    = [
863
-            'view_details'   => [
864
-                'class' => 'dashicons dashicons-search',
865
-                'desc'  => esc_html__('View Event', 'event_espresso'),
866
-            ],
867
-            'edit_event'     => [
868
-                'class' => 'ee-icon ee-icon-calendar-edit',
869
-                'desc'  => esc_html__('Edit Event Details', 'event_espresso'),
870
-            ],
871
-            'view_attendees' => [
872
-                'class' => 'dashicons dashicons-groups',
873
-                'desc'  => esc_html__('View Registrations for Event', 'event_espresso'),
874
-            ],
875
-        ];
876
-        $items    = apply_filters('FHEE__Events_Admin_Page___event_legend_items__items', $items);
877
-        $statuses = [
878
-            'sold_out_status'  => [
879
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::sold_out,
880
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::sold_out, false, 'sentence'),
881
-            ],
882
-            'active_status'    => [
883
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::active,
884
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::active, false, 'sentence'),
885
-            ],
886
-            'upcoming_status'  => [
887
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::upcoming,
888
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::upcoming, false, 'sentence'),
889
-            ],
890
-            'postponed_status' => [
891
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::postponed,
892
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::postponed, false, 'sentence'),
893
-            ],
894
-            'cancelled_status' => [
895
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::cancelled,
896
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::cancelled, false, 'sentence'),
897
-            ],
898
-            'expired_status'   => [
899
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::expired,
900
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::expired, false, 'sentence'),
901
-            ],
902
-            'inactive_status'  => [
903
-                'class' => 'ee-status-legend ee-status-legend-' . EE_Datetime::inactive,
904
-                'desc'  => EEH_Template::pretty_status(EE_Datetime::inactive, false, 'sentence'),
905
-            ],
906
-        ];
907
-        $statuses = apply_filters('FHEE__Events_Admin_Page__event_legend_items__statuses', $statuses);
908
-        return array_merge($items, $statuses);
909
-    }
910
-
911
-
912
-    /**
913
-     * @return EEM_Event
914
-     * @throws EE_Error
915
-     * @throws ReflectionException
916
-     */
917
-    private function _event_model()
918
-    {
919
-        if (! $this->_event_model instanceof EEM_Event) {
920
-            $this->_event_model = EE_Registry::instance()->load_model('Event');
921
-        }
922
-        return $this->_event_model;
923
-    }
924
-
925
-
926
-    /**
927
-     * Adds extra buttons to the WP CPT permalink field row.
928
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
929
-     *
930
-     * @param string $return    the current html
931
-     * @param int    $id        the post id for the page
932
-     * @param string $new_title What the title is
933
-     * @param string $new_slug  what the slug is
934
-     * @return string            The new html string for the permalink area
935
-     */
936
-    public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
937
-    {
938
-        // make sure this is only when editing
939
-        if (! empty($id)) {
940
-            $post   = get_post($id);
941
-            $return .= '<a class="button button-small" onclick="prompt(\'Shortcode:\', jQuery(\'#shortcode\').val()); return false;" href="#"  tabindex="-1">'
942
-                       . esc_html__('Shortcode', 'event_espresso')
943
-                       . '</a> ';
944
-            $return .= '<input id="shortcode" type="hidden" value="[ESPRESSO_TICKET_SELECTOR event_id='
945
-                       . $post->ID
946
-                       . ']">';
947
-        }
948
-        return $return;
949
-    }
950
-
951
-
952
-    /**
953
-     * _events_overview_list_table
954
-     * This contains the logic for showing the events_overview list
955
-     *
956
-     * @access protected
957
-     * @return void
958
-     * @throws EE_Error
959
-     */
960
-    protected function _events_overview_list_table()
961
-    {
962
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
963
-        $this->_template_args['after_list_table']                           =
964
-            ! empty($this->_template_args['after_list_table'])
965
-                ? (array) $this->_template_args['after_list_table']
966
-                : [];
967
-        $this->_template_args['after_list_table']['view_event_list_button'] = EEH_HTML::br()
968
-            . EEH_Template::get_button_or_link(
969
-                get_post_type_archive_link('espresso_events'),
970
-                esc_html__("View Event Archive Page", "event_espresso"),
971
-                'button'
972
-            );
973
-        $this->_template_args['after_list_table']['legend']                 = $this->_display_legend(
974
-            $this->_event_legend_items()
975
-        );
976
-        $this->_admin_page_title                                            .= ' ' . $this->get_action_link_or_button(
977
-            'create_new',
978
-            'add',
979
-            [],
980
-            'add-new-h2'
981
-        );
982
-        $this->display_admin_list_table_page_with_no_sidebar();
983
-    }
984
-
985
-
986
-    /**
987
-     * this allows for extra misc actions in the default WP publish box
988
-     *
989
-     * @return void
990
-     * @throws EE_Error
991
-     * @throws ReflectionException
992
-     */
993
-    public function extra_misc_actions_publish_box()
994
-    {
995
-        $this->_generate_publish_box_extra_content();
996
-    }
997
-
998
-
999
-    /**
1000
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
1001
-     * saved.
1002
-     * Typically you would use this to save any additional data.
1003
-     * Keep in mind also that "save_post" runs on EVERY post update to the database.
1004
-     * ALSO very important.  When a post transitions from scheduled to published,
1005
-     * the save_post action is fired but you will NOT have any _POST data containing any extra info you may have from
1006
-     * other meta saves. So MAKE sure that you handle this accordingly.
1007
-     *
1008
-     * @access protected
1009
-     * @abstract
1010
-     * @param string $post_id The ID of the cpt that was saved (so you can link relationally)
1011
-     * @param object $post    The post object of the cpt that was saved.
1012
-     * @return void
1013
-     * @throws EE_Error
1014
-     * @throws ReflectionException
1015
-     */
1016
-    protected function _insert_update_cpt_item($post_id, $post)
1017
-    {
1018
-        if ($post instanceof WP_Post && $post->post_type !== 'espresso_events') {
1019
-            // get out we're not processing an event save.
1020
-            return;
1021
-        }
1022
-
1023
-        $event_values = [
1024
-            'EVT_display_desc'                => $this->request->getRequestParam('display_desc', false, 'bool'),
1025
-            'EVT_display_ticket_selector'     => $this->request->getRequestParam(
1026
-                'display_ticket_selector',
1027
-                false,
1028
-                'bool'
1029
-            ),
1030
-            'EVT_additional_limit'            => min(
1031
-                apply_filters('FHEE__EE_Events_Admin__insert_update_cpt_item__EVT_additional_limit_max', 255),
1032
-                $this->request->getRequestParam('additional_limit', null, 'int')
1033
-            ),
1034
-            'EVT_default_registration_status' => $this->request->getRequestParam(
1035
-                'EVT_default_registration_status',
1036
-                EE_Registry::instance()->CFG->registration->default_STS_ID
1037
-            ),
1038
-
1039
-            'EVT_member_only'     => $this->request->getRequestParam('member_only', false, 'bool'),
1040
-            'EVT_allow_overflow'  => $this->request->getRequestParam('EVT_allow_overflow', false, 'bool'),
1041
-            'EVT_timezone_string' => $this->request->getRequestParam('timezone_string'),
1042
-            'EVT_external_URL'    => $this->request->getRequestParam('externalURL'),
1043
-            'EVT_phone'           => $this->request->getRequestParam('event_phone'),
1044
-        ];
1045
-        // update event
1046
-        $success = $this->_event_model()->update_by_ID($event_values, $post_id);
1047
-        // get event_object for other metaboxes...
1048
-        // though it would seem to make sense to just use $this->_event_model()->get_one_by_ID( $post_id )..
1049
-        // i have to setup where conditions to override the filters in the model
1050
-        // that filter out autodraft and inherit statuses so we GET the inherit id!
1051
-        $event = $this->_event_model()->get_one(
1052
-            [
1053
-                [
1054
-                    $this->_event_model()->primary_key_name() => $post_id,
1055
-                    'OR'                                      => [
1056
-                        'status'   => $post->post_status,
1057
-                        // if trying to "Publish" a sold out event, it's status will get switched back to "sold_out" in the db,
1058
-                        // but the returned object here has a status of "publish", so use the original post status as well
1059
-                        'status*1' => $this->request->getRequestParam('original_post_status'),
1060
-                    ],
1061
-                ],
1062
-            ]
1063
-        );
1064
-        // the following are default callbacks for event attachment updates that can be overridden by caffeinated functionality and/or addons.
1065
-        $event_update_callbacks = apply_filters(
1066
-            'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
1067
-            [
1068
-                [$this, '_default_venue_update'],
1069
-                [$this, '_default_tickets_update'],
1070
-            ]
1071
-        );
1072
-        $att_success            = true;
1073
-        foreach ($event_update_callbacks as $e_callback) {
1074
-            $_success = is_callable($e_callback)
1075
-                ? call_user_func($e_callback, $event, $this->request->requestParams())
1076
-                : false;
1077
-            // if ANY of these updates fail then we want the appropriate global error message
1078
-            $att_success = ! $att_success ? $att_success : $_success;
1079
-        }
1080
-        // any errors?
1081
-        if ($success && false === $att_success) {
1082
-            EE_Error::add_error(
1083
-                esc_html__(
1084
-                    'Event Details saved successfully but something went wrong with saving attachments.',
1085
-                    'event_espresso'
1086
-                ),
1087
-                __FILE__,
1088
-                __FUNCTION__,
1089
-                __LINE__
1090
-            );
1091
-        } elseif ($success === false) {
1092
-            EE_Error::add_error(
1093
-                esc_html__('Event Details did not save successfully.', 'event_espresso'),
1094
-                __FILE__,
1095
-                __FUNCTION__,
1096
-                __LINE__
1097
-            );
1098
-        }
1099
-    }
1100
-
1101
-
1102
-    /**
1103
-     * @param int $post_id
1104
-     * @param int $revision_id
1105
-     * @throws EE_Error
1106
-     * @throws EE_Error
1107
-     * @throws ReflectionException
1108
-     * @see parent::restore_item()
1109
-     */
1110
-    protected function _restore_cpt_item($post_id, $revision_id)
1111
-    {
1112
-        // copy existing event meta to new post
1113
-        $post_evt = $this->_event_model()->get_one_by_ID($post_id);
1114
-        if ($post_evt instanceof EE_Event) {
1115
-            // meta revision restore
1116
-            $post_evt->restore_revision($revision_id);
1117
-            // related objs restore
1118
-            $post_evt->restore_revision($revision_id, ['Venue', 'Datetime', 'Price']);
1119
-        }
1120
-    }
1121
-
1122
-
1123
-    /**
1124
-     * Attach the venue to the Event
1125
-     *
1126
-     * @param EE_Event $event Event Object to add the venue to
1127
-     * @param array    $data  The request data from the form
1128
-     * @return bool           Success or fail.
1129
-     * @throws EE_Error
1130
-     * @throws ReflectionException
1131
-     */
1132
-    protected function _default_venue_update(EE_Event $event, $data)
1133
-    {
1134
-        require_once(EE_MODELS . 'EEM_Venue.model.php');
1135
-        $venue_model = EE_Registry::instance()->load_model('Venue');
1136
-        $venue_id    = ! empty($data['venue_id']) ? $data['venue_id'] : null;
1137
-        // very important.  If we don't have a venue name...
1138
-        // then we'll get out because not necessary to create empty venue
1139
-        if (empty($data['venue_title'])) {
1140
-            return false;
1141
-        }
1142
-        $venue_array = [
1143
-            'VNU_wp_user'         => $event->get('EVT_wp_user'),
1144
-            'VNU_name'            => $data['venue_title'],
1145
-            'VNU_desc'            => ! empty($data['venue_description']) ? $data['venue_description'] : null,
1146
-            'VNU_identifier'      => ! empty($data['venue_identifier']) ? $data['venue_identifier'] : null,
1147
-            'VNU_short_desc'      => ! empty($data['venue_short_description'])
1148
-                ? $data['venue_short_description']
1149
-                : null,
1150
-            'VNU_address'         => ! empty($data['address']) ? $data['address'] : null,
1151
-            'VNU_address2'        => ! empty($data['address2']) ? $data['address2'] : null,
1152
-            'VNU_city'            => ! empty($data['city']) ? $data['city'] : null,
1153
-            'STA_ID'              => ! empty($data['state']) ? $data['state'] : null,
1154
-            'CNT_ISO'             => ! empty($data['countries']) ? $data['countries'] : null,
1155
-            'VNU_zip'             => ! empty($data['zip']) ? $data['zip'] : null,
1156
-            'VNU_phone'           => ! empty($data['venue_phone']) ? $data['venue_phone'] : null,
1157
-            'VNU_capacity'        => ! empty($data['venue_capacity']) ? $data['venue_capacity'] : null,
1158
-            'VNU_url'             => ! empty($data['venue_url']) ? $data['venue_url'] : null,
1159
-            'VNU_virtual_phone'   => ! empty($data['virtual_phone']) ? $data['virtual_phone'] : null,
1160
-            'VNU_virtual_url'     => ! empty($data['virtual_url']) ? $data['virtual_url'] : null,
1161
-            'VNU_enable_for_gmap' => isset($data['enable_for_gmap']) ? 1 : 0,
1162
-            'status'              => 'publish',
1163
-        ];
1164
-        // if we've got the venue_id then we're just updating the existing venue so let's do that and then get out.
1165
-        if (! empty($venue_id)) {
1166
-            $update_where  = [$venue_model->primary_key_name() => $venue_id];
1167
-            $rows_affected = $venue_model->update($venue_array, [$update_where]);
1168
-            // we've gotta make sure that the venue is always attached to a revision.. add_relation_to should take care of making sure that the relation is already present.
1169
-            $event->_add_relation_to($venue_id, 'Venue');
1170
-            return $rows_affected > 0;
1171
-        }
1172
-        // we insert the venue
1173
-        $venue_id = $venue_model->insert($venue_array);
1174
-        $event->_add_relation_to($venue_id, 'Venue');
1175
-        return ! empty($venue_id);
1176
-        // when we have the ancestor come in it's already been handled by the revision save.
1177
-    }
1178
-
1179
-
1180
-    /**
1181
-     * Handles saving everything related to Tickets (datetimes, tickets, prices)
1182
-     *
1183
-     * @param EE_Event $event The Event object we're attaching data to
1184
-     * @param array    $data  The request data from the form
1185
-     * @return array
1186
-     * @throws EE_Error
1187
-     * @throws ReflectionException
1188
-     * @throws Exception
1189
-     */
1190
-    protected function _default_tickets_update(EE_Event $event, $data)
1191
-    {
1192
-        $datetime       = null;
1193
-        $saved_tickets  = [];
1194
-        $event_timezone = $event->get_timezone();
1195
-        $date_formats   = ['Y-m-d', 'h:i a'];
1196
-        foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
1197
-            // trim all values to ensure any excess whitespace is removed.
1198
-            $datetime_data                = array_map('trim', $datetime_data);
1199
-            $datetime_data['DTT_EVT_end'] =
1200
-                isset($datetime_data['DTT_EVT_end']) && ! empty($datetime_data['DTT_EVT_end'])
1201
-                    ? $datetime_data['DTT_EVT_end']
1202
-                    : $datetime_data['DTT_EVT_start'];
1203
-            $datetime_values              = [
1204
-                'DTT_ID'        => ! empty($datetime_data['DTT_ID']) ? $datetime_data['DTT_ID'] : null,
1205
-                'DTT_EVT_start' => $datetime_data['DTT_EVT_start'],
1206
-                'DTT_EVT_end'   => $datetime_data['DTT_EVT_end'],
1207
-                'DTT_reg_limit' => empty($datetime_data['DTT_reg_limit']) ? EE_INF : $datetime_data['DTT_reg_limit'],
1208
-                'DTT_order'     => $row,
1209
-            ];
1210
-            // if we have an id then let's get existing object first and then set the new values.
1211
-            //  Otherwise we instantiate a new object for save.
1212
-            if (! empty($datetime_data['DTT_ID'])) {
1213
-                $datetime = EEM_Datetime::instance($event_timezone)->get_one_by_ID($datetime_data['DTT_ID']);
1214
-                if (! $datetime instanceof EE_Ticket) {
1215
-                    throw new RuntimeException(
1216
-                        sprintf(
1217
-                            esc_html__(
1218
-                                'Something went wrong! A valid Datetime could not be retrieved from the database using the supplied ID: %1$d',
1219
-                                'event_espresso'
1220
-                            ),
1221
-                            $datetime_data['DTT_ID']
1222
-                        )
1223
-                    );
1224
-                }
1225
-                $datetime->set_date_format($date_formats[0]);
1226
-                $datetime->set_time_format($date_formats[1]);
1227
-                foreach ($datetime_values as $field => $value) {
1228
-                    $datetime->set($field, $value);
1229
-                }
1230
-            } else {
1231
-                $datetime = EE_Datetime::new_instance($datetime_values, $event_timezone, $date_formats);
1232
-            }
1233
-            if (! $datetime instanceof EE_Datetime) {
1234
-                throw new RuntimeException(
1235
-                    sprintf(
1236
-                        esc_html__(
1237
-                            'Something went wrong! A valid Datetime could not be generated or retrieved using the supplied data: %1$s',
1238
-                            'event_espresso'
1239
-                        ),
1240
-                        print_r($datetime_values, true)
1241
-                    )
1242
-                );
1243
-            }
1244
-            // before going any further make sure our dates are setup correctly
1245
-            // so that the end date is always equal or greater than the start date.
1246
-            if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
1247
-                $datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
1248
-                $datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
1249
-            }
1250
-            $datetime->save();
1251
-            $event->_add_relation_to($datetime, 'Datetime');
1252
-        }
1253
-        // no datetimes get deleted so we don't do any of that logic here.
1254
-        // update tickets next
1255
-        $old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : [];
1256
-
1257
-        // set up some default start and end dates in case those are not present in the incoming data
1258
-        $default_start_date = new DateTime('now', new DateTimeZone($event->get_timezone()));
1259
-        $default_start_date = $default_start_date->format($date_formats[0] . ' ' . $date_formats[1]);
1260
-        // use the start date of the first datetime for the end date
1261
-        $first_datetime   = $event->first_datetime();
1262
-        $default_end_date = $first_datetime->start_date_and_time($date_formats[0], $date_formats[1]);
1263
-
1264
-        // now process the incoming data
1265
-        foreach ($data['edit_tickets'] as $row => $ticket_data) {
1266
-            $update_prices = false;
1267
-            $ticket_price  = isset($data['edit_prices'][ $row ][1]['PRC_amount'])
1268
-                ? $data['edit_prices'][ $row ][1]['PRC_amount']
1269
-                : 0;
1270
-            // trim inputs to ensure any excess whitespace is removed.
1271
-            $ticket_data   = array_map('trim', $ticket_data);
1272
-            $ticket_values = [
1273
-                'TKT_ID'          => ! empty($ticket_data['TKT_ID']) ? $ticket_data['TKT_ID'] : null,
1274
-                'TTM_ID'          => ! empty($ticket_data['TTM_ID']) ? $ticket_data['TTM_ID'] : 0,
1275
-                'TKT_name'        => ! empty($ticket_data['TKT_name']) ? $ticket_data['TKT_name'] : '',
1276
-                'TKT_description' => ! empty($ticket_data['TKT_description']) ? $ticket_data['TKT_description'] : '',
1277
-                'TKT_start_date'  => ! empty($ticket_data['TKT_start_date'])
1278
-                    ? $ticket_data['TKT_start_date']
1279
-                    : $default_start_date,
1280
-                'TKT_end_date'    => ! empty($ticket_data['TKT_end_date'])
1281
-                    ? $ticket_data['TKT_end_date']
1282
-                    : $default_end_date,
1283
-                'TKT_qty'         => ! empty($ticket_data['TKT_qty'])
1284
-                                     || (isset($ticket_data['TKT_qty']) && (int) $ticket_data['TKT_qty'] === 0)
1285
-                    ? $ticket_data['TKT_qty']
1286
-                    : EE_INF,
1287
-                'TKT_uses'        => ! empty($ticket_data['TKT_uses'])
1288
-                                     || (isset($ticket_data['TKT_uses']) && (int) $ticket_data['TKT_uses'] === 0)
1289
-                    ? $ticket_data['TKT_uses']
1290
-                    : EE_INF,
1291
-                'TKT_min'         => ! empty($ticket_data['TKT_min']) ? $ticket_data['TKT_min'] : 0,
1292
-                'TKT_max'         => ! empty($ticket_data['TKT_max']) ? $ticket_data['TKT_max'] : EE_INF,
1293
-                'TKT_order'       => isset($ticket_data['TKT_order']) ? $ticket_data['TKT_order'] : $row,
1294
-                'TKT_price'       => $ticket_price,
1295
-                'TKT_row'         => $row,
1296
-            ];
1297
-            // if this is a default ticket, then we need to set the TKT_ID to 0 and update accordingly,
1298
-            // which means in turn that the prices will become new prices as well.
1299
-            if (isset($ticket_data['TKT_is_default']) && $ticket_data['TKT_is_default']) {
1300
-                $ticket_values['TKT_ID']         = 0;
1301
-                $ticket_values['TKT_is_default'] = 0;
1302
-                $update_prices                   = true;
1303
-            }
1304
-            // if we have a TKT_ID then we need to get that existing TKT_obj and update it
1305
-            // we actually do our saves ahead of adding any relations because its entirely possible that this
1306
-            // ticket didn't get removed or added to any datetime in the session but DID have it's items modified.
1307
-            // keep in mind that if the ticket has been sold (and we have changed pricing information),
1308
-            // then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
1309
-            if (! empty($ticket_data['TKT_ID'])) {
1310
-                $existing_ticket = EEM_Ticket::instance($event_timezone)->get_one_by_ID($ticket_data['TKT_ID']);
1311
-                if (! $existing_ticket instanceof EE_Ticket) {
1312
-                    throw new RuntimeException(
1313
-                        sprintf(
1314
-                            esc_html__(
1315
-                                'Something went wrong! A valid Ticket could not be retrieved from the database using the supplied ID: %1$d',
1316
-                                'event_espresso'
1317
-                            ),
1318
-                            $ticket_data['TKT_ID']
1319
-                        )
1320
-                    );
1321
-                }
1322
-                $ticket_sold = $existing_ticket->count_related(
1323
-                    'Registration',
1324
-                    [
1325
-                        [
1326
-                            'STS_ID' => [
1327
-                                'NOT IN',
1328
-                                [EEM_Registration::status_id_incomplete],
1329
-                            ],
1330
-                        ],
1331
-                    ]
1332
-                ) > 0;
1333
-                // let's just check the total price for the existing ticket and determine if it matches the new total price.
1334
-                // if they are different then we create a new ticket (if $ticket_sold)
1335
-                // if they aren't different then we go ahead and modify existing ticket.
1336
-                $create_new_ticket = $ticket_sold
1337
-                                     && $ticket_price !== $existing_ticket->price()
1338
-                                     && ! $existing_ticket->deleted();
1339
-                $existing_ticket->set_date_format($date_formats[0]);
1340
-                $existing_ticket->set_time_format($date_formats[1]);
1341
-                // set new values
1342
-                foreach ($ticket_values as $field => $value) {
1343
-                    if ($field == 'TKT_qty') {
1344
-                        $existing_ticket->set_qty($value);
1345
-                    } elseif ($field == 'TKT_price') {
1346
-                        $existing_ticket->set('TKT_price', $ticket_price);
1347
-                    } else {
1348
-                        $existing_ticket->set($field, $value);
1349
-                    }
1350
-                }
1351
-                $ticket = $existing_ticket;
1352
-                // if $create_new_ticket is false then we can safely update the existing ticket.
1353
-                //  Otherwise we have to create a new ticket.
1354
-                if ($create_new_ticket) {
1355
-                    // archive the old ticket first
1356
-                    $existing_ticket->set('TKT_deleted', 1);
1357
-                    $existing_ticket->save();
1358
-                    // make sure this ticket is still recorded in our $saved_tickets
1359
-                    // so we don't run it through the regular trash routine.
1360
-                    $saved_tickets[ $existing_ticket->ID() ] = $existing_ticket;
1361
-                    // create new ticket that's a copy of the existing except,
1362
-                    // (a new id of course and not archived) AND has the new TKT_price associated with it.
1363
-                    $new_ticket = clone $existing_ticket;
1364
-                    $new_ticket->set('TKT_ID', 0);
1365
-                    $new_ticket->set('TKT_deleted', 0);
1366
-                    $new_ticket->set('TKT_sold', 0);
1367
-                    // now we need to make sure that $new prices are created as well and attached to new ticket.
1368
-                    $update_prices = true;
1369
-                    $ticket        = $new_ticket;
1370
-                }
1371
-            } else {
1372
-                // no TKT_id so a new ticket
1373
-                $ticket_values['TKT_price'] = $ticket_price;
1374
-                $ticket                     = EE_Ticket::new_instance($ticket_values, $event_timezone, $date_formats);
1375
-                $update_prices              = true;
1376
-            }
1377
-            if (! $ticket instanceof EE_Ticket) {
1378
-                throw new RuntimeException(
1379
-                    sprintf(
1380
-                        esc_html__(
1381
-                            'Something went wrong! A valid Ticket could not be generated or retrieved using the supplied data: %1$s',
1382
-                            'event_espresso'
1383
-                        ),
1384
-                        print_r($ticket_values, true)
1385
-                    )
1386
-                );
1387
-            }
1388
-            // cap ticket qty by datetime reg limits
1389
-            $ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
1390
-            // update ticket.
1391
-            $ticket->save();
1392
-            // before going any further make sure our dates are setup correctly
1393
-            // so that the end date is always equal or greater than the start date.
1394
-            if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
1395
-                $ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
1396
-                $ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
1397
-                $ticket->save();
1398
-            }
1399
-            // initially let's add the ticket to the datetime
1400
-            $datetime->_add_relation_to($ticket, 'Ticket');
1401
-            $saved_tickets[ $ticket->ID() ] = $ticket;
1402
-            // add prices to ticket
1403
-            $this->_add_prices_to_ticket($data['edit_prices'][ $row ], $ticket, $update_prices);
1404
-        }
1405
-        // however now we need to handle permanently deleting tickets via the ui.
1406
-        //  Keep in mind that the ui does not allow deleting/archiving tickets that have ticket sold.
1407
-        //  However, it does allow for deleting tickets that have no tickets sold,
1408
-        // in which case we want to get rid of permanently because there is no need to save in db.
1409
-        $old_tickets     = isset($old_tickets[0]) && $old_tickets[0] == '' ? [] : $old_tickets;
1410
-        $tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
1411
-        foreach ($tickets_removed as $id) {
1412
-            $id = absint($id);
1413
-            // get the ticket for this id
1414
-            $ticket_to_remove = EEM_Ticket::instance()->get_one_by_ID($id);
1415
-            if (! $ticket_to_remove instanceof EE_Ticket) {
1416
-                continue;
1417
-            }
1418
-            // need to get all the related datetimes on this ticket and remove from every single one of them
1419
-            // (remember this process can ONLY kick off if there are NO tickets sold)
1420
-            $related_datetimes = $ticket_to_remove->get_many_related('Datetime');
1421
-            foreach ($related_datetimes as $related_datetime) {
1422
-                $ticket_to_remove->_remove_relation_to($related_datetime, 'Datetime');
1423
-            }
1424
-            // need to do the same for prices (except these prices can also be deleted because again,
1425
-            // tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
1426
-            $ticket_to_remove->delete_related_permanently('Price');
1427
-            // finally let's delete this ticket
1428
-            // (which should not be blocked at this point b/c we've removed all our relationships)
1429
-            $ticket_to_remove->delete_permanently();
1430
-        }
1431
-        return [$datetime, $saved_tickets];
1432
-    }
1433
-
1434
-
1435
-    /**
1436
-     * This attaches a list of given prices to a ticket.
1437
-     * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
1438
-     * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
1439
-     * price info and prices are automatically "archived" via the ticket.
1440
-     *
1441
-     * @access  private
1442
-     * @param array     $prices_data Array of prices from the form.
1443
-     * @param EE_Ticket $ticket      EE_Ticket object that prices are being attached to.
1444
-     * @param bool      $new_prices  Whether attach existing incoming prices or create new ones.
1445
-     * @return  void
1446
-     * @throws EE_Error
1447
-     * @throws ReflectionException
1448
-     */
1449
-    private function _add_prices_to_ticket($prices_data, EE_Ticket $ticket, $new_prices = false)
1450
-    {
1451
-        $timezone = $ticket->get_timezone();
1452
-        foreach ($prices_data as $row => $price_data) {
1453
-            $price_values = [
1454
-                'PRC_ID'         => ! empty($price_data['PRC_ID']) ? $price_data['PRC_ID'] : null,
1455
-                'PRT_ID'         => ! empty($price_data['PRT_ID']) ? $price_data['PRT_ID'] : null,
1456
-                'PRC_amount'     => ! empty($price_data['PRC_amount']) ? $price_data['PRC_amount'] : 0,
1457
-                'PRC_name'       => ! empty($price_data['PRC_name']) ? $price_data['PRC_name'] : '',
1458
-                'PRC_desc'       => ! empty($price_data['PRC_desc']) ? $price_data['PRC_desc'] : '',
1459
-                'PRC_is_default' => 0, // make sure prices are NOT set as default from this context
1460
-                'PRC_order'      => $row,
1461
-            ];
1462
-            if ($new_prices || empty($price_values['PRC_ID'])) {
1463
-                $price_values['PRC_ID'] = 0;
1464
-                $price                  = EE_Price::new_instance($price_values, $timezone);
1465
-            } else {
1466
-                $price = EEM_Price::instance($timezone)->get_one_by_ID($price_data['PRC_ID']);
1467
-                // update this price with new values
1468
-                foreach ($price_values as $field => $new_price) {
1469
-                    $price->set($field, $new_price);
1470
-                }
1471
-            }
1472
-            if (! $price instanceof EE_Price) {
1473
-                throw new RuntimeException(
1474
-                    sprintf(
1475
-                        esc_html__(
1476
-                            'Something went wrong! A valid Price could not be generated or retrieved using the supplied data: %1$s',
1477
-                            'event_espresso'
1478
-                        ),
1479
-                        print_r($price_values, true)
1480
-                    )
1481
-                );
1482
-            }
1483
-            $price->save();
1484
-            $ticket->_add_relation_to($price, 'Price');
1485
-        }
1486
-    }
1487
-
1488
-
1489
-    /**
1490
-     * Add in our autosave ajax handlers
1491
-     *
1492
-     */
1493
-    protected function _ee_autosave_create_new()
1494
-    {
1495
-    }
1496
-
1497
-
1498
-    /**
1499
-     * More autosave handlers.
1500
-     */
1501
-    protected function _ee_autosave_edit()
1502
-    {
1503
-        // TEMPORARILY EXITING CAUSE THIS IS A TODO
1504
-    }
1505
-
1506
-
1507
-    /**
1508
-     * @throws EE_Error
1509
-     * @throws ReflectionException
1510
-     */
1511
-    private function _generate_publish_box_extra_content()
1512
-    {
1513
-        // load formatter helper
1514
-        // args for getting related registrations
1515
-        $approved_query_args        = [
1516
-            [
1517
-                'REG_deleted' => 0,
1518
-                'STS_ID'      => EEM_Registration::status_id_approved,
1519
-            ],
1520
-        ];
1521
-        $not_approved_query_args    = [
1522
-            [
1523
-                'REG_deleted' => 0,
1524
-                'STS_ID'      => EEM_Registration::status_id_not_approved,
1525
-            ],
1526
-        ];
1527
-        $pending_payment_query_args = [
1528
-            [
1529
-                'REG_deleted' => 0,
1530
-                'STS_ID'      => EEM_Registration::status_id_pending_payment,
1531
-            ],
1532
-        ];
1533
-        // publish box
1534
-        $publish_box_extra_args = [
1535
-            'view_approved_reg_url'        => add_query_arg(
1536
-                [
1537
-                    'action'      => 'default',
1538
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1539
-                    '_reg_status' => EEM_Registration::status_id_approved,
1540
-                ],
1541
-                REG_ADMIN_URL
1542
-            ),
1543
-            'view_not_approved_reg_url'    => add_query_arg(
1544
-                [
1545
-                    'action'      => 'default',
1546
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1547
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1548
-                ],
1549
-                REG_ADMIN_URL
1550
-            ),
1551
-            'view_pending_payment_reg_url' => add_query_arg(
1552
-                [
1553
-                    'action'      => 'default',
1554
-                    'event_id'    => $this->_cpt_model_obj->ID(),
1555
-                    '_reg_status' => EEM_Registration::status_id_pending_payment,
1556
-                ],
1557
-                REG_ADMIN_URL
1558
-            ),
1559
-            'approved_regs'                => $this->_cpt_model_obj->count_related(
1560
-                'Registration',
1561
-                $approved_query_args
1562
-            ),
1563
-            'not_approved_regs'            => $this->_cpt_model_obj->count_related(
1564
-                'Registration',
1565
-                $not_approved_query_args
1566
-            ),
1567
-            'pending_payment_regs'         => $this->_cpt_model_obj->count_related(
1568
-                'Registration',
1569
-                $pending_payment_query_args
1570
-            ),
1571
-            'misc_pub_section_class'       => apply_filters(
1572
-                'FHEE_Events_Admin_Page___generate_publish_box_extra_content__misc_pub_section_class',
1573
-                'misc-pub-section'
1574
-            ),
1575
-        ];
1576
-        ob_start();
1577
-        do_action(
1578
-            'AHEE__Events_Admin_Page___generate_publish_box_extra_content__event_editor_overview_add',
1579
-            $this->_cpt_model_obj
1580
-        );
1581
-        $publish_box_extra_args['event_editor_overview_add'] = ob_get_clean();
1582
-        // load template
1583
-        EEH_Template::display_template(
1584
-            EVENTS_TEMPLATE_PATH . 'event_publish_box_extras.template.php',
1585
-            $publish_box_extra_args
1586
-        );
1587
-    }
1588
-
1589
-
1590
-    /**
1591
-     * @return EE_Event
1592
-     */
1593
-    public function get_event_object()
1594
-    {
1595
-        return $this->_cpt_model_obj;
1596
-    }
1597
-
1598
-
1599
-
1600
-
1601
-    /** METABOXES * */
1602
-    /**
1603
-     * _register_event_editor_meta_boxes
1604
-     * add all metaboxes related to the event_editor
1605
-     *
1606
-     * @return void
1607
-     * @throws EE_Error
1608
-     * @throws ReflectionException
1609
-     */
1610
-    protected function _register_event_editor_meta_boxes()
1611
-    {
1612
-        $this->verify_cpt_object();
1613
-        add_meta_box(
1614
-            'espresso_event_editor_tickets',
1615
-            esc_html__('Event Datetime & Ticket', 'event_espresso'),
1616
-            [$this, 'ticket_metabox'],
1617
-            $this->page_slug,
1618
-            'normal',
1619
-            'high'
1620
-        );
1621
-        add_meta_box(
1622
-            'espresso_event_editor_event_options',
1623
-            esc_html__('Event Registration Options', 'event_espresso'),
1624
-            [$this, 'registration_options_meta_box'],
1625
-            $this->page_slug,
1626
-            'side'
1627
-        );
1628
-        // NOTE: if you're looking for other metaboxes in here,
1629
-        // where a metabox has a related management page in the admin
1630
-        // you will find it setup in the related management page's "_Hooks" file.
1631
-        // i.e. messages metabox is found in "espresso_events_Messages_Hooks.class.php".
1632
-    }
1633
-
1634
-
1635
-    /**
1636
-     * @throws DomainException
1637
-     * @throws EE_Error
1638
-     * @throws ReflectionException
1639
-     */
1640
-    public function ticket_metabox()
1641
-    {
1642
-        $existing_datetime_ids = $existing_ticket_ids = [];
1643
-        // defaults for template args
1644
-        $template_args = [
1645
-            'existing_datetime_ids'    => '',
1646
-            'event_datetime_help_link' => '',
1647
-            'ticket_options_help_link' => '',
1648
-            'time'                     => null,
1649
-            'ticket_rows'              => '',
1650
-            'existing_ticket_ids'      => '',
1651
-            'total_ticket_rows'        => 1,
1652
-            'ticket_js_structure'      => '',
1653
-            'trash_icon'               => 'ee-lock-icon',
1654
-            'disabled'                 => '',
1655
-        ];
1656
-        $event_id      = is_object($this->_cpt_model_obj) ? $this->_cpt_model_obj->ID() : null;
1657
-        /**
1658
-         * 1. Start with retrieving Datetimes
1659
-         * 2. Fore each datetime get related tickets
1660
-         * 3. For each ticket get related prices
1661
-         */
1662
-        $times          = EEM_Datetime::instance()->get_all_event_dates($event_id);
1663
-        $first_datetime = reset($times);
1664
-        // do we get related tickets?
1665
-        if (
1666
-            $first_datetime instanceof EE_Datetime
1667
-            && $first_datetime->ID() !== 0
1668
-        ) {
1669
-            $existing_datetime_ids[] = $first_datetime->get('DTT_ID');
1670
-            $template_args['time']   = $first_datetime;
1671
-            $related_tickets         = $first_datetime->tickets(
1672
-                [
1673
-                    ['OR' => ['TKT_deleted' => 1, 'TKT_deleted*' => 0]],
1674
-                    'default_where_conditions' => 'none',
1675
-                ]
1676
-            );
1677
-            if (! empty($related_tickets)) {
1678
-                $template_args['total_ticket_rows'] = count($related_tickets);
1679
-                $row                                = 0;
1680
-                foreach ($related_tickets as $ticket) {
1681
-                    $existing_ticket_ids[]        = $ticket->get('TKT_ID');
1682
-                    $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket, false, $row);
1683
-                    $row++;
1684
-                }
1685
-            } else {
1686
-                $template_args['total_ticket_rows'] = 1;
1687
-                /** @type EE_Ticket $ticket */
1688
-                $ticket                       = EEM_Ticket::instance()->create_default_object();
1689
-                $template_args['ticket_rows'] .= $this->_get_ticket_row($ticket);
1690
-            }
1691
-        } else {
1692
-            $template_args['time']        = $times[0];
1693
-            $tickets                      = EEM_Ticket::instance()->get_all_default_tickets();
1694
-            $template_args['ticket_rows'] .= $this->_get_ticket_row($tickets[1]);
1695
-            // NOTE: we're just sending the first default row
1696
-            // (decaf can't manage default tickets so this should be sufficient);
1697
-        }
1698
-        $template_args['event_datetime_help_link'] = $this->_get_help_tab_link(
1699
-            'event_editor_event_datetimes_help_tab'
1700
-        );
1701
-        $template_args['ticket_options_help_link'] = $this->_get_help_tab_link('ticket_options_info');
1702
-        $template_args['existing_datetime_ids']    = implode(',', $existing_datetime_ids);
1703
-        $template_args['existing_ticket_ids']      = implode(',', $existing_ticket_ids);
1704
-        $template_args['ticket_js_structure']      = $this->_get_ticket_row(
1705
-            EEM_Ticket::instance()->create_default_object(),
1706
-            true
1707
-        );
1708
-        $template                                  = apply_filters(
1709
-            'FHEE__Events_Admin_Page__ticket_metabox__template',
1710
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php'
1711
-        );
1712
-        EEH_Template::display_template($template, $template_args);
1713
-    }
1714
-
1715
-
1716
-    /**
1717
-     * Setup an individual ticket form for the decaf event editor page
1718
-     *
1719
-     * @access private
1720
-     * @param EE_Ticket $ticket   the ticket object
1721
-     * @param boolean   $skeleton whether we're generating a skeleton for js manipulation
1722
-     * @param int       $row
1723
-     * @return string generated html for the ticket row.
1724
-     * @throws EE_Error
1725
-     * @throws ReflectionException
1726
-     */
1727
-    private function _get_ticket_row($ticket, $skeleton = false, $row = 0)
1728
-    {
1729
-        $template_args = [
1730
-            'tkt_status_class'    => ' tkt-status-' . $ticket->ticket_status(),
1731
-            'tkt_archive_class'   => $ticket->ticket_status() === EE_Ticket::archived && ! $skeleton ? ' tkt-archived'
1732
-                : '',
1733
-            'ticketrow'           => $skeleton ? 'TICKETNUM' : $row,
1734
-            'TKT_ID'              => $ticket->get('TKT_ID'),
1735
-            'TKT_name'            => $ticket->get('TKT_name'),
1736
-            'TKT_start_date'      => $skeleton ? '' : $ticket->get_date('TKT_start_date', 'Y-m-d h:i a'),
1737
-            'TKT_end_date'        => $skeleton ? '' : $ticket->get_date('TKT_end_date', 'Y-m-d h:i a'),
1738
-            'TKT_is_default'      => $ticket->get('TKT_is_default'),
1739
-            'TKT_qty'             => $ticket->get_pretty('TKT_qty', 'input'),
1740
-            'edit_ticketrow_name' => $skeleton ? 'TICKETNAMEATTR' : 'edit_tickets',
1741
-            'TKT_sold'            => $skeleton ? 0 : $ticket->get('TKT_sold'),
1742
-            'trash_icon'          => ($skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')))
1743
-                                     && (! empty($ticket) && $ticket->get('TKT_sold') === 0)
1744
-                ? 'trash-icon dashicons dashicons-post-trash clickable' : 'ee-lock-icon',
1745
-            'disabled'            => $skeleton || (! empty($ticket) && ! $ticket->get('TKT_deleted')) ? ''
1746
-                : ' disabled=disabled',
1747
-        ];
1748
-        $price         = $ticket->ID() !== 0
1749
-            ? $ticket->get_first_related('Price', ['default_where_conditions' => 'none'])
1750
-            : null;
1751
-        $price         = $price instanceof EE_Price
1752
-            ? $price
1753
-            : EEM_Price::instance()->create_default_object();
1754
-        $price_args    = [
1755
-            'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1756
-            'PRC_amount'            => $price->get('PRC_amount'),
1757
-            'PRT_ID'                => $price->get('PRT_ID'),
1758
-            'PRC_ID'                => $price->get('PRC_ID'),
1759
-            'PRC_is_default'        => $price->get('PRC_is_default'),
1760
-        ];
1761
-        // make sure we have default start and end dates if skeleton
1762
-        // handle rows that should NOT be empty
1763
-        if (empty($template_args['TKT_start_date'])) {
1764
-            // if empty then the start date will be now.
1765
-            $template_args['TKT_start_date'] = date('Y-m-d h:i a', current_time('timestamp'));
1766
-        }
1767
-        if (empty($template_args['TKT_end_date'])) {
1768
-            // get the earliest datetime (if present);
1769
-            $earliest_datetime             = $this->_cpt_model_obj->ID() > 0
1770
-                ? $this->_cpt_model_obj->get_first_related(
1771
-                    'Datetime',
1772
-                    ['order_by' => ['DTT_EVT_start' => 'ASC']]
1773
-                )
1774
-                : null;
1775
-            $template_args['TKT_end_date'] = $earliest_datetime instanceof EE_Datetime
1776
-                ? $earliest_datetime->get_datetime('DTT_EVT_start', 'Y-m-d', 'h:i a')
1777
-                : date('Y-m-d h:i a', mktime(0, 0, 0, date('m'), date('d') + 7, date('Y')));
1778
-        }
1779
-        $template_args = array_merge($template_args, $price_args);
1780
-        $template      = apply_filters(
1781
-            'FHEE__Events_Admin_Page__get_ticket_row__template',
1782
-            EVENTS_TEMPLATE_PATH . 'event_tickets_metabox_ticket_row.template.php',
1783
-            $ticket
1784
-        );
1785
-        return EEH_Template::display_template($template, $template_args, true);
1786
-    }
1787
-
1788
-
1789
-    /**
1790
-     * @throws EE_Error
1791
-     * @throws ReflectionException
1792
-     */
1793
-    public function registration_options_meta_box()
1794
-    {
1795
-        $yes_no_values             = [
1796
-            ['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
1797
-            ['id' => false, 'text' => esc_html__('No', 'event_espresso')],
1798
-        ];
1799
-        $default_reg_status_values = EEM_Registration::reg_status_array(
1800
-            [
1801
-                EEM_Registration::status_id_cancelled,
1802
-                EEM_Registration::status_id_declined,
1803
-                EEM_Registration::status_id_incomplete,
1804
-            ],
1805
-            true
1806
-        );
1807
-        // $template_args['is_active_select'] = EEH_Form_Fields::select_input('is_active', $yes_no_values, $this->_cpt_model_obj->is_active());
1808
-        $template_args['_event']                          = $this->_cpt_model_obj;
1809
-        $template_args['event']                           = $this->_cpt_model_obj;
1810
-        $template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
1811
-        $template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
1812
-        $template_args['default_registration_status']     = EEH_Form_Fields::select_input(
1813
-            'default_reg_status',
1814
-            $default_reg_status_values,
1815
-            $this->_cpt_model_obj->default_registration_status()
1816
-        );
1817
-        $template_args['display_description']             = EEH_Form_Fields::select_input(
1818
-            'display_desc',
1819
-            $yes_no_values,
1820
-            $this->_cpt_model_obj->display_description()
1821
-        );
1822
-        $template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
1823
-            'display_ticket_selector',
1824
-            $yes_no_values,
1825
-            $this->_cpt_model_obj->display_ticket_selector(),
1826
-            '',
1827
-            '',
1828
-            false
1829
-        );
1830
-        $template_args['additional_registration_options'] = apply_filters(
1831
-            'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1832
-            '',
1833
-            $template_args,
1834
-            $yes_no_values,
1835
-            $default_reg_status_values
1836
-        );
1837
-        EEH_Template::display_template(
1838
-            EVENTS_TEMPLATE_PATH . 'event_registration_options.template.php',
1839
-            $template_args
1840
-        );
1841
-    }
1842
-
1843
-
1844
-    /**
1845
-     * _get_events()
1846
-     * This method simply returns all the events (for the given _view and paging)
1847
-     *
1848
-     * @access public
1849
-     * @param int  $per_page     count of items per page (20 default);
1850
-     * @param int  $current_page what is the current page being viewed.
1851
-     * @param bool $count        if TRUE then we just return a count of ALL events matching the given _view.
1852
-     *                           If FALSE then we return an array of event objects
1853
-     *                           that match the given _view and paging parameters.
1854
-     * @return array|int         an array of event objects or a count of them.
1855
-     * @throws Exception
1856
-     */
1857
-    public function get_events($per_page = 10, $current_page = 1, $count = false)
1858
-    {
1859
-        $EEM_Event   = $this->_event_model();
1860
-        $offset      = ($current_page - 1) * $per_page;
1861
-        $limit       = $count ? null : $offset . ',' . $per_page;
1862
-        $orderby     = $this->request->getRequestParam('orderby', 'EVT_ID');
1863
-        $order       = $this->request->getRequestParam('order', 'DESC');
1864
-        $month_range = $this->request->getRequestParam('month_range');
1865
-        if ($month_range) {
1866
-            $pieces = explode(' ', $month_range, 3);
1867
-            // simulate the FIRST day of the month, that fixes issues for months like February
1868
-            // where PHP doesn't know what to assume for date.
1869
-            // @see https://events.codebasehq.com/projects/event-espresso/tickets/10437
1870
-            $month_r = ! empty($pieces[0]) ? date('m', EEH_DTT_Helper::first_of_month_timestamp($pieces[0])) : '';
1871
-            $year_r  = ! empty($pieces[1]) ? $pieces[1] : '';
1872
-        }
1873
-        $where  = [];
1874
-        $status = $this->request->getRequestParam('status');
1875
-        // determine what post_status our condition will have for the query.
1876
-        switch ($status) {
1877
-            case 'month':
1878
-            case 'today':
1879
-            case null:
1880
-            case 'all':
1881
-                break;
1882
-            case 'draft':
1883
-                $where['status'] = ['IN', ['draft', 'auto-draft']];
1884
-                break;
1885
-            default:
1886
-                $where['status'] = $status;
1887
-        }
1888
-        // categories?
1889
-        $category = $this->request->getRequestParam('EVT_CAT', 0, 'int');
1890
-        if ($category) {
1891
-            $where['Term_Taxonomy.taxonomy'] = EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY;
1892
-            $where['Term_Taxonomy.term_id']  = $category;
1893
-        }
1894
-        // date where conditions
1895
-        $start_formats = EEM_Datetime::instance()->get_formats_for('DTT_EVT_start');
1896
-        if ($month_range) {
1897
-            $DateTime = new DateTime(
1898
-                $year_r . '-' . $month_r . '-01 00:00:00',
1899
-                new DateTimeZone('UTC')
1900
-            );
1901
-            $start    = $DateTime->getTimestamp();
1902
-            // set the datetime to be the end of the month
1903
-            $DateTime->setDate(
1904
-                $year_r,
1905
-                $month_r,
1906
-                $DateTime->format('t')
1907
-            )->setTime(23, 59, 59);
1908
-            $end                             = $DateTime->getTimestamp();
1909
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1910
-        } elseif ($status === 'today') {
1911
-            $DateTime                        =
1912
-                new DateTime('now', new DateTimeZone(EEM_Event::instance()->get_timezone()));
1913
-            $start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1914
-            $end                             = $DateTime->setTime(23, 59, 59)->format(implode(' ', $start_formats));
1915
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1916
-        } elseif ($status === 'month') {
1917
-            $now                             = date('Y-m-01');
1918
-            $DateTime                        =
1919
-                new DateTime($now, new DateTimeZone(EEM_Event::instance()->get_timezone()));
1920
-            $start                           = $DateTime->setTime(0, 0)->format(implode(' ', $start_formats));
1921
-            $end                             = $DateTime->setDate(date('Y'), date('m'), $DateTime->format('t'))
1922
-                                                        ->setTime(23, 59, 59)
1923
-                                                        ->format(implode(' ', $start_formats));
1924
-            $where['Datetime.DTT_EVT_start'] = ['BETWEEN', [$start, $end]];
1925
-        }
1926
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')) {
1927
-            $where['EVT_wp_user'] = get_current_user_id();
1928
-        } else {
1929
-            if (! isset($where['status'])) {
1930
-                if (! EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_events')) {
1931
-                    $where['OR'] = [
1932
-                        'status*restrict_private' => ['!=', 'private'],
1933
-                        'AND'                     => [
1934
-                            'status*inclusive' => ['=', 'private'],
1935
-                            'EVT_wp_user'      => get_current_user_id(),
1936
-                        ],
1937
-                    ];
1938
-                }
1939
-            }
1940
-        }
1941
-        $wp_user = $this->request->getRequestParam('EVT_wp_user', 0, 'int');
1942
-        if (
1943
-            $wp_user
1944
-            && $wp_user !== get_current_user_id()
1945
-            && EE_Registry::instance()->CAP->current_user_can('ee_read_others_events', 'get_events')
1946
-        ) {
1947
-            $where['EVT_wp_user'] = $wp_user;
1948
-        }
1949
-        // search query handling
1950
-        $search_term = $this->request->getRequestParam('s');
1951
-        if ($search_term) {
1952
-            $search_term = '%' . $search_term . '%';
1953
-            $where['OR'] = [
1954
-                'EVT_name'       => ['LIKE', $search_term],
1955
-                'EVT_desc'       => ['LIKE', $search_term],
1956
-                'EVT_short_desc' => ['LIKE', $search_term],
1957
-            ];
1958
-        }
1959
-        // filter events by venue.
1960
-        $venue = $this->request->getRequestParam('venue', 0, 'int');
1961
-        if ($venue) {
1962
-            $where['Venue.VNU_ID'] = $venue;
1963
-        }
1964
-        $request_params = $this->request->requestParams();
1965
-        $where          = apply_filters('FHEE__Events_Admin_Page__get_events__where', $where, $request_params);
1966
-        $query_params   = apply_filters(
1967
-            'FHEE__Events_Admin_Page__get_events__query_params',
1968
-            [
1969
-                $where,
1970
-                'limit'    => $limit,
1971
-                'order_by' => $orderby,
1972
-                'order'    => $order,
1973
-                'group_by' => 'EVT_ID',
1974
-            ],
1975
-            $request_params
1976
-        );
1977
-
1978
-        // let's first check if we have special requests coming in.
1979
-        $active_status = $this->request->getRequestParam('active_status');
1980
-        if ($active_status) {
1981
-            switch ($active_status) {
1982
-                case 'upcoming':
1983
-                    return $EEM_Event->get_upcoming_events($query_params, $count);
1984
-                case 'expired':
1985
-                    return $EEM_Event->get_expired_events($query_params, $count);
1986
-                case 'active':
1987
-                    return $EEM_Event->get_active_events($query_params, $count);
1988
-                case 'inactive':
1989
-                    return $EEM_Event->get_inactive_events($query_params, $count);
1990
-            }
1991
-        }
1992
-
1993
-        return $count ? $EEM_Event->count([$where], 'EVT_ID', true) : $EEM_Event->get_all($query_params);
1994
-    }
1995
-
1996
-
1997
-    /**
1998
-     * handling for WordPress CPT actions (trash, restore, delete)
1999
-     *
2000
-     * @param string $post_id
2001
-     * @throws EE_Error
2002
-     * @throws ReflectionException
2003
-     */
2004
-    public function trash_cpt_item($post_id)
2005
-    {
2006
-        $this->request->setRequestParam('EVT_ID', $post_id);
2007
-        $this->_trash_or_restore_event('trash', false);
2008
-    }
2009
-
2010
-
2011
-    /**
2012
-     * @param string $post_id
2013
-     * @throws EE_Error
2014
-     * @throws ReflectionException
2015
-     */
2016
-    public function restore_cpt_item($post_id)
2017
-    {
2018
-        $this->request->setRequestParam('EVT_ID', $post_id);
2019
-        $this->_trash_or_restore_event('draft', false);
2020
-    }
2021
-
2022
-
2023
-    /**
2024
-     * @param string $post_id
2025
-     * @throws EE_Error
2026
-     * @throws EE_Error
2027
-     */
2028
-    public function delete_cpt_item($post_id)
2029
-    {
2030
-        throw new EE_Error(
2031
-            esc_html__(
2032
-                'Please contact Event Espresso support with the details of the steps taken to produce this error.',
2033
-                'event_espresso'
2034
-            )
2035
-        );
2036
-        // $this->request->setRequestParam('EVT_ID', $post_id);
2037
-        // $this->_delete_event();
2038
-    }
2039
-
2040
-
2041
-    /**
2042
-     * _trash_or_restore_event
2043
-     *
2044
-     * @access protected
2045
-     * @param string $event_status
2046
-     * @param bool   $redirect_after
2047
-     * @throws EE_Error
2048
-     * @throws EE_Error
2049
-     * @throws ReflectionException
2050
-     */
2051
-    protected function _trash_or_restore_event($event_status = 'trash', $redirect_after = true)
2052
-    {
2053
-        // determine the event id and set to array.
2054
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
2055
-        // loop thru events
2056
-        if ($EVT_ID) {
2057
-            // clean status
2058
-            $event_status = sanitize_key($event_status);
2059
-            // grab status
2060
-            if (! empty($event_status)) {
2061
-                $success = $this->_change_event_status($EVT_ID, $event_status);
2062
-            } else {
2063
-                $success = false;
2064
-                $msg     = esc_html__(
2065
-                    'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2066
-                    'event_espresso'
2067
-                );
2068
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2069
-            }
2070
-        } else {
2071
-            $success = false;
2072
-            $msg     = esc_html__(
2073
-                'An error occurred. The event could not be moved to the trash because a valid event ID was not not supplied.',
2074
-                'event_espresso'
2075
-            );
2076
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2077
-        }
2078
-        $action = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2079
-        if ($redirect_after) {
2080
-            $this->_redirect_after_action($success, 'Event', $action, ['action' => 'default']);
2081
-        }
2082
-    }
2083
-
2084
-
2085
-    /**
2086
-     * _trash_or_restore_events
2087
-     *
2088
-     * @access protected
2089
-     * @param string $event_status
2090
-     * @return void
2091
-     * @throws EE_Error
2092
-     * @throws EE_Error
2093
-     * @throws ReflectionException
2094
-     */
2095
-    protected function _trash_or_restore_events($event_status = 'trash')
2096
-    {
2097
-        // clean status
2098
-        $event_status = sanitize_key($event_status);
2099
-        // grab status
2100
-        if (! empty($event_status)) {
2101
-            $success = true;
2102
-            // determine the event id and set to array.
2103
-            $EVT_IDs = $this->request->getRequestParam('EVT_IDs', [], 'int', true);
2104
-            // loop thru events
2105
-            foreach ($EVT_IDs as $EVT_ID) {
2106
-                if ($EVT_ID = absint($EVT_ID)) {
2107
-                    $results = $this->_change_event_status($EVT_ID, $event_status);
2108
-                    $success = $results !== false ? $success : false;
2109
-                } else {
2110
-                    $msg = sprintf(
2111
-                        esc_html__(
2112
-                            'An error occurred. Event #%d could not be moved to the trash because a valid event ID was not not supplied.',
2113
-                            'event_espresso'
2114
-                        ),
2115
-                        $EVT_ID
2116
-                    );
2117
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2118
-                    $success = false;
2119
-                }
2120
-            }
2121
-        } else {
2122
-            $success = false;
2123
-            $msg     = esc_html__(
2124
-                'An error occurred. The event could not be moved to the trash because a valid event status was not not supplied.',
2125
-                'event_espresso'
2126
-            );
2127
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2128
-        }
2129
-        // in order to force a pluralized result message we need to send back a success status greater than 1
2130
-        $success = $success ? 2 : false;
2131
-        $action  = $event_status == 'trash' ? 'moved to the trash' : 'restored from the trash';
2132
-        $this->_redirect_after_action($success, 'Events', $action, ['action' => 'default']);
2133
-    }
2134
-
2135
-
2136
-    /**
2137
-     * @param int    $EVT_ID
2138
-     * @param string $event_status
2139
-     * @return bool
2140
-     * @throws EE_Error
2141
-     * @throws ReflectionException
2142
-     */
2143
-    private function _change_event_status($EVT_ID = 0, $event_status = '')
2144
-    {
2145
-        // grab event id
2146
-        if (! $EVT_ID) {
2147
-            $msg = esc_html__(
2148
-                'An error occurred. No Event ID or an invalid Event ID was received.',
2149
-                'event_espresso'
2150
-            );
2151
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2152
-            return false;
2153
-        }
2154
-        $this->_cpt_model_obj = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2155
-        // clean status
2156
-        $event_status = sanitize_key($event_status);
2157
-        // grab status
2158
-        if (empty($event_status)) {
2159
-            $msg = esc_html__(
2160
-                'An error occurred. No Event Status or an invalid Event Status was received.',
2161
-                'event_espresso'
2162
-            );
2163
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2164
-            return false;
2165
-        }
2166
-        // was event trashed or restored ?
2167
-        switch ($event_status) {
2168
-            case 'draft':
2169
-                $action = 'restored from the trash';
2170
-                $hook   = 'AHEE_event_restored_from_trash';
2171
-                break;
2172
-            case 'trash':
2173
-                $action = 'moved to the trash';
2174
-                $hook   = 'AHEE_event_moved_to_trash';
2175
-                break;
2176
-            default:
2177
-                $action = 'updated';
2178
-                $hook   = false;
2179
-        }
2180
-        // use class to change status
2181
-        $this->_cpt_model_obj->set_status($event_status);
2182
-        $success = $this->_cpt_model_obj->save();
2183
-        if (! $success) {
2184
-            $msg = sprintf(esc_html__('An error occurred. The event could not be %s.', 'event_espresso'), $action);
2185
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2186
-            return false;
2187
-        }
2188
-        if ($hook) {
2189
-            do_action($hook);
2190
-        }
2191
-        return true;
2192
-    }
2193
-
2194
-
2195
-    /**
2196
-     * @param array $event_ids
2197
-     * @return array
2198
-     * @since   4.10.23.p
2199
-     */
2200
-    private function cleanEventIds(array $event_ids)
2201
-    {
2202
-        return array_map('absint', $event_ids);
2203
-    }
2204
-
2205
-
2206
-    /**
2207
-     * @return array
2208
-     * @since   4.10.23.p
2209
-     */
2210
-    private function getEventIdsFromRequest()
2211
-    {
2212
-        return $this->request->getRequestParam('EVT_IDs', [], 'int', true, ',');
2213
-    }
2214
-
2215
-
2216
-    /**
2217
-     * @param bool $preview_delete
2218
-     * @throws EE_Error
2219
-     */
2220
-    protected function _delete_event($preview_delete = true)
2221
-    {
2222
-        $this->_delete_events($preview_delete);
2223
-    }
2224
-
2225
-
2226
-    /**
2227
-     * Gets the tree traversal batch persister.
2228
-     *
2229
-     * @return NodeGroupDao
2230
-     * @throws InvalidArgumentException
2231
-     * @throws InvalidDataTypeException
2232
-     * @throws InvalidInterfaceException
2233
-     * @since 4.10.12.p
2234
-     */
2235
-    protected function getModelObjNodeGroupPersister()
2236
-    {
2237
-        if (! $this->model_obj_node_group_persister instanceof NodeGroupDao) {
2238
-            $this->model_obj_node_group_persister =
2239
-                $this->getLoader()->load('\EventEspresso\core\services\orm\tree_traversal\NodeGroupDao');
2240
-        }
2241
-        return $this->model_obj_node_group_persister;
2242
-    }
2243
-
2244
-
2245
-    /**
2246
-     * @param bool $preview_delete
2247
-     * @return void
2248
-     * @throws EE_Error
2249
-     */
2250
-    protected function _delete_events($preview_delete = true)
2251
-    {
2252
-        $event_ids = $this->getEventIdsFromRequest();
2253
-        if ($preview_delete) {
2254
-            $this->generateDeletionPreview($event_ids);
2255
-        } else {
2256
-            EEM_Event::instance()->delete_permanently([['EVT_ID' => ['IN', $event_ids]]]);
2257
-        }
2258
-    }
2259
-
2260
-
2261
-    /**
2262
-     * @param array $event_ids
2263
-     */
2264
-    protected function generateDeletionPreview(array $event_ids)
2265
-    {
2266
-        $event_ids = $this->cleanEventIds($event_ids);
2267
-        // Set a code we can use to reference this deletion task in the batch jobs and preview page.
2268
-        $deletion_job_code = $this->getModelObjNodeGroupPersister()->generateGroupCode();
2269
-        $return_url        = EE_Admin_Page::add_query_args_and_nonce(
2270
-            [
2271
-                'action'            => 'preview_deletion',
2272
-                'deletion_job_code' => $deletion_job_code,
2273
-            ],
2274
-            $this->_admin_base_url
2275
-        );
2276
-        EEH_URL::safeRedirectAndExit(
2277
-            EE_Admin_Page::add_query_args_and_nonce(
2278
-                [
2279
-                    'page'              => 'espresso_batch',
2280
-                    'batch'             => EED_Batch::batch_job,
2281
-                    'EVT_IDs'           => $event_ids,
2282
-                    'deletion_job_code' => $deletion_job_code,
2283
-                    'job_handler'       => urlencode('EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion'),
2284
-                    'return_url'        => urlencode($return_url),
2285
-                ],
2286
-                admin_url()
2287
-            )
2288
-        );
2289
-    }
2290
-
2291
-
2292
-    /**
2293
-     * Checks for a POST submission
2294
-     *
2295
-     * @since 4.10.12.p
2296
-     */
2297
-    protected function confirmDeletion()
2298
-    {
2299
-        $deletion_redirect_logic =
2300
-            $this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion');
2301
-        $deletion_redirect_logic->handle($this->get_request_data(), $this->admin_base_url());
2302
-    }
2303
-
2304
-
2305
-    /**
2306
-     * A page for users to preview what exactly will be deleted, and confirm they want to delete it.
2307
-     *
2308
-     * @throws EE_Error
2309
-     * @since 4.10.12.p
2310
-     */
2311
-    protected function previewDeletion()
2312
-    {
2313
-        $preview_deletion_logic =
2314
-            $this->getLoader()->getShared('\EventEspresso\core\domain\services\admin\events\data\PreviewDeletion');
2315
-        $this->set_template_args($preview_deletion_logic->handle($this->get_request_data(), $this->admin_base_url()));
2316
-        $this->display_admin_page_with_no_sidebar();
2317
-    }
2318
-
2319
-
2320
-    /**
2321
-     * get total number of events
2322
-     *
2323
-     * @access public
2324
-     * @return int
2325
-     * @throws EE_Error
2326
-     * @throws EE_Error
2327
-     */
2328
-    public function total_events()
2329
-    {
2330
-        return EEM_Event::instance()->count(
2331
-            ['caps' => 'read_admin'],
2332
-            'EVT_ID',
2333
-            true
2334
-        );
2335
-    }
2336
-
2337
-
2338
-    /**
2339
-     * get total number of draft events
2340
-     *
2341
-     * @access public
2342
-     * @return int
2343
-     * @throws EE_Error
2344
-     * @throws EE_Error
2345
-     */
2346
-    public function total_events_draft()
2347
-    {
2348
-        return EEM_Event::instance()->count(
2349
-            [
2350
-                ['status' => ['IN', ['draft', 'auto-draft']]],
2351
-                'caps' => 'read_admin',
2352
-            ],
2353
-            'EVT_ID',
2354
-            true
2355
-        );
2356
-    }
2357
-
2358
-
2359
-    /**
2360
-     * get total number of trashed events
2361
-     *
2362
-     * @access public
2363
-     * @return int
2364
-     * @throws EE_Error
2365
-     * @throws EE_Error
2366
-     */
2367
-    public function total_trashed_events()
2368
-    {
2369
-        return EEM_Event::instance()->count(
2370
-            [
2371
-                ['status' => 'trash'],
2372
-                'caps' => 'read_admin',
2373
-            ],
2374
-            'EVT_ID',
2375
-            true
2376
-        );
2377
-    }
2378
-
2379
-
2380
-    /**
2381
-     *    _default_event_settings
2382
-     *    This generates the Default Settings Tab
2383
-     *
2384
-     * @return void
2385
-     * @throws EE_Error
2386
-     */
2387
-    protected function _default_event_settings()
2388
-    {
2389
-        $this->_set_add_edit_form_tags('update_default_event_settings');
2390
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
2391
-        $this->_template_args['admin_page_content'] = $this->_default_event_settings_form()->get_html();
2392
-        $this->display_admin_page_with_sidebar();
2393
-    }
2394
-
2395
-
2396
-    /**
2397
-     * Return the form for event settings.
2398
-     *
2399
-     * @return EE_Form_Section_Proper
2400
-     * @throws EE_Error
2401
-     */
2402
-    protected function _default_event_settings_form()
2403
-    {
2404
-        $registration_config              = EE_Registry::instance()->CFG->registration;
2405
-        $registration_stati_for_selection = EEM_Registration::reg_status_array(
2406
-        // exclude
2407
-            [
2408
-                EEM_Registration::status_id_cancelled,
2409
-                EEM_Registration::status_id_declined,
2410
-                EEM_Registration::status_id_incomplete,
2411
-                EEM_Registration::status_id_wait_list,
2412
-            ],
2413
-            true
2414
-        );
2415
-        return new EE_Form_Section_Proper(
2416
-            [
2417
-                'name'            => 'update_default_event_settings',
2418
-                'html_id'         => 'update_default_event_settings',
2419
-                'html_class'      => 'form-table',
2420
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2421
-                'subsections'     => apply_filters(
2422
-                    'FHEE__Events_Admin_Page___default_event_settings_form__form_subsections',
2423
-                    [
2424
-                        'default_reg_status'  => new EE_Select_Input(
2425
-                            $registration_stati_for_selection,
2426
-                            [
2427
-                                'default'         => isset($registration_config->default_STS_ID)
2428
-                                                     && array_key_exists(
2429
-                                                         $registration_config->default_STS_ID,
2430
-                                                         $registration_stati_for_selection
2431
-                                                     )
2432
-                                    ? sanitize_text_field($registration_config->default_STS_ID)
2433
-                                    : EEM_Registration::status_id_pending_payment,
2434
-                                'html_label_text' => esc_html__('Default Registration Status', 'event_espresso')
2435
-                                                     . EEH_Template::get_help_tab_link(
2436
-                                                         'default_settings_status_help_tab'
2437
-                                                     ),
2438
-                                'html_help_text'  => esc_html__(
2439
-                                    'This setting allows you to preselect what the default registration status setting is when creating an event.  Note that changing this setting does NOT retroactively apply it to existing events.',
2440
-                                    'event_espresso'
2441
-                                ),
2442
-                            ]
2443
-                        ),
2444
-                        'default_max_tickets' => new EE_Integer_Input(
2445
-                            [
2446
-                                'default'         => isset($registration_config->default_maximum_number_of_tickets)
2447
-                                    ? $registration_config->default_maximum_number_of_tickets
2448
-                                    : EEM_Event::get_default_additional_limit(),
2449
-                                'html_label_text' => esc_html__(
2450
-                                    'Default Maximum Tickets Allowed Per Order:',
2451
-                                    'event_espresso'
2452
-                                )
2453
-                                . EEH_Template::get_help_tab_link(
2454
-                                    'default_maximum_tickets_help_tab"'
2455
-                                ),
2456
-                                'html_help_text'  => esc_html__(
2457
-                                    'This setting allows you to indicate what will be the default for the maximum number of tickets per order when creating new events.',
2458
-                                    'event_espresso'
2459
-                                ),
2460
-                            ]
2461
-                        ),
2462
-                    ]
2463
-                ),
2464
-            ]
2465
-        );
2466
-    }
2467
-
2468
-
2469
-    /**
2470
-     * _update_default_event_settings
2471
-     *
2472
-     * @access protected
2473
-     * @return void
2474
-     * @throws EE_Error
2475
-     */
2476
-    protected function _update_default_event_settings()
2477
-    {
2478
-        $registration_config = EE_Registry::instance()->CFG->registration;
2479
-        $form                = $this->_default_event_settings_form();
2480
-        if ($form->was_submitted()) {
2481
-            $form->receive_form_submission();
2482
-            if ($form->is_valid()) {
2483
-                $valid_data = $form->valid_data();
2484
-                if (isset($valid_data['default_reg_status'])) {
2485
-                    $registration_config->default_STS_ID = $valid_data['default_reg_status'];
2486
-                }
2487
-                if (isset($valid_data['default_max_tickets'])) {
2488
-                    $registration_config->default_maximum_number_of_tickets = $valid_data['default_max_tickets'];
2489
-                }
2490
-                // update because data was valid!
2491
-                EE_Registry::instance()->CFG->update_espresso_config();
2492
-                EE_Error::overwrite_success();
2493
-                EE_Error::add_success(
2494
-                    esc_html__('Default Event Settings were updated', 'event_espresso')
2495
-                );
2496
-            }
2497
-        }
2498
-        $this->_redirect_after_action(0, '', '', ['action' => 'default_event_settings'], true);
2499
-    }
2500
-
2501
-
2502
-    /*************        Templates        *************
2503
-     *
2504
-     * @throws EE_Error
2505
-     */
2506
-    protected function _template_settings()
2507
-    {
2508
-        $this->_admin_page_title              = esc_html__('Template Settings (Preview)', 'event_espresso');
2509
-        $this->_template_args['preview_img']  = '<img src="'
2510
-                                                . EVENTS_ASSETS_URL
2511
-                                                . '/images/'
2512
-                                                . 'caffeinated_template_features.jpg" alt="'
2513
-                                                . esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2514
-                                                . '" />';
2515
-        $this->_template_args['preview_text'] = '<strong>'
2516
-                                                . esc_html__(
2517
-                                                    'Template Settings is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. Template Settings allow you to configure some of the appearance options for both the Event List and Event Details pages.',
2518
-                                                    'event_espresso'
2519
-                                                ) . '</strong>';
2520
-        $this->display_admin_caf_preview_page('template_settings_tab');
2521
-    }
2522
-
2523
-
2524
-    /** Event Category Stuff **/
2525
-    /**
2526
-     * set the _category property with the category object for the loaded page.
2527
-     *
2528
-     * @access private
2529
-     * @return void
2530
-     */
2531
-    private function _set_category_object()
2532
-    {
2533
-        if (isset($this->_category->id) && ! empty($this->_category->id)) {
2534
-            return;
2535
-        } //already have the category object so get out.
2536
-        // set default category object
2537
-        $this->_set_empty_category_object();
2538
-        // only set if we've got an id
2539
-        $category_ID = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
2540
-        if (! $category_ID) {
2541
-            return;
2542
-        }
2543
-        $term = get_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2544
-        if (! empty($term)) {
2545
-            $this->_category->category_name       = $term->name;
2546
-            $this->_category->category_identifier = $term->slug;
2547
-            $this->_category->category_desc       = $term->description;
2548
-            $this->_category->id                  = $term->term_id;
2549
-            $this->_category->parent              = $term->parent;
2550
-        }
2551
-    }
2552
-
2553
-
2554
-    /**
2555
-     * Clears out category properties.
2556
-     */
2557
-    private function _set_empty_category_object()
2558
-    {
2559
-        $this->_category                = new stdClass();
2560
-        $this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2561
-        $this->_category->id            = $this->_category->parent = 0;
2562
-    }
2563
-
2564
-
2565
-    /**
2566
-     * @throws EE_Error
2567
-     */
2568
-    protected function _category_list_table()
2569
-    {
2570
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2571
-        $this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2572
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
2573
-            'add_category',
2574
-            'add_category',
2575
-            [],
2576
-            'add-new-h2'
2577
-        );
2578
-        $this->display_admin_list_table_page_with_sidebar();
2579
-    }
2580
-
2581
-
2582
-    /**
2583
-     * Output category details view.
2584
-     *
2585
-     * @throws EE_Error
2586
-     * @throws EE_Error
2587
-     */
2588
-    protected function _category_details($view)
2589
-    {
2590
-        // load formatter helper
2591
-        // load field generator helper
2592
-        $route = $view == 'edit' ? 'update_category' : 'insert_category';
2593
-        $this->_set_add_edit_form_tags($route);
2594
-        $this->_set_category_object();
2595
-        $id            = ! empty($this->_category->id) ? $this->_category->id : '';
2596
-        $delete_action = 'delete_category';
2597
-        // custom redirect
2598
-        $redirect = EE_Admin_Page::add_query_args_and_nonce(
2599
-            ['action' => 'category_list'],
2600
-            $this->_admin_base_url
2601
-        );
2602
-        $this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect);
2603
-        // take care of contents
2604
-        $this->_template_args['admin_page_content'] = $this->_category_details_content();
2605
-        $this->display_admin_page_with_sidebar();
2606
-    }
2607
-
2608
-
2609
-    /**
2610
-     * Output category details content.
2611
-     */
2612
-    protected function _category_details_content()
2613
-    {
2614
-        $editor_args['category_desc'] = [
2615
-            'type'          => 'wp_editor',
2616
-            'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2617
-            'class'         => 'my_editor_custom',
2618
-            'wpeditor_args' => ['media_buttons' => false],
2619
-        ];
2620
-        $_wp_editor                   = $this->_generate_admin_form_fields($editor_args, 'array');
2621
-        $all_terms                    = get_terms(
2622
-            [EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY],
2623
-            ['hide_empty' => 0, 'exclude' => [$this->_category->id]]
2624
-        );
2625
-        // setup category select for term parents.
2626
-        $category_select_values[] = [
2627
-            'text' => esc_html__('No Parent', 'event_espresso'),
2628
-            'id'   => 0,
2629
-        ];
2630
-        foreach ($all_terms as $term) {
2631
-            $category_select_values[] = [
2632
-                'text' => $term->name,
2633
-                'id'   => $term->term_id,
2634
-            ];
2635
-        }
2636
-        $category_select = EEH_Form_Fields::select_input(
2637
-            'category_parent',
2638
-            $category_select_values,
2639
-            $this->_category->parent
2640
-        );
2641
-        $template_args   = [
2642
-            'category'                 => $this->_category,
2643
-            'category_select'          => $category_select,
2644
-            'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2645
-            'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2646
-            'disable'                  => '',
2647
-            'disabled_message'         => false,
2648
-        ];
2649
-        $template        = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2650
-        return EEH_Template::display_template($template, $template_args, true);
2651
-    }
2652
-
2653
-
2654
-    /**
2655
-     * Handles deleting categories.
2656
-     *
2657
-     * @throws EE_Error
2658
-     */
2659
-    protected function _delete_categories()
2660
-    {
2661
-        $category_IDs = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int', true);
2662
-        foreach ($category_IDs as $category_ID) {
2663
-            $this->_delete_category($category_ID);
2664
-        }
2665
-        // doesn't matter what page we're coming from... we're going to the same place after delete.
2666
-        $query_args = [
2667
-            'action' => 'category_list',
2668
-        ];
2669
-        $this->_redirect_after_action(0, '', '', $query_args);
2670
-    }
2671
-
2672
-
2673
-    /**
2674
-     * Handles deleting specific category.
2675
-     *
2676
-     * @param int $cat_id
2677
-     */
2678
-    protected function _delete_category($cat_id)
2679
-    {
2680
-        $cat_id = absint($cat_id);
2681
-        wp_delete_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2682
-    }
2683
-
2684
-
2685
-    /**
2686
-     * Handles triggering the update or insertion of a new category.
2687
-     *
2688
-     * @param bool $new_category true means we're triggering the insert of a new category.
2689
-     * @throws EE_Error
2690
-     * @throws EE_Error
2691
-     */
2692
-    protected function _insert_or_update_category($new_category)
2693
-    {
2694
-        $cat_id  = $new_category ? $this->_insert_category() : $this->_insert_category(true);
2695
-        $success = 0; // we already have a success message so lets not send another.
2696
-        if ($cat_id) {
2697
-            $query_args = [
2698
-                'action'     => 'edit_category',
2699
-                'EVT_CAT_ID' => $cat_id,
2700
-            ];
2701
-        } else {
2702
-            $query_args = ['action' => 'add_category'];
2703
-        }
2704
-        $this->_redirect_after_action($success, '', '', $query_args, true);
2705
-    }
2706
-
2707
-
2708
-    /**
2709
-     * Inserts or updates category
2710
-     *
2711
-     * @param bool $update (true indicates we're updating a category).
2712
-     * @return bool|mixed|string
2713
-     */
2714
-    private function _insert_category($update = false)
2715
-    {
2716
-        $category_ID         = $update ? $this->request->getRequestParam('EVT_CAT_ID', 0, 'int') : 0;
2717
-        $category_name       = $this->request->getRequestParam('category_name', '');
2718
-        $category_desc       = $this->request->getRequestParam('category_desc', '');
2719
-        $category_parent     = $this->request->getRequestParam('category_parent', 0, 'int');
2720
-        $category_identifier = $this->request->getRequestParam('category_identifier', '');
2721
-
2722
-        if (empty($category_name)) {
2723
-            $msg = esc_html__('You must add a name for the category.', 'event_espresso');
2724
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2725
-            return false;
2726
-        }
2727
-        $term_args = [
2728
-            'name'        => $category_name,
2729
-            'description' => $category_desc,
2730
-            'parent'      => $category_parent,
2731
-        ];
2732
-        // was the category_identifier input disabled?
2733
-        if ($category_identifier) {
2734
-            $term_args['slug'] = $category_identifier;
2735
-        }
2736
-        $insert_ids = $update
2737
-            ? wp_update_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2738
-            : wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2739
-        if (! is_array($insert_ids)) {
2740
-            $msg = esc_html__(
2741
-                'An error occurred and the category has not been saved to the database.',
2742
-                'event_espresso'
2743
-            );
2744
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2745
-        } else {
2746
-            $category_ID = $insert_ids['term_id'];
2747
-            $msg         =
2748
-                sprintf(esc_html__('The category %s was successfully saved', 'event_espresso'), $category_name);
2749
-            EE_Error::add_success($msg);
2750
-        }
2751
-        return $category_ID;
2752
-    }
2753
-
2754
-
2755
-    /**
2756
-     * Gets categories or count of categories matching the arguments in the request.
2757
-     *
2758
-     * @param int  $per_page
2759
-     * @param int  $current_page
2760
-     * @param bool $count
2761
-     * @return EE_Term_Taxonomy[]|int
2762
-     * @throws EE_Error
2763
-     * @throws EE_Error
2764
-     */
2765
-    public function get_categories($per_page = 10, $current_page = 1, $count = false)
2766
-    {
2767
-        // testing term stuff
2768
-        $orderby     = $this->request->getRequestParam('orderby', 'Term.term_id');
2769
-        $order       = $this->request->getRequestParam('order', 'DESC');
2770
-        $limit       = ($current_page - 1) * $per_page;
2771
-        $where       = ['taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY];
2772
-        $search_term = $this->request->getRequestParam('s');
2773
-        if ($search_term) {
2774
-            $search_term = '%' . $search_term . '%';
2775
-            $where['OR'] = [
2776
-                'Term.name'   => ['LIKE', $search_term],
2777
-                'description' => ['LIKE', $search_term],
2778
-            ];
2779
-        }
2780
-        $query_params = [
2781
-            $where,
2782
-            'order_by'   => [$orderby => $order],
2783
-            'limit'      => $limit . ',' . $per_page,
2784
-            'force_join' => ['Term'],
2785
-        ];
2786
-        return $count
2787
-            ? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2788
-            : EEM_Term_Taxonomy::instance()->get_all($query_params);
2789
-    }
2790
-
2791
-    /* end category stuff */
2792
-    /**************/
2793
-
2794
-
2795
-    /**
2796
-     * Callback for the `ee_save_timezone_setting` ajax action.
2797
-     *
2798
-     * @throws EE_Error
2799
-     */
2800
-    public function saveTimezoneString()
2801
-    {
2802
-        $timezone_string = $this->request->getRequestParam('timezone_selected');
2803
-        if (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false)) {
2804
-            EE_Error::add_error(
2805
-                esc_html__('An invalid timezone string submitted.', 'event_espresso'),
2806
-                __FILE__,
2807
-                __FUNCTION__,
2808
-                __LINE__
2809
-            );
2810
-            $this->_template_args['error'] = true;
2811
-            $this->_return_json();
2812
-        }
2813
-
2814
-        update_option('timezone_string', $timezone_string);
2815
-        EE_Error::add_success(
2816
-            esc_html__('Your timezone string was updated.', 'event_espresso')
2817
-        );
2818
-        $this->_template_args['success'] = true;
2819
-        $this->_return_json(true, ['action' => 'create_new']);
2820
-    }
2821
-
2822
-
2823
-    /**
2824 2504
      * @throws EE_Error
2825
-     * @deprecated 4.10.25.p
2826 2505
      */
2827
-    public function save_timezonestring_setting()
2828
-    {
2829
-        $this->saveTimezoneString();
2830
-    }
2506
+	protected function _template_settings()
2507
+	{
2508
+		$this->_admin_page_title              = esc_html__('Template Settings (Preview)', 'event_espresso');
2509
+		$this->_template_args['preview_img']  = '<img src="'
2510
+												. EVENTS_ASSETS_URL
2511
+												. '/images/'
2512
+												. 'caffeinated_template_features.jpg" alt="'
2513
+												. esc_attr__('Template Settings Preview screenshot', 'event_espresso')
2514
+												. '" />';
2515
+		$this->_template_args['preview_text'] = '<strong>'
2516
+												. esc_html__(
2517
+													'Template Settings is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. Template Settings allow you to configure some of the appearance options for both the Event List and Event Details pages.',
2518
+													'event_espresso'
2519
+												) . '</strong>';
2520
+		$this->display_admin_caf_preview_page('template_settings_tab');
2521
+	}
2522
+
2523
+
2524
+	/** Event Category Stuff **/
2525
+	/**
2526
+	 * set the _category property with the category object for the loaded page.
2527
+	 *
2528
+	 * @access private
2529
+	 * @return void
2530
+	 */
2531
+	private function _set_category_object()
2532
+	{
2533
+		if (isset($this->_category->id) && ! empty($this->_category->id)) {
2534
+			return;
2535
+		} //already have the category object so get out.
2536
+		// set default category object
2537
+		$this->_set_empty_category_object();
2538
+		// only set if we've got an id
2539
+		$category_ID = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int');
2540
+		if (! $category_ID) {
2541
+			return;
2542
+		}
2543
+		$term = get_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2544
+		if (! empty($term)) {
2545
+			$this->_category->category_name       = $term->name;
2546
+			$this->_category->category_identifier = $term->slug;
2547
+			$this->_category->category_desc       = $term->description;
2548
+			$this->_category->id                  = $term->term_id;
2549
+			$this->_category->parent              = $term->parent;
2550
+		}
2551
+	}
2552
+
2553
+
2554
+	/**
2555
+	 * Clears out category properties.
2556
+	 */
2557
+	private function _set_empty_category_object()
2558
+	{
2559
+		$this->_category                = new stdClass();
2560
+		$this->_category->category_name = $this->_category->category_identifier = $this->_category->category_desc = '';
2561
+		$this->_category->id            = $this->_category->parent = 0;
2562
+	}
2563
+
2564
+
2565
+	/**
2566
+	 * @throws EE_Error
2567
+	 */
2568
+	protected function _category_list_table()
2569
+	{
2570
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2571
+		$this->_search_btn_label = esc_html__('Categories', 'event_espresso');
2572
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
2573
+			'add_category',
2574
+			'add_category',
2575
+			[],
2576
+			'add-new-h2'
2577
+		);
2578
+		$this->display_admin_list_table_page_with_sidebar();
2579
+	}
2580
+
2581
+
2582
+	/**
2583
+	 * Output category details view.
2584
+	 *
2585
+	 * @throws EE_Error
2586
+	 * @throws EE_Error
2587
+	 */
2588
+	protected function _category_details($view)
2589
+	{
2590
+		// load formatter helper
2591
+		// load field generator helper
2592
+		$route = $view == 'edit' ? 'update_category' : 'insert_category';
2593
+		$this->_set_add_edit_form_tags($route);
2594
+		$this->_set_category_object();
2595
+		$id            = ! empty($this->_category->id) ? $this->_category->id : '';
2596
+		$delete_action = 'delete_category';
2597
+		// custom redirect
2598
+		$redirect = EE_Admin_Page::add_query_args_and_nonce(
2599
+			['action' => 'category_list'],
2600
+			$this->_admin_base_url
2601
+		);
2602
+		$this->_set_publish_post_box_vars('EVT_CAT_ID', $id, $delete_action, $redirect);
2603
+		// take care of contents
2604
+		$this->_template_args['admin_page_content'] = $this->_category_details_content();
2605
+		$this->display_admin_page_with_sidebar();
2606
+	}
2607
+
2608
+
2609
+	/**
2610
+	 * Output category details content.
2611
+	 */
2612
+	protected function _category_details_content()
2613
+	{
2614
+		$editor_args['category_desc'] = [
2615
+			'type'          => 'wp_editor',
2616
+			'value'         => EEH_Formatter::admin_format_content($this->_category->category_desc),
2617
+			'class'         => 'my_editor_custom',
2618
+			'wpeditor_args' => ['media_buttons' => false],
2619
+		];
2620
+		$_wp_editor                   = $this->_generate_admin_form_fields($editor_args, 'array');
2621
+		$all_terms                    = get_terms(
2622
+			[EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY],
2623
+			['hide_empty' => 0, 'exclude' => [$this->_category->id]]
2624
+		);
2625
+		// setup category select for term parents.
2626
+		$category_select_values[] = [
2627
+			'text' => esc_html__('No Parent', 'event_espresso'),
2628
+			'id'   => 0,
2629
+		];
2630
+		foreach ($all_terms as $term) {
2631
+			$category_select_values[] = [
2632
+				'text' => $term->name,
2633
+				'id'   => $term->term_id,
2634
+			];
2635
+		}
2636
+		$category_select = EEH_Form_Fields::select_input(
2637
+			'category_parent',
2638
+			$category_select_values,
2639
+			$this->_category->parent
2640
+		);
2641
+		$template_args   = [
2642
+			'category'                 => $this->_category,
2643
+			'category_select'          => $category_select,
2644
+			'unique_id_info_help_link' => $this->_get_help_tab_link('unique_id_info'),
2645
+			'category_desc_editor'     => $_wp_editor['category_desc']['field'],
2646
+			'disable'                  => '',
2647
+			'disabled_message'         => false,
2648
+		];
2649
+		$template        = EVENTS_TEMPLATE_PATH . 'event_category_details.template.php';
2650
+		return EEH_Template::display_template($template, $template_args, true);
2651
+	}
2652
+
2653
+
2654
+	/**
2655
+	 * Handles deleting categories.
2656
+	 *
2657
+	 * @throws EE_Error
2658
+	 */
2659
+	protected function _delete_categories()
2660
+	{
2661
+		$category_IDs = $this->request->getRequestParam('EVT_CAT_ID', 0, 'int', true);
2662
+		foreach ($category_IDs as $category_ID) {
2663
+			$this->_delete_category($category_ID);
2664
+		}
2665
+		// doesn't matter what page we're coming from... we're going to the same place after delete.
2666
+		$query_args = [
2667
+			'action' => 'category_list',
2668
+		];
2669
+		$this->_redirect_after_action(0, '', '', $query_args);
2670
+	}
2671
+
2672
+
2673
+	/**
2674
+	 * Handles deleting specific category.
2675
+	 *
2676
+	 * @param int $cat_id
2677
+	 */
2678
+	protected function _delete_category($cat_id)
2679
+	{
2680
+		$cat_id = absint($cat_id);
2681
+		wp_delete_term($cat_id, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY);
2682
+	}
2683
+
2684
+
2685
+	/**
2686
+	 * Handles triggering the update or insertion of a new category.
2687
+	 *
2688
+	 * @param bool $new_category true means we're triggering the insert of a new category.
2689
+	 * @throws EE_Error
2690
+	 * @throws EE_Error
2691
+	 */
2692
+	protected function _insert_or_update_category($new_category)
2693
+	{
2694
+		$cat_id  = $new_category ? $this->_insert_category() : $this->_insert_category(true);
2695
+		$success = 0; // we already have a success message so lets not send another.
2696
+		if ($cat_id) {
2697
+			$query_args = [
2698
+				'action'     => 'edit_category',
2699
+				'EVT_CAT_ID' => $cat_id,
2700
+			];
2701
+		} else {
2702
+			$query_args = ['action' => 'add_category'];
2703
+		}
2704
+		$this->_redirect_after_action($success, '', '', $query_args, true);
2705
+	}
2706
+
2707
+
2708
+	/**
2709
+	 * Inserts or updates category
2710
+	 *
2711
+	 * @param bool $update (true indicates we're updating a category).
2712
+	 * @return bool|mixed|string
2713
+	 */
2714
+	private function _insert_category($update = false)
2715
+	{
2716
+		$category_ID         = $update ? $this->request->getRequestParam('EVT_CAT_ID', 0, 'int') : 0;
2717
+		$category_name       = $this->request->getRequestParam('category_name', '');
2718
+		$category_desc       = $this->request->getRequestParam('category_desc', '');
2719
+		$category_parent     = $this->request->getRequestParam('category_parent', 0, 'int');
2720
+		$category_identifier = $this->request->getRequestParam('category_identifier', '');
2721
+
2722
+		if (empty($category_name)) {
2723
+			$msg = esc_html__('You must add a name for the category.', 'event_espresso');
2724
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2725
+			return false;
2726
+		}
2727
+		$term_args = [
2728
+			'name'        => $category_name,
2729
+			'description' => $category_desc,
2730
+			'parent'      => $category_parent,
2731
+		];
2732
+		// was the category_identifier input disabled?
2733
+		if ($category_identifier) {
2734
+			$term_args['slug'] = $category_identifier;
2735
+		}
2736
+		$insert_ids = $update
2737
+			? wp_update_term($category_ID, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args)
2738
+			: wp_insert_term($category_name, EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY, $term_args);
2739
+		if (! is_array($insert_ids)) {
2740
+			$msg = esc_html__(
2741
+				'An error occurred and the category has not been saved to the database.',
2742
+				'event_espresso'
2743
+			);
2744
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2745
+		} else {
2746
+			$category_ID = $insert_ids['term_id'];
2747
+			$msg         =
2748
+				sprintf(esc_html__('The category %s was successfully saved', 'event_espresso'), $category_name);
2749
+			EE_Error::add_success($msg);
2750
+		}
2751
+		return $category_ID;
2752
+	}
2753
+
2754
+
2755
+	/**
2756
+	 * Gets categories or count of categories matching the arguments in the request.
2757
+	 *
2758
+	 * @param int  $per_page
2759
+	 * @param int  $current_page
2760
+	 * @param bool $count
2761
+	 * @return EE_Term_Taxonomy[]|int
2762
+	 * @throws EE_Error
2763
+	 * @throws EE_Error
2764
+	 */
2765
+	public function get_categories($per_page = 10, $current_page = 1, $count = false)
2766
+	{
2767
+		// testing term stuff
2768
+		$orderby     = $this->request->getRequestParam('orderby', 'Term.term_id');
2769
+		$order       = $this->request->getRequestParam('order', 'DESC');
2770
+		$limit       = ($current_page - 1) * $per_page;
2771
+		$where       = ['taxonomy' => EEM_CPT_Base::EVENT_CATEGORY_TAXONOMY];
2772
+		$search_term = $this->request->getRequestParam('s');
2773
+		if ($search_term) {
2774
+			$search_term = '%' . $search_term . '%';
2775
+			$where['OR'] = [
2776
+				'Term.name'   => ['LIKE', $search_term],
2777
+				'description' => ['LIKE', $search_term],
2778
+			];
2779
+		}
2780
+		$query_params = [
2781
+			$where,
2782
+			'order_by'   => [$orderby => $order],
2783
+			'limit'      => $limit . ',' . $per_page,
2784
+			'force_join' => ['Term'],
2785
+		];
2786
+		return $count
2787
+			? EEM_Term_Taxonomy::instance()->count($query_params, 'term_id')
2788
+			: EEM_Term_Taxonomy::instance()->get_all($query_params);
2789
+	}
2790
+
2791
+	/* end category stuff */
2792
+	/**************/
2793
+
2794
+
2795
+	/**
2796
+	 * Callback for the `ee_save_timezone_setting` ajax action.
2797
+	 *
2798
+	 * @throws EE_Error
2799
+	 */
2800
+	public function saveTimezoneString()
2801
+	{
2802
+		$timezone_string = $this->request->getRequestParam('timezone_selected');
2803
+		if (empty($timezone_string) || ! EEH_DTT_Helper::validate_timezone($timezone_string, false)) {
2804
+			EE_Error::add_error(
2805
+				esc_html__('An invalid timezone string submitted.', 'event_espresso'),
2806
+				__FILE__,
2807
+				__FUNCTION__,
2808
+				__LINE__
2809
+			);
2810
+			$this->_template_args['error'] = true;
2811
+			$this->_return_json();
2812
+		}
2813
+
2814
+		update_option('timezone_string', $timezone_string);
2815
+		EE_Error::add_success(
2816
+			esc_html__('Your timezone string was updated.', 'event_espresso')
2817
+		);
2818
+		$this->_template_args['success'] = true;
2819
+		$this->_return_json(true, ['action' => 'create_new']);
2820
+	}
2821
+
2822
+
2823
+	/**
2824
+	 * @throws EE_Error
2825
+	 * @deprecated 4.10.25.p
2826
+	 */
2827
+	public function save_timezonestring_setting()
2828
+	{
2829
+		$this->saveTimezoneString();
2830
+	}
2831 2831
 }
Please login to merge, or discard this patch.
admin_pages/messages/Messages_Admin_Page.core.php 2 patches
Indentation   +4472 added lines, -4472 removed lines patch added patch discarded remove patch
@@ -17,2638 +17,2638 @@  discard block
 block discarded – undo
17 17
 class Messages_Admin_Page extends EE_Admin_Page
18 18
 {
19 19
 
20
-    /**
21
-     * @var EE_Message_Resource_Manager $_message_resource_manager
22
-     */
23
-    protected $_message_resource_manager;
24
-
25
-    /**
26
-     * @var string
27
-     */
28
-    protected $_active_message_type_name = '';
29
-
30
-    /**
31
-     * @var string
32
-     */
33
-    protected $_active_messenger_name = '';
34
-
35
-    /**
36
-     * @var EE_messenger $_active_messenger
37
-     */
38
-    protected $_active_messenger;
39
-
40
-    protected $_activate_meta_box_type;
41
-
42
-    protected $_current_message_meta_box;
43
-
44
-    protected $_current_message_meta_box_object;
45
-
46
-    protected $_context_switcher;
47
-
48
-    protected $_shortcodes           = [];
49
-
50
-    protected $_active_messengers    = [];
51
-
52
-    protected $_active_message_types = [];
53
-
54
-    /**
55
-     * @var EE_Message_Template_Group $_message_template_group
56
-     */
57
-    protected $_message_template_group;
58
-
59
-    protected $_m_mt_settings = [];
60
-
61
-
62
-    /**
63
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
64
-     * IF there is no group then it gets automatically set to the Default template pack.
65
-     *
66
-     * @since 4.5.0
67
-     *
68
-     * @var EE_Messages_Template_Pack
69
-     */
70
-    protected $_template_pack;
71
-
72
-
73
-    /**
74
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
75
-     * group is.  If there is no group then it automatically gets set to default.
76
-     *
77
-     * @since 4.5.0
78
-     *
79
-     * @var string
80
-     */
81
-    protected $_variation;
82
-
83
-
84
-    /**
85
-     * @param bool $routing
86
-     * @throws EE_Error
87
-     * @throws ReflectionException
88
-     */
89
-    public function __construct($routing = true)
90
-    {
91
-        // make sure messages autoloader is running
92
-        EED_Messages::set_autoloaders();
93
-        parent::__construct($routing);
94
-    }
95
-
96
-
97
-    /**
98
-     * @throws EE_Error
99
-     * @throws ReflectionException
100
-     */
101
-    protected function _init_page_props()
102
-    {
103
-        $this->page_slug        = EE_MSG_PG_SLUG;
104
-        $this->page_label       = esc_html__('Messages Settings', 'event_espresso');
105
-        $this->_admin_base_url  = EE_MSG_ADMIN_URL;
106
-        $this->_admin_base_path = EE_MSG_ADMIN;
107
-
108
-        $this->_active_messenger_name    = $this->request->getRequestParam('messenger', '');
109
-        $this->_active_message_type_name = $this->request->getRequestParam('message_type', '');
110
-
111
-        $this->_load_message_resource_manager();
112
-    }
113
-
114
-
115
-    /**
116
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
117
-     *
118
-     * @throws EE_Error
119
-     * @throws InvalidDataTypeException
120
-     * @throws InvalidInterfaceException
121
-     * @throws InvalidArgumentException
122
-     * @throws ReflectionException
123
-     */
124
-    protected function _load_message_resource_manager()
125
-    {
126
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
127
-    }
128
-
129
-
130
-    /**
131
-     * @return array
132
-     * @throws EE_Error
133
-     * @throws InvalidArgumentException
134
-     * @throws InvalidDataTypeException
135
-     * @throws InvalidInterfaceException
136
-     * @deprecated 4.9.9.rc.014
137
-     */
138
-    public function get_messengers_for_list_table()
139
-    {
140
-        EE_Error::doing_it_wrong(
141
-            __METHOD__,
142
-            sprintf(
143
-                esc_html__(
144
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
145
-                    'event_espresso'
146
-                ),
147
-                'Messages_Admin_Page::get_messengers_select_input()'
148
-            ),
149
-            '4.9.9.rc.014'
150
-        );
151
-
152
-        $m_values          = [];
153
-        $active_messengers = EEM_Message::instance()->get_all(['group_by' => 'MSG_messenger']);
154
-        // setup messengers for selects
155
-        $i = 1;
156
-        foreach ($active_messengers as $active_messenger) {
157
-            if ($active_messenger instanceof EE_Message) {
158
-                $m_values[ $i ]['id']   = $active_messenger->messenger();
159
-                $m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
160
-                $i++;
161
-            }
162
-        }
163
-
164
-        return $m_values;
165
-    }
166
-
167
-
168
-    /**
169
-     * @return array
170
-     * @throws EE_Error
171
-     * @throws InvalidArgumentException
172
-     * @throws InvalidDataTypeException
173
-     * @throws InvalidInterfaceException
174
-     * @deprecated 4.9.9.rc.014
175
-     */
176
-    public function get_message_types_for_list_table()
177
-    {
178
-        EE_Error::doing_it_wrong(
179
-            __METHOD__,
180
-            sprintf(
181
-                esc_html__(
182
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
183
-                    'event_espresso'
184
-                ),
185
-                'Messages_Admin_Page::get_message_types_select_input()'
186
-            ),
187
-            '4.9.9.rc.014'
188
-        );
189
-
190
-        $mt_values       = [];
191
-        $active_messages = EEM_Message::instance()->get_all(['group_by' => 'MSG_message_type']);
192
-        $i               = 1;
193
-        foreach ($active_messages as $active_message) {
194
-            if ($active_message instanceof EE_Message) {
195
-                $mt_values[ $i ]['id']   = $active_message->message_type();
196
-                $mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
197
-                $i++;
198
-            }
199
-        }
200
-
201
-        return $mt_values;
202
-    }
203
-
204
-
205
-    /**
206
-     * @return array
207
-     * @throws EE_Error
208
-     * @throws InvalidArgumentException
209
-     * @throws InvalidDataTypeException
210
-     * @throws InvalidInterfaceException
211
-     * @deprecated 4.9.9.rc.014
212
-     */
213
-    public function get_contexts_for_message_types_for_list_table()
214
-    {
215
-        EE_Error::doing_it_wrong(
216
-            __METHOD__,
217
-            sprintf(
218
-                esc_html__(
219
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
220
-                    'event_espresso'
221
-                ),
222
-                'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
223
-            ),
224
-            '4.9.9.rc.014'
225
-        );
226
-
227
-        $contexts                = [];
228
-        $active_message_contexts = EEM_Message::instance()->get_all(['group_by' => 'MSG_context']);
229
-        foreach ($active_message_contexts as $active_message) {
230
-            if ($active_message instanceof EE_Message) {
231
-                $message_type = $active_message->message_type_object();
232
-                if ($message_type instanceof EE_message_type) {
233
-                    $message_type_contexts = $message_type->get_contexts();
234
-                    foreach ($message_type_contexts as $context => $context_details) {
235
-                        $contexts[ $context ] = $context_details['label'];
236
-                    }
237
-                }
238
-            }
239
-        }
240
-
241
-        return $contexts;
242
-    }
243
-
244
-
245
-    /**
246
-     * Generate select input with provided messenger options array.
247
-     *
248
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
249
-     *                                 labels.
250
-     * @return string
251
-     * @throws EE_Error
252
-     */
253
-    public function get_messengers_select_input($messenger_options)
254
-    {
255
-        // if empty or just one value then just return an empty string
256
-        if (
257
-            empty($messenger_options)
258
-            || ! is_array($messenger_options)
259
-            || count($messenger_options) === 1
260
-        ) {
261
-            return '';
262
-        }
263
-        // merge in default
264
-        $messenger_options = array_merge(
265
-            ['none_selected' => esc_html__('Show All Messengers', 'event_espresso')],
266
-            $messenger_options
267
-        );
268
-        $input             = new EE_Select_Input(
269
-            $messenger_options,
270
-            [
271
-                'html_name'  => 'ee_messenger_filter_by',
272
-                'html_id'    => 'ee_messenger_filter_by',
273
-                'html_class' => 'wide',
274
-                'default'    => $this->request->getRequestParam('ee_messenger_filter_by', 'none_selected', 'title'),
275
-            ]
276
-        );
277
-
278
-        return $input->get_html_for_input();
279
-    }
280
-
281
-
282
-    /**
283
-     * Generate select input with provided message type options array.
284
-     *
285
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
286
-     *                                    message type labels
287
-     * @return string
288
-     * @throws EE_Error
289
-     */
290
-    public function get_message_types_select_input($message_type_options)
291
-    {
292
-        // if empty or count of options is 1 then just return an empty string
293
-        if (
294
-            empty($message_type_options)
295
-            || ! is_array($message_type_options)
296
-            || count($message_type_options) === 1
297
-        ) {
298
-            return '';
299
-        }
300
-        // merge in default
301
-        $message_type_options = array_merge(
302
-            ['none_selected' => esc_html__('Show All Message Types', 'event_espresso')],
303
-            $message_type_options
304
-        );
305
-        $input                = new EE_Select_Input(
306
-            $message_type_options,
307
-            [
308
-                'html_name'  => 'ee_message_type_filter_by',
309
-                'html_id'    => 'ee_message_type_filter_by',
310
-                'html_class' => 'wide',
311
-                'default'    => $this->request->getRequestParam('ee_message_type_filter_by', 'none_selected', 'title'),
312
-            ]
313
-        );
314
-
315
-        return $input->get_html_for_input();
316
-    }
317
-
318
-
319
-    /**
320
-     * Generate select input with provide message type contexts array.
321
-     *
322
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
323
-     *                               context label.
324
-     * @return string
325
-     * @throws EE_Error
326
-     */
327
-    public function get_contexts_for_message_types_select_input($context_options)
328
-    {
329
-        // if empty or count of options is one then just return empty string
330
-        if (
331
-            empty($context_options)
332
-            || ! is_array($context_options)
333
-            || count($context_options) === 1
334
-        ) {
335
-            return '';
336
-        }
337
-        // merge in default
338
-        $context_options = array_merge(
339
-            ['none_selected' => esc_html__('Show all Contexts', 'event_espresso')],
340
-            $context_options
341
-        );
342
-        $input           = new EE_Select_Input(
343
-            $context_options,
344
-            [
345
-                'html_name'  => 'ee_context_filter_by',
346
-                'html_id'    => 'ee_context_filter_by',
347
-                'html_class' => 'wide',
348
-                'default'    => $this->request->getRequestParam('ee_context_filter_by', 'none_selected', 'title'),
349
-            ]
350
-        );
351
-
352
-        return $input->get_html_for_input();
353
-    }
354
-
355
-
356
-    protected function _ajax_hooks()
357
-    {
358
-        add_action('wp_ajax_activate_messenger', [$this, 'activate_messenger_toggle']);
359
-        add_action('wp_ajax_activate_mt', [$this, 'activate_mt_toggle']);
360
-        add_action('wp_ajax_ee_msgs_save_settings', [$this, 'save_settings']);
361
-        add_action('wp_ajax_ee_msgs_update_mt_form', [$this, 'update_mt_form']);
362
-        add_action('wp_ajax_switch_template_pack', [$this, 'switch_template_pack']);
363
-        add_action('wp_ajax_toggle_context_template', [$this, 'toggle_context_template']);
364
-    }
365
-
366
-
367
-    protected function _define_page_props()
368
-    {
369
-        $this->_admin_page_title = $this->page_label;
370
-        $this->_labels           = [
371
-            'buttons'    => [
372
-                'add'    => esc_html__('Add New Message Template', 'event_espresso'),
373
-                'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
374
-                'delete' => esc_html__('Delete Message Template', 'event_espresso'),
375
-            ],
376
-            'publishbox' => esc_html__('Update Actions', 'event_espresso'),
377
-        ];
378
-    }
379
-
380
-
381
-    /**
382
-     *        an array for storing key => value pairs of request actions and their corresponding methods
383
-     *
384
-     * @access protected
385
-     * @return void
386
-     */
387
-    protected function _set_page_routes()
388
-    {
389
-        $GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
390
-        $GRP_ID = $this->request->getRequestParam('id', $GRP_ID, 'int');
391
-        $MSG_ID = $this->request->getRequestParam('MSG_ID', 0, 'int');
392
-
393
-        $this->_page_routes = [
394
-            'default'                          => [
395
-                'func'       => '_message_queue_list_table',
396
-                'capability' => 'ee_read_global_messages',
397
-            ],
398
-            'global_mtps'                      => [
399
-                'func'       => '_ee_default_messages_overview_list_table',
400
-                'capability' => 'ee_read_global_messages',
401
-            ],
402
-            'custom_mtps'                      => [
403
-                'func'       => '_custom_mtps_preview',
404
-                'capability' => 'ee_read_messages',
405
-            ],
406
-            'add_new_message_template'         => [
407
-                'func'       => '_add_message_template',
408
-                'capability' => 'ee_edit_messages',
409
-                'noheader'   => true,
410
-            ],
411
-            'edit_message_template'            => [
412
-                'func'       => '_edit_message_template',
413
-                'capability' => 'ee_edit_message',
414
-                'obj_id'     => $GRP_ID,
415
-            ],
416
-            'preview_message'                  => [
417
-                'func'               => '_preview_message',
418
-                'capability'         => 'ee_read_message',
419
-                'obj_id'             => $GRP_ID,
420
-                'noheader'           => true,
421
-                'headers_sent_route' => 'display_preview_message',
422
-            ],
423
-            'display_preview_message'          => [
424
-                'func'       => '_display_preview_message',
425
-                'capability' => 'ee_read_message',
426
-                'obj_id'     => $GRP_ID,
427
-            ],
428
-            'insert_message_template'          => [
429
-                'func'       => '_insert_or_update_message_template',
430
-                'capability' => 'ee_edit_messages',
431
-                'args'       => ['new' => true],
432
-                'noheader'   => true,
433
-            ],
434
-            'update_message_template'          => [
435
-                'func'       => '_insert_or_update_message_template',
436
-                'capability' => 'ee_edit_message',
437
-                'obj_id'     => $GRP_ID,
438
-                'args'       => ['new' => false],
439
-                'noheader'   => true,
440
-            ],
441
-            'trash_message_template'           => [
442
-                'func'       => '_trash_or_restore_message_template',
443
-                'capability' => 'ee_delete_message',
444
-                'obj_id'     => $GRP_ID,
445
-                'args'       => ['trash' => true, 'all' => true],
446
-                'noheader'   => true,
447
-            ],
448
-            'trash_message_template_context'   => [
449
-                'func'       => '_trash_or_restore_message_template',
450
-                'capability' => 'ee_delete_message',
451
-                'obj_id'     => $GRP_ID,
452
-                'args'       => ['trash' => true],
453
-                'noheader'   => true,
454
-            ],
455
-            'restore_message_template'         => [
456
-                'func'       => '_trash_or_restore_message_template',
457
-                'capability' => 'ee_delete_message',
458
-                'obj_id'     => $GRP_ID,
459
-                'args'       => ['trash' => false, 'all' => true],
460
-                'noheader'   => true,
461
-            ],
462
-            'restore_message_template_context' => [
463
-                'func'       => '_trash_or_restore_message_template',
464
-                'capability' => 'ee_delete_message',
465
-                'obj_id'     => $GRP_ID,
466
-                'args'       => ['trash' => false],
467
-                'noheader'   => true,
468
-            ],
469
-            'delete_message_template'          => [
470
-                'func'       => '_delete_message_template',
471
-                'capability' => 'ee_delete_message',
472
-                'obj_id'     => $GRP_ID,
473
-                'noheader'   => true,
474
-            ],
475
-            'reset_to_default'                 => [
476
-                'func'       => '_reset_to_default_template',
477
-                'capability' => 'ee_edit_message',
478
-                'obj_id'     => $GRP_ID,
479
-                'noheader'   => true,
480
-            ],
481
-            'settings'                         => [
482
-                'func'       => '_settings',
483
-                'capability' => 'manage_options',
484
-            ],
485
-            'update_global_settings'           => [
486
-                'func'       => '_update_global_settings',
487
-                'capability' => 'manage_options',
488
-                'noheader'   => true,
489
-            ],
490
-            'generate_now'                     => [
491
-                'func'       => '_generate_now',
492
-                'capability' => 'ee_send_message',
493
-                'noheader'   => true,
494
-            ],
495
-            'generate_and_send_now'            => [
496
-                'func'       => '_generate_and_send_now',
497
-                'capability' => 'ee_send_message',
498
-                'noheader'   => true,
499
-            ],
500
-            'queue_for_resending'              => [
501
-                'func'       => '_queue_for_resending',
502
-                'capability' => 'ee_send_message',
503
-                'noheader'   => true,
504
-            ],
505
-            'send_now'                         => [
506
-                'func'       => '_send_now',
507
-                'capability' => 'ee_send_message',
508
-                'noheader'   => true,
509
-            ],
510
-            'delete_ee_message'                => [
511
-                'func'       => '_delete_ee_messages',
512
-                'capability' => 'ee_delete_messages',
513
-                'noheader'   => true,
514
-            ],
515
-            'delete_ee_messages'               => [
516
-                'func'       => '_delete_ee_messages',
517
-                'capability' => 'ee_delete_messages',
518
-                'noheader'   => true,
519
-                'obj_id'     => $MSG_ID,
520
-            ],
521
-        ];
522
-    }
523
-
524
-
525
-    protected function _set_page_config()
526
-    {
527
-        $this->_page_config = [
528
-            'default'                  => [
529
-                'nav'           => [
530
-                    'label' => esc_html__('Message Activity', 'event_espresso'),
531
-                    'order' => 10,
532
-                ],
533
-                'list_table'    => 'EE_Message_List_Table',
534
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
535
-                'require_nonce' => false,
536
-            ],
537
-            'global_mtps'              => [
538
-                'nav'           => [
539
-                    'label' => esc_html__('Default Message Templates', 'event_espresso'),
540
-                    'order' => 20,
541
-                ],
542
-                'list_table'    => 'Messages_Template_List_Table',
543
-                'help_tabs'     => [
544
-                    'messages_overview_help_tab'                                => [
545
-                        'title'    => esc_html__('Messages Overview', 'event_espresso'),
546
-                        'filename' => 'messages_overview',
547
-                    ],
548
-                    'messages_overview_messages_table_column_headings_help_tab' => [
549
-                        'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
550
-                        'filename' => 'messages_overview_table_column_headings',
551
-                    ],
552
-                    'messages_overview_messages_filters_help_tab'               => [
553
-                        'title'    => esc_html__('Message Filters', 'event_espresso'),
554
-                        'filename' => 'messages_overview_filters',
555
-                    ],
556
-                    'messages_overview_messages_views_help_tab'                 => [
557
-                        'title'    => esc_html__('Message Views', 'event_espresso'),
558
-                        'filename' => 'messages_overview_views',
559
-                    ],
560
-                    'message_overview_message_types_help_tab'                   => [
561
-                        'title'    => esc_html__('Message Types', 'event_espresso'),
562
-                        'filename' => 'messages_overview_types',
563
-                    ],
564
-                    'messages_overview_messengers_help_tab'                     => [
565
-                        'title'    => esc_html__('Messengers', 'event_espresso'),
566
-                        'filename' => 'messages_overview_messengers',
567
-                    ],
568
-                ],
569
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
570
-                // 'help_tour'     => array('Messages_Overview_Help_Tour'),
571
-                'require_nonce' => false,
572
-            ],
573
-            'custom_mtps'              => [
574
-                'nav'           => [
575
-                    'label' => esc_html__('Custom Message Templates', 'event_espresso'),
576
-                    'order' => 30,
577
-                ],
578
-                'help_tabs'     => [],
579
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
580
-                // 'help_tour'     => array(),
581
-                'require_nonce' => false,
582
-            ],
583
-            'add_new_message_template' => [
584
-                'nav'           => [
585
-                    'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
586
-                    'order'      => 5,
587
-                    'persistent' => false,
588
-                ],
589
-                'require_nonce' => false,
590
-            ],
591
-            'edit_message_template'    => [
592
-                'labels'        => [
593
-                    'buttons'    => [
594
-                        'reset' => esc_html__('Reset Templates', 'event_espresso'),
595
-                    ],
596
-                    'publishbox' => esc_html__('Update Actions', 'event_espresso'),
597
-                ],
598
-                'nav'           => [
599
-                    'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
600
-                    'order'      => 5,
601
-                    'persistent' => false,
602
-                    'url'        => '',
603
-                ],
604
-                'metaboxes'     => ['_publish_post_box', '_register_edit_meta_boxes'],
605
-                'has_metaboxes' => true,
606
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
607
-                // 'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
608
-                'help_tabs'     => [
609
-                    'edit_message_template'            => [
610
-                        'title'    => esc_html__('Message Template Editor', 'event_espresso'),
611
-                        'callback' => 'edit_message_template_help_tab',
612
-                    ],
613
-                    'message_templates_help_tab'       => [
614
-                        'title'    => esc_html__('Message Templates', 'event_espresso'),
615
-                        'filename' => 'messages_templates',
616
-                    ],
617
-                    'message_template_shortcodes'      => [
618
-                        'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
619
-                        'callback' => 'message_template_shortcodes_help_tab',
620
-                    ],
621
-                    'message_preview_help_tab'         => [
622
-                        'title'    => esc_html__('Message Preview', 'event_espresso'),
623
-                        'filename' => 'messages_preview',
624
-                    ],
625
-                    'messages_overview_other_help_tab' => [
626
-                        'title'    => esc_html__('Messages Other', 'event_espresso'),
627
-                        'filename' => 'messages_overview_other',
628
-                    ],
629
-                ],
630
-                'require_nonce' => false,
631
-            ],
632
-            'display_preview_message'  => [
633
-                'nav'           => [
634
-                    'label'      => esc_html__('Message Preview', 'event_espresso'),
635
-                    'order'      => 5,
636
-                    'url'        => '',
637
-                    'persistent' => false,
638
-                ],
639
-                'help_tabs'     => [
640
-                    'preview_message' => [
641
-                        'title'    => esc_html__('About Previews', 'event_espresso'),
642
-                        'callback' => 'preview_message_help_tab',
643
-                    ],
644
-                ],
645
-                'require_nonce' => false,
646
-            ],
647
-            'settings'                 => [
648
-                'nav'           => [
649
-                    'label' => esc_html__('Settings', 'event_espresso'),
650
-                    'order' => 40,
651
-                ],
652
-                'metaboxes'     => ['_messages_settings_metaboxes'],
653
-                'help_tabs'     => [
654
-                    'messages_settings_help_tab'               => [
655
-                        'title'    => esc_html__('Messages Settings', 'event_espresso'),
656
-                        'filename' => 'messages_settings',
657
-                    ],
658
-                    'messages_settings_message_types_help_tab' => [
659
-                        'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
660
-                        'filename' => 'messages_settings_message_types',
661
-                    ],
662
-                    'messages_settings_messengers_help_tab'    => [
663
-                        'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
664
-                        'filename' => 'messages_settings_messengers',
665
-                    ],
666
-                ],
667
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
668
-                // 'help_tour'     => array('Messages_Settings_Help_Tour'),
669
-                'require_nonce' => false,
670
-            ],
671
-        ];
672
-    }
673
-
674
-
675
-    protected function _add_screen_options()
676
-    {
677
-        // todo
678
-    }
679
-
680
-
681
-    protected function _add_screen_options_global_mtps()
682
-    {
683
-        /**
684
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
685
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
686
-         */
687
-        $page_title              = $this->_admin_page_title;
688
-        $this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
689
-        $this->_per_page_screen_option();
690
-        $this->_admin_page_title = $page_title;
691
-    }
692
-
693
-
694
-    protected function _add_screen_options_default()
695
-    {
696
-        $this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
697
-        $this->_per_page_screen_option();
698
-    }
699
-
700
-
701
-    // none of the below group are currently used for Messages
702
-    protected function _add_feature_pointers()
703
-    {
704
-    }
705
-
706
-
707
-    public function admin_init()
708
-    {
709
-    }
710
-
711
-
712
-    public function admin_notices()
713
-    {
714
-    }
715
-
716
-
717
-    public function admin_footer_scripts()
718
-    {
719
-    }
720
-
721
-
722
-    public function messages_help_tab()
723
-    {
724
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
725
-    }
726
-
727
-
728
-    public function messengers_help_tab()
729
-    {
730
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
731
-    }
732
-
733
-
734
-    public function message_types_help_tab()
735
-    {
736
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
737
-    }
738
-
739
-
740
-    public function messages_overview_help_tab()
741
-    {
742
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
743
-    }
744
-
745
-
746
-    public function message_templates_help_tab()
747
-    {
748
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
749
-    }
750
-
751
-
752
-    public function edit_message_template_help_tab()
753
-    {
754
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
755
-                        . esc_attr__('Editor Title', 'event_espresso')
756
-                        . '" />';
757
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
758
-                        . esc_attr__('Context Switcher and Preview', 'event_espresso')
759
-                        . '" />';
760
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
761
-                        . esc_attr__('Message Template Form Fields', 'event_espresso')
762
-                        . '" />';
763
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
764
-                        . esc_attr__('Shortcodes Metabox', 'event_espresso')
765
-                        . '" />';
766
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
767
-                        . esc_attr__('Publish Metabox', 'event_espresso')
768
-                        . '" />';
769
-        EEH_Template::display_template(
770
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
771
-            $args
772
-        );
773
-    }
774
-
775
-
776
-    /**
777
-     * @throws ReflectionException
778
-     * @throws EE_Error
779
-     */
780
-    public function message_template_shortcodes_help_tab()
781
-    {
782
-        $this->_set_shortcodes();
783
-        $args['shortcodes'] = $this->_shortcodes;
784
-        EEH_Template::display_template(
785
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
786
-            $args
787
-        );
788
-    }
789
-
790
-
791
-    public function preview_message_help_tab()
792
-    {
793
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
794
-    }
795
-
796
-
797
-    public function settings_help_tab()
798
-    {
799
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
800
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
801
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
802
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
803
-        $args['img3'] = '<div class="switch">'
804
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
805
-                        . ' type="checkbox" checked="checked">'
806
-                        . '<label for="ee-on-off-toggle-on"></label>'
807
-                        . '</div>';
808
-        $args['img4'] = '<div class="switch">'
809
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
810
-                        . ' type="checkbox">'
811
-                        . '<label for="ee-on-off-toggle-on"></label>'
812
-                        . '</div>';
813
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
814
-    }
815
-
816
-
817
-    public function load_scripts_styles()
818
-    {
819
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
820
-        wp_enqueue_style('espresso_ee_msg');
821
-
822
-        wp_register_script(
823
-            'ee-messages-settings',
824
-            EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
825
-            ['jquery-ui-droppable', 'ee-serialize-full-array'],
826
-            EVENT_ESPRESSO_VERSION,
827
-            true
828
-        );
829
-        wp_register_script(
830
-            'ee-msg-list-table-js',
831
-            EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
832
-            ['ee-dialog'],
833
-            EVENT_ESPRESSO_VERSION
834
-        );
835
-    }
836
-
837
-
838
-    public function load_scripts_styles_default()
839
-    {
840
-        wp_enqueue_script('ee-msg-list-table-js');
841
-    }
842
-
843
-
844
-    public function wp_editor_css($mce_css)
845
-    {
846
-        // if we're on the edit_message_template route
847
-        if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
848
-            $message_type_name = $this->_active_message_type_name;
849
-
850
-            // we're going to REPLACE the existing mce css
851
-            // we need to get the css file location from the active messenger
852
-            $mce_css = $this->_active_messenger->get_variation(
853
-                $this->_template_pack,
854
-                $message_type_name,
855
-                true,
856
-                'wpeditor',
857
-                $this->_variation
858
-            );
859
-        }
860
-
861
-        return $mce_css;
862
-    }
863
-
864
-
865
-    /**
866
-     * @throws EE_Error
867
-     * @throws ReflectionException
868
-     */
869
-    public function load_scripts_styles_edit_message_template()
870
-    {
871
-
872
-        $this->_set_shortcodes();
873
-
874
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
875
-            esc_html__(
876
-                'Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
877
-                'event_espresso'
878
-            ),
879
-            $this->_message_template_group->messenger_obj()->label['singular'],
880
-            $this->_message_template_group->message_type_obj()->label['singular']
881
-        );
882
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
883
-            'Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
884
-            'event_espresso'
885
-        );
886
-        EE_Registry::$i18n_js_strings['server_error']                 = esc_html__(
887
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
888
-            'event_espresso'
889
-        );
890
-
891
-        wp_register_script(
892
-            'ee_msgs_edit_js',
893
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
894
-            ['jquery'],
895
-            EVENT_ESPRESSO_VERSION
896
-        );
897
-
898
-        wp_enqueue_script('ee_admin_js');
899
-        wp_enqueue_script('ee_msgs_edit_js');
900
-
901
-        // add in special css for tiny_mce
902
-        add_filter('mce_css', [$this, 'wp_editor_css']);
903
-    }
904
-
905
-
906
-    /**
907
-     * @throws EE_Error
908
-     * @throws ReflectionException
909
-     */
910
-    public function load_scripts_styles_display_preview_message()
911
-    {
912
-        $this->_set_message_template_group();
913
-        if ($this->_active_messenger_name) {
914
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
915
-                $this->_active_messenger_name
916
-            );
917
-        }
918
-
919
-        wp_enqueue_style(
920
-            'espresso_preview_css',
921
-            $this->_active_messenger->get_variation(
922
-                $this->_template_pack,
923
-                $this->_active_message_type_name,
924
-                true,
925
-                'preview',
926
-                $this->_variation
927
-            )
928
-        );
929
-    }
930
-
931
-
932
-    public function load_scripts_styles_settings()
933
-    {
934
-        wp_register_style(
935
-            'ee-message-settings',
936
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
937
-            [],
938
-            EVENT_ESPRESSO_VERSION
939
-        );
940
-        wp_enqueue_style('ee-text-links');
941
-        wp_enqueue_style('ee-message-settings');
942
-        wp_enqueue_script('ee-messages-settings');
943
-    }
944
-
945
-
946
-    /**
947
-     * set views array for List Table
948
-     */
949
-    public function _set_list_table_views_global_mtps()
950
-    {
951
-        $this->_views = [
952
-            'in_use' => [
953
-                'slug'  => 'in_use',
954
-                'label' => esc_html__('In Use', 'event_espresso'),
955
-                'count' => 0,
956
-            ],
957
-        ];
958
-    }
959
-
960
-
961
-    /**
962
-     * Set views array for the Custom Template List Table
963
-     */
964
-    public function _set_list_table_views_custom_mtps()
965
-    {
966
-        $this->_set_list_table_views_global_mtps();
967
-        $this->_views['in_use']['bulk_action'] = [
968
-            'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
969
-        ];
970
-    }
971
-
972
-
973
-    /**
974
-     * set views array for message queue list table
975
-     *
976
-     * @throws InvalidDataTypeException
977
-     * @throws InvalidInterfaceException
978
-     * @throws InvalidArgumentException
979
-     * @throws EE_Error
980
-     * @throws ReflectionException
981
-     */
982
-    public function _set_list_table_views_default()
983
-    {
984
-        EE_Registry::instance()->load_helper('Template');
985
-
986
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
987
-            'ee_send_message',
988
-            'message_list_table_bulk_actions'
989
-        )
990
-            ? [
991
-                'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
992
-                'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
993
-                'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
994
-                'send_now'              => esc_html__('Send Now', 'event_espresso'),
995
-            ]
996
-            : [];
997
-
998
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
999
-            'ee_delete_messages',
1000
-            'message_list_table_bulk_actions'
1001
-        )
1002
-            ? ['delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso')]
1003
-            : [];
1004
-
1005
-
1006
-        $this->_views = [
1007
-            'all' => [
1008
-                'slug'        => 'all',
1009
-                'label'       => esc_html__('All', 'event_espresso'),
1010
-                'count'       => 0,
1011
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
1012
-            ],
1013
-        ];
1014
-
1015
-
1016
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
1017
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
1018
-                continue;
1019
-            }
1020
-            $status_bulk_actions = $common_bulk_actions;
1021
-            // unset bulk actions not applying to status
1022
-            if (! empty($status_bulk_actions)) {
1023
-                switch ($status) {
1024
-                    case EEM_Message::status_idle:
1025
-                    case EEM_Message::status_resend:
1026
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1027
-                        break;
1028
-
1029
-                    case EEM_Message::status_failed:
1030
-                    case EEM_Message::status_debug_only:
1031
-                    case EEM_Message::status_messenger_executing:
1032
-                        $status_bulk_actions = [];
1033
-                        break;
1034
-
1035
-                    case EEM_Message::status_incomplete:
1036
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1037
-                        break;
1038
-
1039
-                    case EEM_Message::status_retry:
1040
-                    case EEM_Message::status_sent:
1041
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1042
-                        break;
1043
-                }
1044
-            }
1045
-
1046
-            // skip adding messenger executing status to views because it will be included with the Failed view.
1047
-            if ($status === EEM_Message::status_messenger_executing) {
1048
-                continue;
1049
-            }
1050
-
1051
-            $this->_views[ strtolower($status) ] = [
1052
-                'slug'        => strtolower($status),
1053
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1054
-                'count'       => 0,
1055
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1056
-            ];
1057
-        }
1058
-    }
1059
-
1060
-
1061
-    /**
1062
-     * @throws EE_Error
1063
-     */
1064
-    protected function _ee_default_messages_overview_list_table()
1065
-    {
1066
-        $this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1067
-        $this->display_admin_list_table_page_with_no_sidebar();
1068
-    }
1069
-
1070
-
1071
-    /**
1072
-     * @throws EE_Error
1073
-     * @throws ReflectionException
1074
-     */
1075
-    protected function _message_queue_list_table()
1076
-    {
1077
-        $this->_search_btn_label                   = esc_html__('Message Activity', 'event_espresso');
1078
-        $this->_template_args['per_column']        = 6;
1079
-        $this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
1080
-        $this->_template_args['before_list_table'] = '<h3>'
1081
-                                                     . EEM_Message::instance()->get_pretty_label_for_results()
1082
-                                                     . '</h3>';
1083
-        $this->display_admin_list_table_page_with_no_sidebar();
1084
-    }
1085
-
1086
-
1087
-    /**
1088
-     * @throws EE_Error
1089
-     */
1090
-    protected function _message_legend_items()
1091
-    {
1092
-
1093
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
1094
-        $action_items       = [];
1095
-
1096
-        foreach ($action_css_classes as $action_item => $action_details) {
1097
-            if ($action_item === 'see_notifications_for') {
1098
-                continue;
1099
-            }
1100
-            $action_items[ $action_item ] = [
1101
-                'class' => $action_details['css_class'],
1102
-                'desc'  => $action_details['label'],
1103
-            ];
1104
-        }
1105
-
1106
-        /** @var array $status_items status legend setup */
1107
-        $status_items = [
1108
-            'sent_status'                => [
1109
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1110
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1111
-            ],
1112
-            'idle_status'                => [
1113
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1114
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1115
-            ],
1116
-            'failed_status'              => [
1117
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1118
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1119
-            ],
1120
-            'messenger_executing_status' => [
1121
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1122
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1123
-            ],
1124
-            'resend_status'              => [
1125
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1126
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1127
-            ],
1128
-            'incomplete_status'          => [
1129
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1130
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1131
-            ],
1132
-            'retry_status'               => [
1133
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1134
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1135
-            ],
1136
-        ];
1137
-        if (EEM_Message::debug()) {
1138
-            $status_items['debug_only_status'] = [
1139
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1140
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1141
-            ];
1142
-        }
1143
-
1144
-        return array_merge($action_items, $status_items);
1145
-    }
1146
-
1147
-
1148
-    /**
1149
-     * @throws EE_Error
1150
-     */
1151
-    protected function _custom_mtps_preview()
1152
-    {
1153
-        $this->_admin_page_title              = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1154
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1155
-                                                . ' alt="' . esc_attr__(
1156
-                                                    'Preview Custom Message Templates screenshot',
1157
-                                                    'event_espresso'
1158
-                                                ) . '" />';
1159
-        $this->_template_args['preview_text'] = '<strong>'
1160
-                                                . esc_html__(
1161
-                                                    'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1162
-                                                    'event_espresso'
1163
-                                                )
1164
-                                                . '</strong>';
1165
-
1166
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1167
-    }
1168
-
1169
-
1170
-    /**
1171
-     * get_message_templates
1172
-     * This gets all the message templates for listing on the overview list.
1173
-     *
1174
-     * @access public
1175
-     * @param int    $per_page the amount of templates groups to show per page
1176
-     * @param string $type     the current _view we're getting templates for
1177
-     * @param bool   $count    return count?
1178
-     * @param bool   $all      disregard any paging info (get all data);
1179
-     * @param bool   $global   whether to return just global (true) or custom templates (false)
1180
-     * @return array
1181
-     * @throws EE_Error
1182
-     * @throws InvalidArgumentException
1183
-     * @throws InvalidDataTypeException
1184
-     * @throws InvalidInterfaceException
1185
-     */
1186
-    public function get_message_templates(
1187
-        $per_page = 10,
1188
-        $type = 'in_use',
1189
-        $count = false,
1190
-        $all = false,
1191
-        $global = true
1192
-    ) {
1193
-
1194
-        $MTP = EEM_Message_Template_Group::instance();
1195
-
1196
-        $orderby = $this->request->getRequestParam('orderby', 'GRP_ID');
1197
-        $this->request->setRequestParam('orderby', $orderby);
1198
-
1199
-        $order        = $this->request->getRequestParam('order', 'ASC');
1200
-        $current_page = $this->request->getRequestParam('paged', 1, 'int');
1201
-        $per_page     = $this->request->getRequestParam('perpage', $per_page, 'int');
1202
-
1203
-        $offset = ($current_page - 1) * $per_page;
1204
-        $limit  = $all ? null : [$offset, $per_page];
1205
-
1206
-        // options will match what is in the _views array property
1207
-        switch ($type) {
1208
-            case 'in_use':
1209
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1210
-                break;
1211
-            default:
1212
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1213
-        }
1214
-
1215
-        return $templates;
1216
-    }
1217
-
1218
-
1219
-    /**
1220
-     * filters etc might need a list of installed message_types
1221
-     *
1222
-     * @return array an array of message type objects
1223
-     */
1224
-    public function get_installed_message_types()
1225
-    {
1226
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1227
-        $installed               = [];
1228
-
1229
-        foreach ($installed_message_types as $message_type) {
1230
-            $installed[ $message_type->name ] = $message_type;
1231
-        }
1232
-
1233
-        return $installed;
1234
-    }
1235
-
1236
-
1237
-    /**
1238
-     * _add_message_template
1239
-     *
1240
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1241
-     *
1242
-     * @param string $message_type
1243
-     * @param string $messenger
1244
-     * @param string $GRP_ID
1245
-     *
1246
-     * @throws EE_error
1247
-     * @throws ReflectionException
1248
-     */
1249
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1250
-    {
1251
-        // set values override any request data
1252
-        $message_type = ! empty($message_type) ? $message_type : $this->_active_message_type_name;
1253
-        $messenger    = ! empty($messenger) ? $messenger : $this->_active_messenger_name;
1254
-        $GRP_ID       = ! empty($GRP_ID) ? $GRP_ID : $this->request->getRequestParam('GRP_ID', 0, 'int');
1255
-
1256
-        // we need messenger and message type.  They should be coming from the event editor. If not here then return error
1257
-        if (empty($message_type) || empty($messenger)) {
1258
-            throw new EE_Error(
1259
-                esc_html__(
1260
-                    'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1261
-                    'event_espresso'
1262
-                )
1263
-            );
1264
-        }
1265
-
1266
-        // we need the GRP_ID for the template being used as the base for the new template
1267
-        if (empty($GRP_ID)) {
1268
-            throw new EE_Error(
1269
-                esc_html__(
1270
-                    'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1271
-                    'event_espresso'
1272
-                )
1273
-            );
1274
-        }
1275
-
1276
-        // let's just make sure the template gets generated!
1277
-
1278
-        // we need to reassign some variables for what the insert is expecting
1279
-        $this->request->setRequestParam('MTP_messenger', $messenger);
1280
-        $this->request->setRequestParam('MTP_message_type', $message_type);
1281
-        $this->request->setRequestParam('GRP_ID', $GRP_ID);
1282
-
1283
-        $this->_insert_or_update_message_template(true);
1284
-    }
1285
-
1286
-
1287
-    /**
1288
-     * public wrapper for the _add_message_template method
1289
-     *
1290
-     * @param string $message_type     message type slug
1291
-     * @param string $messenger        messenger slug
1292
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1293
-     *                                 off of.
1294
-     * @throws EE_error
1295
-     * @throws ReflectionException
1296
-     */
1297
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1298
-    {
1299
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1300
-    }
1301
-
1302
-
1303
-    /**
1304
-     * _edit_message_template
1305
-     *
1306
-     * @access protected
1307
-     * @return void
1308
-     * @throws InvalidIdentifierException
1309
-     * @throws DomainException
1310
-     * @throws EE_Error
1311
-     * @throws InvalidArgumentException
1312
-     * @throws ReflectionException
1313
-     * @throws InvalidDataTypeException
1314
-     * @throws InvalidInterfaceException
1315
-     */
1316
-    protected function _edit_message_template()
1317
-    {
1318
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1319
-        $template_fields = '';
1320
-        $sidebar_fields  = '';
1321
-        // we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1322
-        // valid html in the templates.
1323
-        add_filter('tiny_mce_before_init', [$this, 'filter_tinymce_init'], 10, 2);
1324
-
1325
-        $GRP_ID = $this->request->getRequestParam('id', 0, 'int');
1326
-        $EVT_ID = $this->request->getRequestParam('evt_id', 0, 'int');
1327
-
1328
-        $this->_set_shortcodes(); // this also sets the _message_template property.
1329
-        $message_template_group = $this->_message_template_group;
1330
-        $c_label                = $message_template_group->context_label();
1331
-        $c_config               = $message_template_group->contexts_config();
1332
-
1333
-        reset($c_config);
1334
-        $context = $this->request->getRequestParam('context', key($c_config));
1335
-        $context = strtolower($context);
1336
-
1337
-        $action = empty($GRP_ID) ? 'insert_message_template' : 'update_message_template';
1338
-
1339
-        $edit_message_template_form_url = add_query_arg(
1340
-            ['action' => $action, 'noheader' => true],
1341
-            EE_MSG_ADMIN_URL
1342
-        );
1343
-
1344
-        // set active messenger for this view
1345
-        $this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1346
-            $message_template_group->messenger()
1347
-        );
1348
-        $this->_active_message_type_name = $message_template_group->message_type();
1349
-
1350
-
1351
-        // Do we have any validation errors?
1352
-        $validators = $this->_get_transient();
1353
-        $v_fields   = ! empty($validators) ? array_keys($validators) : [];
1354
-
1355
-
1356
-        // we need to assemble the title from Various details
1357
-        $context_label = sprintf(
1358
-            esc_html__('(%s %s)', 'event_espresso'),
1359
-            $c_config[ $context ]['label'],
1360
-            ucwords($c_label['label'])
1361
-        );
1362
-
1363
-        $title = sprintf(
1364
-            esc_html__(' %s %s Template %s', 'event_espresso'),
1365
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1366
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1367
-            $context_label
1368
-        );
1369
-
1370
-        $this->_template_args['GRP_ID']           = $GRP_ID;
1371
-        $this->_template_args['message_template'] = $message_template_group;
1372
-        $this->_template_args['is_extra_fields']  = false;
1373
-
1374
-
1375
-        // let's get EEH_MSG_Template so we can get template form fields
1376
-        $template_field_structure = EEH_MSG_Template::get_fields(
1377
-            $message_template_group->messenger(),
1378
-            $message_template_group->message_type()
1379
-        );
1380
-
1381
-        if (! $template_field_structure) {
1382
-            $template_field_structure = false;
1383
-            $template_fields          = esc_html__(
1384
-                'There was an error in assembling the fields for this display (you should see an error message)',
1385
-                'event_espresso'
1386
-            );
1387
-        }
1388
-
1389
-
1390
-        $message_templates = $message_template_group->context_templates();
1391
-
1392
-
1393
-        // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1394
-        // will get handled in the "extra" array.
1395
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1396
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1397
-                unset($template_field_structure[ $context ][ $reference_field ]);
1398
-            }
1399
-        }
1400
-
1401
-        // let's loop through the template_field_structure and actually assemble the input fields!
1402
-        if (! empty($template_field_structure)) {
1403
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1404
-                // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1405
-                // the extra array and reset them.
1406
-                if ($template_field === 'extra') {
1407
-                    $this->_template_args['is_extra_fields'] = true;
1408
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1409
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1410
-                        $content          = $message_template instanceof EE_Message_Template
1411
-                            ? $message_template->get('MTP_content')
1412
-                            : '';
1413
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1414
-                            // let's verify if we need this extra field via the shortcodes parameter.
1415
-                            $continue = false;
1416
-                            if (isset($extra_array['shortcodes_required'])) {
1417
-                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1418
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1419
-                                        $continue = true;
1420
-                                    }
1421
-                                }
1422
-                                if ($continue) {
1423
-                                    continue;
1424
-                                }
1425
-                            }
1426
-
1427
-                            $field_id                                  = $reference_field
1428
-                                                                         . '-'
1429
-                                                                         . $extra_field
1430
-                                                                         . '-content';
1431
-                            $template_form_fields[ $field_id ]         = $extra_array;
1432
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1433
-                                                                         . $reference_field
1434
-                                                                         . '][content]['
1435
-                                                                         . $extra_field . ']';
1436
-                            $css_class                                 = isset($extra_array['css_class'])
1437
-                                ? $extra_array['css_class']
1438
-                                : '';
1439
-
1440
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1441
-                                                                              && in_array($extra_field, $v_fields, true)
1442
-                                                                              && (
1443
-                                                                                  is_array($validators[ $extra_field ])
1444
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1445
-                                                                              )
1446
-                                ? 'validate-error ' . $css_class
1447
-                                : $css_class;
1448
-
1449
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1450
-                                                                          && isset($content[ $extra_field ])
1451
-                                ? $content[ $extra_field ]
1452
-                                : '';
1453
-
1454
-                            // do we have a validation error?  if we do then let's use that value instead
1455
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1456
-                                ? $validators[ $extra_field ]['value']
1457
-                                : $template_form_fields[ $field_id ]['value'];
1458
-
1459
-
1460
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1461
-
1462
-                            // shortcode selector
1463
-                            $field_name_to_use                                   = $extra_field === 'main'
1464
-                                ? 'content'
1465
-                                : $extra_field;
1466
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1467
-                                $field_name_to_use,
1468
-                                $field_id
1469
-                            );
1470
-                        }
1471
-                        $template_field_MTP_id           = $reference_field . '-MTP_ID';
1472
-                        $template_field_template_name_id = $reference_field . '-name';
1473
-
1474
-                        $template_form_fields[ $template_field_MTP_id ] = [
1475
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1476
-                            'label'      => null,
1477
-                            'input'      => 'hidden',
1478
-                            'type'       => 'int',
1479
-                            'required'   => false,
1480
-                            'validation' => false,
1481
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1482
-                            'css_class'  => '',
1483
-                            'format'     => '%d',
1484
-                            'db-col'     => 'MTP_ID',
1485
-                        ];
1486
-
1487
-                        $template_form_fields[ $template_field_template_name_id ] = [
1488
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1489
-                            'label'      => null,
1490
-                            'input'      => 'hidden',
1491
-                            'type'       => 'string',
1492
-                            'required'   => false,
1493
-                            'validation' => true,
1494
-                            'value'      => $reference_field,
1495
-                            'css_class'  => '',
1496
-                            'format'     => '%s',
1497
-                            'db-col'     => 'MTP_template_field',
1498
-                        ];
1499
-                    }
1500
-                    continue; // skip the next stuff, we got the necessary fields here for this dataset.
1501
-                } else {
1502
-                    $field_id                                   = $template_field . '-content';
1503
-                    $template_form_fields[ $field_id ]          = $field_setup_array;
1504
-                    $template_form_fields[ $field_id ]['name']  =
1505
-                        'MTP_template_fields[' . $template_field . '][content]';
1506
-                    $message_template                           =
1507
-                        isset($message_templates[ $context ][ $template_field ])
1508
-                            ? $message_templates[ $context ][ $template_field ]
1509
-                            : null;
1510
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1511
-                                                                  && is_array($message_templates[ $context ])
1512
-                                                                  && $message_template instanceof EE_Message_Template
1513
-                        ? $message_template->get('MTP_content')
1514
-                        : '';
1515
-
1516
-                    // do we have a validator error for this field?  if we do then we'll use that value instead
1517
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1518
-                        ? $validators[ $template_field ]['value']
1519
-                        : $template_form_fields[ $field_id ]['value'];
1520
-
1521
-
1522
-                    $template_form_fields[ $field_id ]['db-col']    = 'MTP_content';
1523
-                    $css_class                                      = isset($field_setup_array['css_class'])
1524
-                        ? $field_setup_array['css_class']
1525
-                        : '';
1526
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1527
-                                                                      && in_array($template_field, $v_fields, true)
1528
-                                                                      && isset($validators[ $template_field ]['msg'])
1529
-                        ? 'validate-error ' . $css_class
1530
-                        : $css_class;
1531
-
1532
-                    // shortcode selector
1533
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1534
-                        $template_field,
1535
-                        $field_id
1536
-                    );
1537
-                }
1538
-
1539
-                // k took care of content field(s) now let's take care of others.
1540
-
1541
-                $template_field_MTP_id                 = $template_field . '-MTP_ID';
1542
-                $template_field_field_template_name_id = $template_field . '-name';
1543
-
1544
-                // foreach template field there are actually two form fields created
1545
-                $template_form_fields[ $template_field_MTP_id ] = [
1546
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1547
-                    'label'      => null,
1548
-                    'input'      => 'hidden',
1549
-                    'type'       => 'int',
1550
-                    'required'   => false,
1551
-                    'validation' => true,
1552
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1553
-                    'css_class'  => '',
1554
-                    'format'     => '%d',
1555
-                    'db-col'     => 'MTP_ID',
1556
-                ];
1557
-
1558
-                $template_form_fields[ $template_field_field_template_name_id ] = [
1559
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1560
-                    'label'      => null,
1561
-                    'input'      => 'hidden',
1562
-                    'type'       => 'string',
1563
-                    'required'   => false,
1564
-                    'validation' => true,
1565
-                    'value'      => $template_field,
1566
-                    'css_class'  => '',
1567
-                    'format'     => '%s',
1568
-                    'db-col'     => 'MTP_template_field',
1569
-                ];
1570
-            }
1571
-
1572
-            // add other fields
1573
-            $template_form_fields['ee-msg-current-context'] = [
1574
-                'name'       => 'MTP_context',
1575
-                'label'      => null,
1576
-                'input'      => 'hidden',
1577
-                'type'       => 'string',
1578
-                'required'   => false,
1579
-                'validation' => true,
1580
-                'value'      => $context,
1581
-                'css_class'  => '',
1582
-                'format'     => '%s',
1583
-                'db-col'     => 'MTP_context',
1584
-            ];
1585
-
1586
-            $template_form_fields['ee-msg-grp-id'] = [
1587
-                'name'       => 'GRP_ID',
1588
-                'label'      => null,
1589
-                'input'      => 'hidden',
1590
-                'type'       => 'int',
1591
-                'required'   => false,
1592
-                'validation' => true,
1593
-                'value'      => $GRP_ID,
1594
-                'css_class'  => '',
1595
-                'format'     => '%d',
1596
-                'db-col'     => 'GRP_ID',
1597
-            ];
1598
-
1599
-            $template_form_fields['ee-msg-messenger'] = [
1600
-                'name'       => 'MTP_messenger',
1601
-                'label'      => null,
1602
-                'input'      => 'hidden',
1603
-                'type'       => 'string',
1604
-                'required'   => false,
1605
-                'validation' => true,
1606
-                'value'      => $message_template_group->messenger(),
1607
-                'css_class'  => '',
1608
-                'format'     => '%s',
1609
-                'db-col'     => 'MTP_messenger',
1610
-            ];
1611
-
1612
-            $template_form_fields['ee-msg-message-type'] = [
1613
-                'name'       => 'MTP_message_type',
1614
-                'label'      => null,
1615
-                'input'      => 'hidden',
1616
-                'type'       => 'string',
1617
-                'required'   => false,
1618
-                'validation' => true,
1619
-                'value'      => $message_template_group->message_type(),
1620
-                'css_class'  => '',
1621
-                'format'     => '%s',
1622
-                'db-col'     => 'MTP_message_type',
1623
-            ];
1624
-
1625
-            $sidebar_form_fields['ee-msg-is-global'] = [
1626
-                'name'       => 'MTP_is_global',
1627
-                'label'      => esc_html__('Global Template', 'event_espresso'),
1628
-                'input'      => 'hidden',
1629
-                'type'       => 'int',
1630
-                'required'   => false,
1631
-                'validation' => true,
1632
-                'value'      => $message_template_group->get('MTP_is_global'),
1633
-                'css_class'  => '',
1634
-                'format'     => '%d',
1635
-                'db-col'     => 'MTP_is_global',
1636
-            ];
1637
-
1638
-            $sidebar_form_fields['ee-msg-is-override'] = [
1639
-                'name'       => 'MTP_is_override',
1640
-                'label'      => esc_html__('Override all custom', 'event_espresso'),
1641
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1642
-                'type'       => 'int',
1643
-                'required'   => false,
1644
-                'validation' => true,
1645
-                'value'      => $message_template_group->get('MTP_is_override'),
1646
-                'css_class'  => '',
1647
-                'format'     => '%d',
1648
-                'db-col'     => 'MTP_is_override',
1649
-            ];
1650
-
1651
-            $sidebar_form_fields['ee-msg-is-active'] = [
1652
-                'name'       => 'MTP_is_active',
1653
-                'label'      => esc_html__('Active Template', 'event_espresso'),
1654
-                'input'      => 'hidden',
1655
-                'type'       => 'int',
1656
-                'required'   => false,
1657
-                'validation' => true,
1658
-                'value'      => $message_template_group->is_active(),
1659
-                'css_class'  => '',
1660
-                'format'     => '%d',
1661
-                'db-col'     => 'MTP_is_active',
1662
-            ];
1663
-
1664
-            $sidebar_form_fields['ee-msg-deleted'] = [
1665
-                'name'       => 'MTP_deleted',
1666
-                'label'      => null,
1667
-                'input'      => 'hidden',
1668
-                'type'       => 'int',
1669
-                'required'   => false,
1670
-                'validation' => true,
1671
-                'value'      => $message_template_group->get('MTP_deleted'),
1672
-                'css_class'  => '',
1673
-                'format'     => '%d',
1674
-                'db-col'     => 'MTP_deleted',
1675
-            ];
1676
-            $sidebar_form_fields['ee-msg-author']  = [
1677
-                'name'       => 'MTP_user_id',
1678
-                'label'      => esc_html__('Author', 'event_espresso'),
1679
-                'input'      => 'hidden',
1680
-                'type'       => 'int',
1681
-                'required'   => false,
1682
-                'validation' => false,
1683
-                'value'      => $message_template_group->user(),
1684
-                'format'     => '%d',
1685
-                'db-col'     => 'MTP_user_id',
1686
-            ];
1687
-
1688
-            $sidebar_form_fields['ee-msg-route'] = [
1689
-                'name'  => 'action',
1690
-                'input' => 'hidden',
1691
-                'type'  => 'string',
1692
-                'value' => $action,
1693
-            ];
1694
-
1695
-            $sidebar_form_fields['ee-msg-id']        = [
1696
-                'name'  => 'id',
1697
-                'input' => 'hidden',
1698
-                'type'  => 'int',
1699
-                'value' => $GRP_ID,
1700
-            ];
1701
-            $sidebar_form_fields['ee-msg-evt-nonce'] = [
1702
-                'name'  => $action . '_nonce',
1703
-                'input' => 'hidden',
1704
-                'type'  => 'string',
1705
-                'value' => wp_create_nonce($action . '_nonce'),
1706
-            ];
1707
-
1708
-            $template_switch = $this->request->getRequestParam('template_switch');
1709
-            if ($template_switch) {
1710
-                $sidebar_form_fields['ee-msg-template-switch'] = [
1711
-                    'name'  => 'template_switch',
1712
-                    'input' => 'hidden',
1713
-                    'type'  => 'int',
1714
-                    'value' => 1,
1715
-                ];
1716
-            }
1717
-
1718
-
1719
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1720
-            $sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1721
-        } //end if ( !empty($template_field_structure) )
1722
-
1723
-        // set extra content for publish box
1724
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1725
-        $this->_set_publish_post_box_vars(
1726
-            'id',
1727
-            $GRP_ID,
1728
-            false,
1729
-            add_query_arg(
1730
-                ['action' => 'global_mtps'],
1731
-                $this->_admin_base_url
1732
-            )
1733
-        );
1734
-
1735
-        // add preview button
1736
-        $preview_url    = parent::add_query_args_and_nonce(
1737
-            [
1738
-                'message_type' => $message_template_group->message_type(),
1739
-                'messenger'    => $message_template_group->messenger(),
1740
-                'context'      => $context,
1741
-                'GRP_ID'       => $GRP_ID,
1742
-                'evt_id'       => $EVT_ID,
1743
-                'action'       => 'preview_message',
1744
-            ],
1745
-            $this->_admin_base_url
1746
-        );
1747
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1748
-                          . esc_html__('Preview', 'event_espresso')
1749
-                          . '</a>';
1750
-
1751
-
1752
-        // setup context switcher
1753
-        $context_switcher_args = [
1754
-            'page'    => 'espresso_messages',
1755
-            'action'  => 'edit_message_template',
1756
-            'id'      => $GRP_ID,
1757
-            'evt_id'  => $EVT_ID,
1758
-            'context' => $context,
1759
-            'extra'   => $preview_button,
1760
-        ];
1761
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1762
-
1763
-
1764
-        // main box
1765
-        $this->_template_args['template_fields']                         = $template_fields;
1766
-        $this->_template_args['sidebar_box_id']                          = 'details';
1767
-        $this->_template_args['action']                                  = $action;
1768
-        $this->_template_args['context']                                 = $context;
1769
-        $this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1770
-        $this->_template_args['learn_more_about_message_templates_link'] =
1771
-            $this->_learn_more_about_message_templates_link();
1772
-
1773
-
1774
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1775
-        $this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1776
-            $message_template_group,
1777
-            $context,
1778
-            $context_label
1779
-        );
1780
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1781
-        $this->_template_args['after_admin_page_content']  = $this->_add_form_element_after();
1782
-
1783
-        $this->_template_path = $this->_template_args['GRP_ID']
1784
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1785
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1786
-
1787
-        // send along EE_Message_Template_Group object for further template use.
1788
-        $this->_template_args['MTP'] = $message_template_group;
1789
-
1790
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1791
-            $this->_template_path,
1792
-            $this->_template_args,
1793
-            true
1794
-        );
1795
-
1796
-
1797
-        // finally, let's set the admin_page title
1798
-        $this->_admin_page_title = sprintf(esc_html__('Editing %s', 'event_espresso'), $title);
1799
-
1800
-
1801
-        // we need to take care of setting the shortcodes property for use elsewhere.
1802
-        $this->_set_shortcodes();
1803
-
1804
-
1805
-        // final template wrapper
1806
-        $this->display_admin_page_with_sidebar();
1807
-    }
1808
-
1809
-
1810
-    public function filter_tinymce_init($mceInit, $editor_id)
1811
-    {
1812
-        return $mceInit;
1813
-    }
1814
-
1815
-
1816
-    public function add_context_switcher()
1817
-    {
1818
-        return $this->_context_switcher;
1819
-    }
1820
-
1821
-
1822
-    /**
1823
-     * Adds the activation/deactivation toggle for the message template context.
1824
-     *
1825
-     * @param EE_Message_Template_Group $message_template_group
1826
-     * @param string                    $context
1827
-     * @param string                    $context_label
1828
-     * @return string
1829
-     * @throws DomainException
1830
-     * @throws EE_Error
1831
-     * @throws InvalidIdentifierException
1832
-     * @throws ReflectionException
1833
-     */
1834
-    protected function add_active_context_element(
1835
-        EE_Message_Template_Group $message_template_group,
1836
-        $context,
1837
-        $context_label
1838
-    ) {
1839
-        $template_args = [
1840
-            'context'                   => $context,
1841
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1842
-            'is_active'                 => $message_template_group->is_context_active($context),
1843
-            'on_off_action'             => $message_template_group->is_context_active($context)
1844
-                ? 'context-off'
1845
-                : 'context-on',
1846
-            'context_label'             => str_replace(['(', ')'], '', $context_label),
1847
-            'message_template_group_id' => $message_template_group->ID(),
1848
-        ];
1849
-        return EEH_Template::display_template(
1850
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1851
-            $template_args,
1852
-            true
1853
-        );
1854
-    }
1855
-
1856
-
1857
-    /**
1858
-     * Ajax callback for `toggle_context_template` ajax action.
1859
-     * Handles toggling the message context on or off.
1860
-     *
1861
-     * @throws EE_Error
1862
-     * @throws InvalidArgumentException
1863
-     * @throws InvalidDataTypeException
1864
-     * @throws InvalidIdentifierException
1865
-     * @throws InvalidInterfaceException
1866
-     */
1867
-    public function toggle_context_template()
1868
-    {
1869
-        $success = true;
1870
-        // check for required data
1871
-        if (
1872
-            ! (
1873
-                $this->request->requestParamIsSet('message_template_group_id')
1874
-                && $this->request->requestParamIsSet('context')
1875
-                && $this->request->requestParamIsSet('status')
1876
-            )
1877
-        ) {
1878
-            EE_Error::add_error(
1879
-                esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1880
-                __FILE__,
1881
-                __FUNCTION__,
1882
-                __LINE__
1883
-            );
1884
-            $success = false;
1885
-        }
1886
-
1887
-        $nonce   = $this->request->getRequestParam('toggle_context_nonce', '');
1888
-        $context = $this->request->getRequestParam('context', '');
1889
-        $status  = $this->request->getRequestParam('status', '');
1890
-
1891
-        $this->_verify_nonce($nonce, "activate_{$context}_toggle_nonce");
1892
-
1893
-        if ($status !== 'off' && $status !== 'on') {
1894
-            EE_Error::add_error(
1895
-                sprintf(
1896
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1897
-                    $status
1898
-                ),
1899
-                __FILE__,
1900
-                __FUNCTION__,
1901
-                __LINE__
1902
-            );
1903
-            $success = false;
1904
-        }
1905
-        $message_template_group_id = $this->request->getRequestParam('message_template_group_id', 0, 'int');
1906
-        $message_template_group    = EEM_Message_Template_Group::instance()->get_one_by_ID($message_template_group_id);
1907
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1908
-            EE_Error::add_error(
1909
-                sprintf(
1910
-                    esc_html__(
1911
-                        'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1912
-                        'event_espresso'
1913
-                    ),
1914
-                    $message_template_group_id,
1915
-                    'EE_Message_Template_Group'
1916
-                ),
1917
-                __FILE__,
1918
-                __FUNCTION__,
1919
-                __LINE__
1920
-            );
1921
-            $success = false;
1922
-        }
1923
-        if ($success) {
1924
-            $success = $status === 'off'
1925
-                ? $message_template_group->deactivate_context($context)
1926
-                : $message_template_group->activate_context($context);
1927
-        }
1928
-        $this->_template_args['success'] = $success;
1929
-        $this->_return_json();
1930
-    }
1931
-
1932
-
1933
-    public function _add_form_element_before()
1934
-    {
1935
-        return '<form method="post" action="'
1936
-               . $this->_template_args['edit_message_template_form_url']
1937
-               . '" id="ee-msg-edit-frm">';
1938
-    }
1939
-
1940
-
1941
-    public function _add_form_element_after()
1942
-    {
1943
-        return '</form>';
1944
-    }
1945
-
1946
-
1947
-    /**
1948
-     * This executes switching the template pack for a message template.
1949
-     *
1950
-     * @throws EE_Error
1951
-     * @throws InvalidDataTypeException
1952
-     * @throws InvalidInterfaceException
1953
-     * @throws InvalidArgumentException
1954
-     * @throws ReflectionException
1955
-     * @since 4.5.0
1956
-     */
1957
-    public function switch_template_pack()
1958
-    {
1959
-
1960
-        $GRP_ID        = $this->request->getRequestParam('GRP_ID', 0, 'int');
1961
-        $template_pack = $this->request->getRequestParam('template_pack', '');
1962
-
1963
-        // verify we have needed values.
1964
-        if (empty($GRP_ID) || empty($template_pack)) {
1965
-            $this->_template_args['error'] = true;
1966
-            EE_Error::add_error(
1967
-                esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1968
-                __FILE__,
1969
-                __FUNCTION__,
1970
-                __LINE__
1971
-            );
1972
-        } else {
1973
-            // get template, set the new template_pack and then reset to default
1974
-            /** @var EE_Message_Template_Group $message_template_group */
1975
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1976
-
1977
-            $message_template_group->set_template_pack_name($template_pack);
1978
-            $this->request->setRequestParam('msgr', $message_template_group->messenger());
1979
-            $this->request->setRequestParam('mt', $message_template_group->message_type());
1980
-
1981
-            $query_args = $this->_reset_to_default_template();
1982
-
1983
-            if (empty($query_args['id'])) {
1984
-                EE_Error::add_error(
1985
-                    esc_html__(
1986
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1987
-                        'event_espresso'
1988
-                    ),
1989
-                    __FILE__,
1990
-                    __FUNCTION__,
1991
-                    __LINE__
1992
-                );
1993
-                $this->_template_args['error'] = true;
1994
-            } else {
1995
-                $template_label       = $message_template_group->get_template_pack()->label;
1996
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1997
-                EE_Error::add_success(
1998
-                    sprintf(
1999
-                        esc_html__(
2000
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
2001
-                            'event_espresso'
2002
-                        ),
2003
-                        $template_label,
2004
-                        $template_pack_labels->template_pack
2005
-                    )
2006
-                );
2007
-                // generate the redirect url for js.
2008
-                $url = self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2009
-
2010
-                $this->_template_args['data']['redirect_url'] = $url;
2011
-                $this->_template_args['success']              = true;
2012
-            }
2013
-
2014
-            $this->_return_json();
2015
-        }
2016
-    }
2017
-
2018
-
2019
-    /**
2020
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2021
-     * they want.
2022
-     *
2023
-     * @access protected
2024
-     * @return array|void
2025
-     * @throws EE_Error
2026
-     * @throws InvalidArgumentException
2027
-     * @throws InvalidDataTypeException
2028
-     * @throws InvalidInterfaceException
2029
-     * @throws ReflectionException
2030
-     */
2031
-    protected function _reset_to_default_template()
2032
-    {
2033
-        $templates    = [];
2034
-        $GRP_ID       = $this->request->getRequestParam('GRP_ID', 0, 'int');
2035
-        $messenger    = $this->request->getRequestParam('msgr');
2036
-        $message_type = $this->request->getRequestParam('mt');
2037
-        // we need to make sure we've got the info we need.
2038
-        if (! ($GRP_ID && $messenger && $message_type)) {
2039
-            EE_Error::add_error(
2040
-                esc_html__(
2041
-                    'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
2042
-                    'event_espresso'
2043
-                ),
2044
-                __FILE__,
2045
-                __FUNCTION__,
2046
-                __LINE__
2047
-            );
2048
-        }
2049
-
2050
-        // all templates will be reset to whatever the defaults are
2051
-        // for the global template matching the messenger and message type.
2052
-        $success = ! empty($GRP_ID);
2053
-
2054
-        if ($success) {
2055
-            // let's first determine if the incoming template is a global template,
2056
-            // if it isn't then we need to get the global template matching messenger and message type.
2057
-            // $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2058
-
2059
-
2060
-            // note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2061
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
2062
-
2063
-            if ($success) {
2064
-                // if successfully deleted, lets generate the new ones.
2065
-                // Note. We set GLOBAL to true, because resets on ANY template
2066
-                // will use the related global template defaults for regeneration.
2067
-                // This means that if a custom template is reset it resets to whatever the related global template is.
2068
-                // HOWEVER, we DO keep the template pack and template variation set
2069
-                // for the current custom template when resetting.
2070
-                $templates = $this->_generate_new_templates($messenger, $message_type, $GRP_ID, true);
2071
-            }
2072
-        }
2073
-
2074
-        // any error messages?
2075
-        if (! $success) {
2076
-            EE_Error::add_error(
2077
-                esc_html__(
2078
-                    'Something went wrong with deleting existing templates. Unable to reset to default',
2079
-                    'event_espresso'
2080
-                ),
2081
-                __FILE__,
2082
-                __FUNCTION__,
2083
-                __LINE__
2084
-            );
2085
-        }
2086
-
2087
-        // all good, let's add a success message!
2088
-        if ($success && ! empty($templates)) {
2089
-            // the info for the template we generated is the first element in the returned array
2090
-            // $templates = $templates[0];
2091
-            EE_Error::overwrite_success();
2092
-            EE_Error::add_success(esc_html__('Templates have been reset to defaults.', 'event_espresso'));
2093
-        }
2094
-
2095
-
2096
-        $query_args = [
2097
-            'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2098
-            'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2099
-            'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2100
-        ];
2101
-
2102
-        // if called via ajax then we return query args otherwise redirect
2103
-        if ($this->request->isAjax()) {
2104
-            return $query_args;
2105
-        }
2106
-        $this->_redirect_after_action(false, '', '', $query_args, true);
2107
-    }
2108
-
2109
-
2110
-    /**
2111
-     * Retrieve and set the message preview for display.
2112
-     *
2113
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2114
-     * @return string
2115
-     * @throws ReflectionException
2116
-     * @throws EE_Error
2117
-     * @throws InvalidArgumentException
2118
-     * @throws InvalidDataTypeException
2119
-     * @throws InvalidInterfaceException
2120
-     */
2121
-    public function _preview_message($send = false)
2122
-    {
2123
-        // first make sure we've got the necessary parameters
2124
-        $GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
2125
-        if (! ($GRP_ID && $this->_active_messenger_name && $this->_active_message_type_name)) {
2126
-            EE_Error::add_error(
2127
-                esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2128
-                __FILE__,
2129
-                __FUNCTION__,
2130
-                __LINE__
2131
-            );
2132
-        }
2133
-
2134
-        $context = $this->request->getRequestParam('context');
2135
-        // get the preview!
2136
-        $preview = EED_Messages::preview_message(
2137
-            $this->_active_message_type_name,
2138
-            $context,
2139
-            $this->_active_messenger_name,
2140
-            $send
2141
-        );
2142
-
2143
-        if ($send) {
2144
-            return $preview;
2145
-        }
2146
-
2147
-        // if we have an evt_id set on the request, use it.
2148
-        $EVT_ID = $this->request->getRequestParam('evt_id', 0, 'int');
2149
-
2150
-        // let's add a button to go back to the edit view
2151
-        $query_args             = [
2152
-            'id'      => $GRP_ID,
2153
-            'evt_id'  => $EVT_ID,
2154
-            'context' => $context,
2155
-            'action'  => 'edit_message_template',
2156
-        ];
2157
-        $go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2158
-        $preview_button         = '<a href="'
2159
-                                  . $go_back_url
2160
-                                  . '" class="button-secondary messages-preview-go-back-button">'
2161
-                                  . esc_html__('Go Back to Edit', 'event_espresso')
2162
-                                  . '</a>';
2163
-        $message_types          = $this->get_installed_message_types();
2164
-        $active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_active_messenger_name);
2165
-        $active_messenger_label = $active_messenger instanceof EE_messenger
2166
-            ? ucwords($active_messenger->label['singular'])
2167
-            : esc_html__('Unknown Messenger', 'event_espresso');
2168
-        // let's provide a helpful title for context
2169
-        $preview_title = sprintf(
2170
-            esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2171
-            $active_messenger_label,
2172
-            ucwords($message_types[ $this->_active_message_type_name ]->label['singular'])
2173
-        );
2174
-        if (empty($preview)) {
2175
-            $this->noEventsErrorMessage();
2176
-        }
2177
-        // setup display of preview.
2178
-        $this->_admin_page_title                    = $preview_title;
2179
-        $this->_template_args['admin_page_title']   = $preview_title;
2180
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2181
-        $this->_template_args['data']['force_json'] = true;
2182
-
2183
-        return '';
2184
-    }
2185
-
2186
-
2187
-    /**
2188
-     * Used to set an error if there are no events available for generating a preview/test send.
2189
-     *
2190
-     * @param bool $test_send Whether the error should be generated for the context of a test send.
2191
-     */
2192
-    protected function noEventsErrorMessage($test_send = false)
2193
-    {
2194
-        $events_url = parent::add_query_args_and_nonce(
2195
-            [
2196
-                'action' => 'default',
2197
-                'page'   => 'espresso_events',
2198
-            ],
2199
-            admin_url('admin.php')
2200
-        );
2201
-        $message    = $test_send
2202
-            ? esc_html__(
2203
-                'A test message could not be sent for this message template because there are no events created yet. The preview system uses actual events for generating the test message. %1$sGo see your events%2$s!',
2204
-                'event_espresso'
2205
-            )
2206
-            : esc_html__(
2207
-                'There is no preview for this message template available because there are no events created yet. The preview system uses actual events for generating the preview. %1$sGo see your events%2$s!',
2208
-                'event_espresso'
2209
-            );
2210
-
2211
-        EE_Error::add_attention(
2212
-            sprintf(
2213
-                $message,
2214
-                "<a href='{$events_url}'>",
2215
-                '</a>'
2216
-            )
2217
-        );
2218
-    }
2219
-
2220
-
2221
-    /**
2222
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2223
-     * gets called automatically.
2224
-     *
2225
-     * @return void
2226
-     * @throws EE_Error
2227
-     * @since 4.5.0
2228
-     *
2229
-     */
2230
-    protected function _display_preview_message()
2231
-    {
2232
-        $this->display_admin_page_with_no_sidebar();
2233
-    }
2234
-
2235
-
2236
-    /**
2237
-     * registers metaboxes that should show up on the "edit_message_template" page
2238
-     *
2239
-     * @access protected
2240
-     * @return void
2241
-     */
2242
-    protected function _register_edit_meta_boxes()
2243
-    {
2244
-        add_meta_box(
2245
-            'mtp_valid_shortcodes',
2246
-            esc_html__('Valid Shortcodes', 'event_espresso'),
2247
-            [$this, 'shortcode_meta_box'],
2248
-            $this->_current_screen->id,
2249
-            'side'
2250
-        );
2251
-        add_meta_box(
2252
-            'mtp_extra_actions',
2253
-            esc_html__('Extra Actions', 'event_espresso'),
2254
-            [$this, 'extra_actions_meta_box'],
2255
-            $this->_current_screen->id,
2256
-            'side',
2257
-            'high'
2258
-        );
2259
-        add_meta_box(
2260
-            'mtp_templates',
2261
-            esc_html__('Template Styles', 'event_espresso'),
2262
-            [$this, 'template_pack_meta_box'],
2263
-            $this->_current_screen->id,
2264
-            'side',
2265
-            'high'
2266
-        );
2267
-    }
2268
-
2269
-
2270
-    /**
2271
-     * metabox content for all template pack and variation selection.
2272
-     *
2273
-     * @return void
2274
-     * @throws DomainException
2275
-     * @throws EE_Error
2276
-     * @throws InvalidArgumentException
2277
-     * @throws ReflectionException
2278
-     * @throws InvalidDataTypeException
2279
-     * @throws InvalidInterfaceException
2280
-     * @since 4.5.0
2281
-     */
2282
-    public function template_pack_meta_box()
2283
-    {
2284
-        $this->_set_message_template_group();
2285
-
2286
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
2287
-
2288
-        $tp_select_values = [];
2289
-
2290
-        foreach ($tp_collection as $tp) {
2291
-            // only include template packs that support this messenger and message type!
2292
-            $supports = $tp->get_supports();
2293
-            if (
2294
-                ! isset($supports[ $this->_message_template_group->messenger() ])
2295
-                || ! in_array(
2296
-                    $this->_message_template_group->message_type(),
2297
-                    $supports[ $this->_message_template_group->messenger() ],
2298
-                    true
2299
-                )
2300
-            ) {
2301
-                // not supported
2302
-                continue;
2303
-            }
2304
-
2305
-            $tp_select_values[] = [
2306
-                'text' => $tp->label,
2307
-                'id'   => $tp->dbref,
2308
-            ];
2309
-        }
2310
-
2311
-        // if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2312
-        // the default template pack.  This still allows for the odd template pack to override.
2313
-        if (empty($tp_select_values)) {
2314
-            $tp_select_values[] = [
2315
-                'text' => esc_html__('Default', 'event_espresso'),
2316
-                'id'   => 'default',
2317
-            ];
2318
-        }
2319
-
2320
-        // setup variation select values for the currently selected template.
2321
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
2322
-            $this->_message_template_group->messenger(),
2323
-            $this->_message_template_group->message_type()
2324
-        );
2325
-        $variations_select_values = [];
2326
-        foreach ($variations as $variation => $label) {
2327
-            $variations_select_values[] = [
2328
-                'text' => $label,
2329
-                'id'   => $variation,
2330
-            ];
2331
-        }
2332
-
2333
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2334
-
2335
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
2336
-            'MTP_template_pack',
2337
-            $tp_select_values,
2338
-            $this->_message_template_group->get_template_pack_name()
2339
-        );
2340
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
2341
-            'MTP_template_variation',
2342
-            $variations_select_values,
2343
-            $this->_message_template_group->get_template_pack_variation()
2344
-        );
2345
-        $template_args['template_pack_label']            = $template_pack_labels->template_pack;
2346
-        $template_args['template_variation_label']       = $template_pack_labels->template_variation;
2347
-        $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
2348
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2349
-
2350
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2351
-
2352
-        EEH_Template::display_template($template, $template_args);
2353
-    }
2354
-
2355
-
2356
-    /**
2357
-     * This meta box holds any extra actions related to Message Templates
2358
-     * For now, this includes Resetting templates to defaults and sending a test email.
2359
-     *
2360
-     * @access  public
2361
-     * @return void
2362
-     * @throws EE_Error
2363
-     */
2364
-    public function extra_actions_meta_box()
2365
-    {
2366
-        $template_form_fields = [];
2367
-
2368
-        $extra_args = [
2369
-            'msgr'   => $this->_message_template_group->messenger(),
2370
-            'mt'     => $this->_message_template_group->message_type(),
2371
-            'GRP_ID' => $this->_message_template_group->GRP_ID(),
2372
-        ];
2373
-        // first we need to see if there are any fields
2374
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2375
-
2376
-        if (! empty($fields)) {
2377
-            // yup there be fields
2378
-            foreach ($fields as $field => $config) {
2379
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2380
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2381
-                $default  = isset($config['default']) ? $config['default'] : '';
2382
-                $default  = isset($config['value']) ? $config['value'] : $default;
2383
-
2384
-                // if type is hidden and the value is empty
2385
-                // something may have gone wrong so let's correct with the defaults
2386
-                $fix                = $config['input'] === 'hidden'
2387
-                                      && isset($existing[ $field ])
2388
-                                      && empty($existing[ $field ])
2389
-                    ? $default
2390
-                    : '';
2391
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2392
-                    ? $existing[ $field ]
2393
-                    : $fix;
2394
-
2395
-                $template_form_fields[ $field_id ] = [
2396
-                    'name'       => 'test_settings_fld[' . $field . ']',
2397
-                    'label'      => $config['label'],
2398
-                    'input'      => $config['input'],
2399
-                    'type'       => $config['type'],
2400
-                    'required'   => $config['required'],
2401
-                    'validation' => $config['validation'],
2402
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2403
-                    'css_class'  => $config['css_class'],
2404
-                    'options'    => isset($config['options']) ? $config['options'] : [],
2405
-                    'default'    => $default,
2406
-                    'format'     => $config['format'],
2407
-                ];
2408
-            }
2409
-        }
2410
-
2411
-        $test_settings_html = ! empty($template_form_fields)
2412
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2413
-            : '';
2414
-
2415
-        // print out $test_settings_fields
2416
-        if (! empty($test_settings_html)) {
2417
-            $test_settings_html .= '<input type="submit" class="button-primary mtp-test-button alignright" ';
2418
-            $test_settings_html .= 'name="test_button" value="';
2419
-            $test_settings_html .= esc_html__('Test Send', 'event_espresso');
2420
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2421
-        }
2422
-
2423
-        // and button
2424
-        $test_settings_html .= '<p>';
2425
-        $test_settings_html .= esc_html__('Need to reset this message type and start over?', 'event_espresso');
2426
-        $test_settings_html .= '</p>';
2427
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2428
-        $test_settings_html .= $this->get_action_link_or_button(
2429
-            'reset_to_default',
2430
-            'reset',
2431
-            $extra_args,
2432
-            'button-primary reset-default-button'
2433
-        );
2434
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2435
-        echo $test_settings_html; // already escaped
2436
-    }
2437
-
2438
-
2439
-    /**
2440
-     * This returns the shortcode selector skeleton for a given context and field.
2441
-     *
2442
-     * @param string $field           The name of the field retrieving shortcodes for.
2443
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2444
-     * @return string
2445
-     * @throws DomainException
2446
-     * @throws EE_Error
2447
-     * @throws InvalidArgumentException
2448
-     * @throws ReflectionException
2449
-     * @throws InvalidDataTypeException
2450
-     * @throws InvalidInterfaceException
2451
-     * @since 4.9.rc.000
2452
-     */
2453
-    protected function _get_shortcode_selector($field, $linked_input_id)
2454
-    {
2455
-        $template_args = [
2456
-            'shortcodes'      => $this->_get_shortcodes([$field]),
2457
-            'fieldname'       => $field,
2458
-            'linked_input_id' => $linked_input_id,
2459
-        ];
2460
-
2461
-        return EEH_Template::display_template(
2462
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2463
-            $template_args,
2464
-            true
2465
-        );
2466
-    }
2467
-
2468
-
2469
-    /**
2470
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2471
-     * page)
2472
-     *
2473
-     * @access public
2474
-     * @return void
2475
-     * @throws EE_Error
2476
-     * @throws InvalidArgumentException
2477
-     * @throws ReflectionException
2478
-     * @throws InvalidDataTypeException
2479
-     * @throws InvalidInterfaceException
2480
-     */
2481
-    public function shortcode_meta_box()
2482
-    {
2483
-        $shortcodes = $this->_get_shortcodes([], false);
2484
-        // just make sure the shortcodes property is set
2485
-        // $messenger = $this->_message_template_group->messenger_obj();
2486
-        // now let's set the content depending on the status of the shortcodes array
2487
-        if (empty($shortcodes)) {
2488
-            echo '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2489
-            return;
2490
-        }
2491
-        ?>
20
+	/**
21
+	 * @var EE_Message_Resource_Manager $_message_resource_manager
22
+	 */
23
+	protected $_message_resource_manager;
24
+
25
+	/**
26
+	 * @var string
27
+	 */
28
+	protected $_active_message_type_name = '';
29
+
30
+	/**
31
+	 * @var string
32
+	 */
33
+	protected $_active_messenger_name = '';
34
+
35
+	/**
36
+	 * @var EE_messenger $_active_messenger
37
+	 */
38
+	protected $_active_messenger;
39
+
40
+	protected $_activate_meta_box_type;
41
+
42
+	protected $_current_message_meta_box;
43
+
44
+	protected $_current_message_meta_box_object;
45
+
46
+	protected $_context_switcher;
47
+
48
+	protected $_shortcodes           = [];
49
+
50
+	protected $_active_messengers    = [];
51
+
52
+	protected $_active_message_types = [];
53
+
54
+	/**
55
+	 * @var EE_Message_Template_Group $_message_template_group
56
+	 */
57
+	protected $_message_template_group;
58
+
59
+	protected $_m_mt_settings = [];
60
+
61
+
62
+	/**
63
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
64
+	 * IF there is no group then it gets automatically set to the Default template pack.
65
+	 *
66
+	 * @since 4.5.0
67
+	 *
68
+	 * @var EE_Messages_Template_Pack
69
+	 */
70
+	protected $_template_pack;
71
+
72
+
73
+	/**
74
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
75
+	 * group is.  If there is no group then it automatically gets set to default.
76
+	 *
77
+	 * @since 4.5.0
78
+	 *
79
+	 * @var string
80
+	 */
81
+	protected $_variation;
82
+
83
+
84
+	/**
85
+	 * @param bool $routing
86
+	 * @throws EE_Error
87
+	 * @throws ReflectionException
88
+	 */
89
+	public function __construct($routing = true)
90
+	{
91
+		// make sure messages autoloader is running
92
+		EED_Messages::set_autoloaders();
93
+		parent::__construct($routing);
94
+	}
95
+
96
+
97
+	/**
98
+	 * @throws EE_Error
99
+	 * @throws ReflectionException
100
+	 */
101
+	protected function _init_page_props()
102
+	{
103
+		$this->page_slug        = EE_MSG_PG_SLUG;
104
+		$this->page_label       = esc_html__('Messages Settings', 'event_espresso');
105
+		$this->_admin_base_url  = EE_MSG_ADMIN_URL;
106
+		$this->_admin_base_path = EE_MSG_ADMIN;
107
+
108
+		$this->_active_messenger_name    = $this->request->getRequestParam('messenger', '');
109
+		$this->_active_message_type_name = $this->request->getRequestParam('message_type', '');
110
+
111
+		$this->_load_message_resource_manager();
112
+	}
113
+
114
+
115
+	/**
116
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
117
+	 *
118
+	 * @throws EE_Error
119
+	 * @throws InvalidDataTypeException
120
+	 * @throws InvalidInterfaceException
121
+	 * @throws InvalidArgumentException
122
+	 * @throws ReflectionException
123
+	 */
124
+	protected function _load_message_resource_manager()
125
+	{
126
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
127
+	}
128
+
129
+
130
+	/**
131
+	 * @return array
132
+	 * @throws EE_Error
133
+	 * @throws InvalidArgumentException
134
+	 * @throws InvalidDataTypeException
135
+	 * @throws InvalidInterfaceException
136
+	 * @deprecated 4.9.9.rc.014
137
+	 */
138
+	public function get_messengers_for_list_table()
139
+	{
140
+		EE_Error::doing_it_wrong(
141
+			__METHOD__,
142
+			sprintf(
143
+				esc_html__(
144
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
145
+					'event_espresso'
146
+				),
147
+				'Messages_Admin_Page::get_messengers_select_input()'
148
+			),
149
+			'4.9.9.rc.014'
150
+		);
151
+
152
+		$m_values          = [];
153
+		$active_messengers = EEM_Message::instance()->get_all(['group_by' => 'MSG_messenger']);
154
+		// setup messengers for selects
155
+		$i = 1;
156
+		foreach ($active_messengers as $active_messenger) {
157
+			if ($active_messenger instanceof EE_Message) {
158
+				$m_values[ $i ]['id']   = $active_messenger->messenger();
159
+				$m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
160
+				$i++;
161
+			}
162
+		}
163
+
164
+		return $m_values;
165
+	}
166
+
167
+
168
+	/**
169
+	 * @return array
170
+	 * @throws EE_Error
171
+	 * @throws InvalidArgumentException
172
+	 * @throws InvalidDataTypeException
173
+	 * @throws InvalidInterfaceException
174
+	 * @deprecated 4.9.9.rc.014
175
+	 */
176
+	public function get_message_types_for_list_table()
177
+	{
178
+		EE_Error::doing_it_wrong(
179
+			__METHOD__,
180
+			sprintf(
181
+				esc_html__(
182
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
183
+					'event_espresso'
184
+				),
185
+				'Messages_Admin_Page::get_message_types_select_input()'
186
+			),
187
+			'4.9.9.rc.014'
188
+		);
189
+
190
+		$mt_values       = [];
191
+		$active_messages = EEM_Message::instance()->get_all(['group_by' => 'MSG_message_type']);
192
+		$i               = 1;
193
+		foreach ($active_messages as $active_message) {
194
+			if ($active_message instanceof EE_Message) {
195
+				$mt_values[ $i ]['id']   = $active_message->message_type();
196
+				$mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
197
+				$i++;
198
+			}
199
+		}
200
+
201
+		return $mt_values;
202
+	}
203
+
204
+
205
+	/**
206
+	 * @return array
207
+	 * @throws EE_Error
208
+	 * @throws InvalidArgumentException
209
+	 * @throws InvalidDataTypeException
210
+	 * @throws InvalidInterfaceException
211
+	 * @deprecated 4.9.9.rc.014
212
+	 */
213
+	public function get_contexts_for_message_types_for_list_table()
214
+	{
215
+		EE_Error::doing_it_wrong(
216
+			__METHOD__,
217
+			sprintf(
218
+				esc_html__(
219
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
220
+					'event_espresso'
221
+				),
222
+				'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
223
+			),
224
+			'4.9.9.rc.014'
225
+		);
226
+
227
+		$contexts                = [];
228
+		$active_message_contexts = EEM_Message::instance()->get_all(['group_by' => 'MSG_context']);
229
+		foreach ($active_message_contexts as $active_message) {
230
+			if ($active_message instanceof EE_Message) {
231
+				$message_type = $active_message->message_type_object();
232
+				if ($message_type instanceof EE_message_type) {
233
+					$message_type_contexts = $message_type->get_contexts();
234
+					foreach ($message_type_contexts as $context => $context_details) {
235
+						$contexts[ $context ] = $context_details['label'];
236
+					}
237
+				}
238
+			}
239
+		}
240
+
241
+		return $contexts;
242
+	}
243
+
244
+
245
+	/**
246
+	 * Generate select input with provided messenger options array.
247
+	 *
248
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
249
+	 *                                 labels.
250
+	 * @return string
251
+	 * @throws EE_Error
252
+	 */
253
+	public function get_messengers_select_input($messenger_options)
254
+	{
255
+		// if empty or just one value then just return an empty string
256
+		if (
257
+			empty($messenger_options)
258
+			|| ! is_array($messenger_options)
259
+			|| count($messenger_options) === 1
260
+		) {
261
+			return '';
262
+		}
263
+		// merge in default
264
+		$messenger_options = array_merge(
265
+			['none_selected' => esc_html__('Show All Messengers', 'event_espresso')],
266
+			$messenger_options
267
+		);
268
+		$input             = new EE_Select_Input(
269
+			$messenger_options,
270
+			[
271
+				'html_name'  => 'ee_messenger_filter_by',
272
+				'html_id'    => 'ee_messenger_filter_by',
273
+				'html_class' => 'wide',
274
+				'default'    => $this->request->getRequestParam('ee_messenger_filter_by', 'none_selected', 'title'),
275
+			]
276
+		);
277
+
278
+		return $input->get_html_for_input();
279
+	}
280
+
281
+
282
+	/**
283
+	 * Generate select input with provided message type options array.
284
+	 *
285
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
286
+	 *                                    message type labels
287
+	 * @return string
288
+	 * @throws EE_Error
289
+	 */
290
+	public function get_message_types_select_input($message_type_options)
291
+	{
292
+		// if empty or count of options is 1 then just return an empty string
293
+		if (
294
+			empty($message_type_options)
295
+			|| ! is_array($message_type_options)
296
+			|| count($message_type_options) === 1
297
+		) {
298
+			return '';
299
+		}
300
+		// merge in default
301
+		$message_type_options = array_merge(
302
+			['none_selected' => esc_html__('Show All Message Types', 'event_espresso')],
303
+			$message_type_options
304
+		);
305
+		$input                = new EE_Select_Input(
306
+			$message_type_options,
307
+			[
308
+				'html_name'  => 'ee_message_type_filter_by',
309
+				'html_id'    => 'ee_message_type_filter_by',
310
+				'html_class' => 'wide',
311
+				'default'    => $this->request->getRequestParam('ee_message_type_filter_by', 'none_selected', 'title'),
312
+			]
313
+		);
314
+
315
+		return $input->get_html_for_input();
316
+	}
317
+
318
+
319
+	/**
320
+	 * Generate select input with provide message type contexts array.
321
+	 *
322
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
323
+	 *                               context label.
324
+	 * @return string
325
+	 * @throws EE_Error
326
+	 */
327
+	public function get_contexts_for_message_types_select_input($context_options)
328
+	{
329
+		// if empty or count of options is one then just return empty string
330
+		if (
331
+			empty($context_options)
332
+			|| ! is_array($context_options)
333
+			|| count($context_options) === 1
334
+		) {
335
+			return '';
336
+		}
337
+		// merge in default
338
+		$context_options = array_merge(
339
+			['none_selected' => esc_html__('Show all Contexts', 'event_espresso')],
340
+			$context_options
341
+		);
342
+		$input           = new EE_Select_Input(
343
+			$context_options,
344
+			[
345
+				'html_name'  => 'ee_context_filter_by',
346
+				'html_id'    => 'ee_context_filter_by',
347
+				'html_class' => 'wide',
348
+				'default'    => $this->request->getRequestParam('ee_context_filter_by', 'none_selected', 'title'),
349
+			]
350
+		);
351
+
352
+		return $input->get_html_for_input();
353
+	}
354
+
355
+
356
+	protected function _ajax_hooks()
357
+	{
358
+		add_action('wp_ajax_activate_messenger', [$this, 'activate_messenger_toggle']);
359
+		add_action('wp_ajax_activate_mt', [$this, 'activate_mt_toggle']);
360
+		add_action('wp_ajax_ee_msgs_save_settings', [$this, 'save_settings']);
361
+		add_action('wp_ajax_ee_msgs_update_mt_form', [$this, 'update_mt_form']);
362
+		add_action('wp_ajax_switch_template_pack', [$this, 'switch_template_pack']);
363
+		add_action('wp_ajax_toggle_context_template', [$this, 'toggle_context_template']);
364
+	}
365
+
366
+
367
+	protected function _define_page_props()
368
+	{
369
+		$this->_admin_page_title = $this->page_label;
370
+		$this->_labels           = [
371
+			'buttons'    => [
372
+				'add'    => esc_html__('Add New Message Template', 'event_espresso'),
373
+				'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
374
+				'delete' => esc_html__('Delete Message Template', 'event_espresso'),
375
+			],
376
+			'publishbox' => esc_html__('Update Actions', 'event_espresso'),
377
+		];
378
+	}
379
+
380
+
381
+	/**
382
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
383
+	 *
384
+	 * @access protected
385
+	 * @return void
386
+	 */
387
+	protected function _set_page_routes()
388
+	{
389
+		$GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
390
+		$GRP_ID = $this->request->getRequestParam('id', $GRP_ID, 'int');
391
+		$MSG_ID = $this->request->getRequestParam('MSG_ID', 0, 'int');
392
+
393
+		$this->_page_routes = [
394
+			'default'                          => [
395
+				'func'       => '_message_queue_list_table',
396
+				'capability' => 'ee_read_global_messages',
397
+			],
398
+			'global_mtps'                      => [
399
+				'func'       => '_ee_default_messages_overview_list_table',
400
+				'capability' => 'ee_read_global_messages',
401
+			],
402
+			'custom_mtps'                      => [
403
+				'func'       => '_custom_mtps_preview',
404
+				'capability' => 'ee_read_messages',
405
+			],
406
+			'add_new_message_template'         => [
407
+				'func'       => '_add_message_template',
408
+				'capability' => 'ee_edit_messages',
409
+				'noheader'   => true,
410
+			],
411
+			'edit_message_template'            => [
412
+				'func'       => '_edit_message_template',
413
+				'capability' => 'ee_edit_message',
414
+				'obj_id'     => $GRP_ID,
415
+			],
416
+			'preview_message'                  => [
417
+				'func'               => '_preview_message',
418
+				'capability'         => 'ee_read_message',
419
+				'obj_id'             => $GRP_ID,
420
+				'noheader'           => true,
421
+				'headers_sent_route' => 'display_preview_message',
422
+			],
423
+			'display_preview_message'          => [
424
+				'func'       => '_display_preview_message',
425
+				'capability' => 'ee_read_message',
426
+				'obj_id'     => $GRP_ID,
427
+			],
428
+			'insert_message_template'          => [
429
+				'func'       => '_insert_or_update_message_template',
430
+				'capability' => 'ee_edit_messages',
431
+				'args'       => ['new' => true],
432
+				'noheader'   => true,
433
+			],
434
+			'update_message_template'          => [
435
+				'func'       => '_insert_or_update_message_template',
436
+				'capability' => 'ee_edit_message',
437
+				'obj_id'     => $GRP_ID,
438
+				'args'       => ['new' => false],
439
+				'noheader'   => true,
440
+			],
441
+			'trash_message_template'           => [
442
+				'func'       => '_trash_or_restore_message_template',
443
+				'capability' => 'ee_delete_message',
444
+				'obj_id'     => $GRP_ID,
445
+				'args'       => ['trash' => true, 'all' => true],
446
+				'noheader'   => true,
447
+			],
448
+			'trash_message_template_context'   => [
449
+				'func'       => '_trash_or_restore_message_template',
450
+				'capability' => 'ee_delete_message',
451
+				'obj_id'     => $GRP_ID,
452
+				'args'       => ['trash' => true],
453
+				'noheader'   => true,
454
+			],
455
+			'restore_message_template'         => [
456
+				'func'       => '_trash_or_restore_message_template',
457
+				'capability' => 'ee_delete_message',
458
+				'obj_id'     => $GRP_ID,
459
+				'args'       => ['trash' => false, 'all' => true],
460
+				'noheader'   => true,
461
+			],
462
+			'restore_message_template_context' => [
463
+				'func'       => '_trash_or_restore_message_template',
464
+				'capability' => 'ee_delete_message',
465
+				'obj_id'     => $GRP_ID,
466
+				'args'       => ['trash' => false],
467
+				'noheader'   => true,
468
+			],
469
+			'delete_message_template'          => [
470
+				'func'       => '_delete_message_template',
471
+				'capability' => 'ee_delete_message',
472
+				'obj_id'     => $GRP_ID,
473
+				'noheader'   => true,
474
+			],
475
+			'reset_to_default'                 => [
476
+				'func'       => '_reset_to_default_template',
477
+				'capability' => 'ee_edit_message',
478
+				'obj_id'     => $GRP_ID,
479
+				'noheader'   => true,
480
+			],
481
+			'settings'                         => [
482
+				'func'       => '_settings',
483
+				'capability' => 'manage_options',
484
+			],
485
+			'update_global_settings'           => [
486
+				'func'       => '_update_global_settings',
487
+				'capability' => 'manage_options',
488
+				'noheader'   => true,
489
+			],
490
+			'generate_now'                     => [
491
+				'func'       => '_generate_now',
492
+				'capability' => 'ee_send_message',
493
+				'noheader'   => true,
494
+			],
495
+			'generate_and_send_now'            => [
496
+				'func'       => '_generate_and_send_now',
497
+				'capability' => 'ee_send_message',
498
+				'noheader'   => true,
499
+			],
500
+			'queue_for_resending'              => [
501
+				'func'       => '_queue_for_resending',
502
+				'capability' => 'ee_send_message',
503
+				'noheader'   => true,
504
+			],
505
+			'send_now'                         => [
506
+				'func'       => '_send_now',
507
+				'capability' => 'ee_send_message',
508
+				'noheader'   => true,
509
+			],
510
+			'delete_ee_message'                => [
511
+				'func'       => '_delete_ee_messages',
512
+				'capability' => 'ee_delete_messages',
513
+				'noheader'   => true,
514
+			],
515
+			'delete_ee_messages'               => [
516
+				'func'       => '_delete_ee_messages',
517
+				'capability' => 'ee_delete_messages',
518
+				'noheader'   => true,
519
+				'obj_id'     => $MSG_ID,
520
+			],
521
+		];
522
+	}
523
+
524
+
525
+	protected function _set_page_config()
526
+	{
527
+		$this->_page_config = [
528
+			'default'                  => [
529
+				'nav'           => [
530
+					'label' => esc_html__('Message Activity', 'event_espresso'),
531
+					'order' => 10,
532
+				],
533
+				'list_table'    => 'EE_Message_List_Table',
534
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
535
+				'require_nonce' => false,
536
+			],
537
+			'global_mtps'              => [
538
+				'nav'           => [
539
+					'label' => esc_html__('Default Message Templates', 'event_espresso'),
540
+					'order' => 20,
541
+				],
542
+				'list_table'    => 'Messages_Template_List_Table',
543
+				'help_tabs'     => [
544
+					'messages_overview_help_tab'                                => [
545
+						'title'    => esc_html__('Messages Overview', 'event_espresso'),
546
+						'filename' => 'messages_overview',
547
+					],
548
+					'messages_overview_messages_table_column_headings_help_tab' => [
549
+						'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
550
+						'filename' => 'messages_overview_table_column_headings',
551
+					],
552
+					'messages_overview_messages_filters_help_tab'               => [
553
+						'title'    => esc_html__('Message Filters', 'event_espresso'),
554
+						'filename' => 'messages_overview_filters',
555
+					],
556
+					'messages_overview_messages_views_help_tab'                 => [
557
+						'title'    => esc_html__('Message Views', 'event_espresso'),
558
+						'filename' => 'messages_overview_views',
559
+					],
560
+					'message_overview_message_types_help_tab'                   => [
561
+						'title'    => esc_html__('Message Types', 'event_espresso'),
562
+						'filename' => 'messages_overview_types',
563
+					],
564
+					'messages_overview_messengers_help_tab'                     => [
565
+						'title'    => esc_html__('Messengers', 'event_espresso'),
566
+						'filename' => 'messages_overview_messengers',
567
+					],
568
+				],
569
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
570
+				// 'help_tour'     => array('Messages_Overview_Help_Tour'),
571
+				'require_nonce' => false,
572
+			],
573
+			'custom_mtps'              => [
574
+				'nav'           => [
575
+					'label' => esc_html__('Custom Message Templates', 'event_espresso'),
576
+					'order' => 30,
577
+				],
578
+				'help_tabs'     => [],
579
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
580
+				// 'help_tour'     => array(),
581
+				'require_nonce' => false,
582
+			],
583
+			'add_new_message_template' => [
584
+				'nav'           => [
585
+					'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
586
+					'order'      => 5,
587
+					'persistent' => false,
588
+				],
589
+				'require_nonce' => false,
590
+			],
591
+			'edit_message_template'    => [
592
+				'labels'        => [
593
+					'buttons'    => [
594
+						'reset' => esc_html__('Reset Templates', 'event_espresso'),
595
+					],
596
+					'publishbox' => esc_html__('Update Actions', 'event_espresso'),
597
+				],
598
+				'nav'           => [
599
+					'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
600
+					'order'      => 5,
601
+					'persistent' => false,
602
+					'url'        => '',
603
+				],
604
+				'metaboxes'     => ['_publish_post_box', '_register_edit_meta_boxes'],
605
+				'has_metaboxes' => true,
606
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
607
+				// 'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
608
+				'help_tabs'     => [
609
+					'edit_message_template'            => [
610
+						'title'    => esc_html__('Message Template Editor', 'event_espresso'),
611
+						'callback' => 'edit_message_template_help_tab',
612
+					],
613
+					'message_templates_help_tab'       => [
614
+						'title'    => esc_html__('Message Templates', 'event_espresso'),
615
+						'filename' => 'messages_templates',
616
+					],
617
+					'message_template_shortcodes'      => [
618
+						'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
619
+						'callback' => 'message_template_shortcodes_help_tab',
620
+					],
621
+					'message_preview_help_tab'         => [
622
+						'title'    => esc_html__('Message Preview', 'event_espresso'),
623
+						'filename' => 'messages_preview',
624
+					],
625
+					'messages_overview_other_help_tab' => [
626
+						'title'    => esc_html__('Messages Other', 'event_espresso'),
627
+						'filename' => 'messages_overview_other',
628
+					],
629
+				],
630
+				'require_nonce' => false,
631
+			],
632
+			'display_preview_message'  => [
633
+				'nav'           => [
634
+					'label'      => esc_html__('Message Preview', 'event_espresso'),
635
+					'order'      => 5,
636
+					'url'        => '',
637
+					'persistent' => false,
638
+				],
639
+				'help_tabs'     => [
640
+					'preview_message' => [
641
+						'title'    => esc_html__('About Previews', 'event_espresso'),
642
+						'callback' => 'preview_message_help_tab',
643
+					],
644
+				],
645
+				'require_nonce' => false,
646
+			],
647
+			'settings'                 => [
648
+				'nav'           => [
649
+					'label' => esc_html__('Settings', 'event_espresso'),
650
+					'order' => 40,
651
+				],
652
+				'metaboxes'     => ['_messages_settings_metaboxes'],
653
+				'help_tabs'     => [
654
+					'messages_settings_help_tab'               => [
655
+						'title'    => esc_html__('Messages Settings', 'event_espresso'),
656
+						'filename' => 'messages_settings',
657
+					],
658
+					'messages_settings_message_types_help_tab' => [
659
+						'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
660
+						'filename' => 'messages_settings_message_types',
661
+					],
662
+					'messages_settings_messengers_help_tab'    => [
663
+						'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
664
+						'filename' => 'messages_settings_messengers',
665
+					],
666
+				],
667
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
668
+				// 'help_tour'     => array('Messages_Settings_Help_Tour'),
669
+				'require_nonce' => false,
670
+			],
671
+		];
672
+	}
673
+
674
+
675
+	protected function _add_screen_options()
676
+	{
677
+		// todo
678
+	}
679
+
680
+
681
+	protected function _add_screen_options_global_mtps()
682
+	{
683
+		/**
684
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
685
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
686
+		 */
687
+		$page_title              = $this->_admin_page_title;
688
+		$this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
689
+		$this->_per_page_screen_option();
690
+		$this->_admin_page_title = $page_title;
691
+	}
692
+
693
+
694
+	protected function _add_screen_options_default()
695
+	{
696
+		$this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
697
+		$this->_per_page_screen_option();
698
+	}
699
+
700
+
701
+	// none of the below group are currently used for Messages
702
+	protected function _add_feature_pointers()
703
+	{
704
+	}
705
+
706
+
707
+	public function admin_init()
708
+	{
709
+	}
710
+
711
+
712
+	public function admin_notices()
713
+	{
714
+	}
715
+
716
+
717
+	public function admin_footer_scripts()
718
+	{
719
+	}
720
+
721
+
722
+	public function messages_help_tab()
723
+	{
724
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
725
+	}
726
+
727
+
728
+	public function messengers_help_tab()
729
+	{
730
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
731
+	}
732
+
733
+
734
+	public function message_types_help_tab()
735
+	{
736
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
737
+	}
738
+
739
+
740
+	public function messages_overview_help_tab()
741
+	{
742
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
743
+	}
744
+
745
+
746
+	public function message_templates_help_tab()
747
+	{
748
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
749
+	}
750
+
751
+
752
+	public function edit_message_template_help_tab()
753
+	{
754
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
755
+						. esc_attr__('Editor Title', 'event_espresso')
756
+						. '" />';
757
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
758
+						. esc_attr__('Context Switcher and Preview', 'event_espresso')
759
+						. '" />';
760
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
761
+						. esc_attr__('Message Template Form Fields', 'event_espresso')
762
+						. '" />';
763
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
764
+						. esc_attr__('Shortcodes Metabox', 'event_espresso')
765
+						. '" />';
766
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
767
+						. esc_attr__('Publish Metabox', 'event_espresso')
768
+						. '" />';
769
+		EEH_Template::display_template(
770
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
771
+			$args
772
+		);
773
+	}
774
+
775
+
776
+	/**
777
+	 * @throws ReflectionException
778
+	 * @throws EE_Error
779
+	 */
780
+	public function message_template_shortcodes_help_tab()
781
+	{
782
+		$this->_set_shortcodes();
783
+		$args['shortcodes'] = $this->_shortcodes;
784
+		EEH_Template::display_template(
785
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
786
+			$args
787
+		);
788
+	}
789
+
790
+
791
+	public function preview_message_help_tab()
792
+	{
793
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
794
+	}
795
+
796
+
797
+	public function settings_help_tab()
798
+	{
799
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
800
+						. '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
801
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
802
+						. '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
803
+		$args['img3'] = '<div class="switch">'
804
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
805
+						. ' type="checkbox" checked="checked">'
806
+						. '<label for="ee-on-off-toggle-on"></label>'
807
+						. '</div>';
808
+		$args['img4'] = '<div class="switch">'
809
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
810
+						. ' type="checkbox">'
811
+						. '<label for="ee-on-off-toggle-on"></label>'
812
+						. '</div>';
813
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
814
+	}
815
+
816
+
817
+	public function load_scripts_styles()
818
+	{
819
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
820
+		wp_enqueue_style('espresso_ee_msg');
821
+
822
+		wp_register_script(
823
+			'ee-messages-settings',
824
+			EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
825
+			['jquery-ui-droppable', 'ee-serialize-full-array'],
826
+			EVENT_ESPRESSO_VERSION,
827
+			true
828
+		);
829
+		wp_register_script(
830
+			'ee-msg-list-table-js',
831
+			EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
832
+			['ee-dialog'],
833
+			EVENT_ESPRESSO_VERSION
834
+		);
835
+	}
836
+
837
+
838
+	public function load_scripts_styles_default()
839
+	{
840
+		wp_enqueue_script('ee-msg-list-table-js');
841
+	}
842
+
843
+
844
+	public function wp_editor_css($mce_css)
845
+	{
846
+		// if we're on the edit_message_template route
847
+		if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
848
+			$message_type_name = $this->_active_message_type_name;
849
+
850
+			// we're going to REPLACE the existing mce css
851
+			// we need to get the css file location from the active messenger
852
+			$mce_css = $this->_active_messenger->get_variation(
853
+				$this->_template_pack,
854
+				$message_type_name,
855
+				true,
856
+				'wpeditor',
857
+				$this->_variation
858
+			);
859
+		}
860
+
861
+		return $mce_css;
862
+	}
863
+
864
+
865
+	/**
866
+	 * @throws EE_Error
867
+	 * @throws ReflectionException
868
+	 */
869
+	public function load_scripts_styles_edit_message_template()
870
+	{
871
+
872
+		$this->_set_shortcodes();
873
+
874
+		EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
875
+			esc_html__(
876
+				'Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
877
+				'event_espresso'
878
+			),
879
+			$this->_message_template_group->messenger_obj()->label['singular'],
880
+			$this->_message_template_group->message_type_obj()->label['singular']
881
+		);
882
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
883
+			'Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
884
+			'event_espresso'
885
+		);
886
+		EE_Registry::$i18n_js_strings['server_error']                 = esc_html__(
887
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
888
+			'event_espresso'
889
+		);
890
+
891
+		wp_register_script(
892
+			'ee_msgs_edit_js',
893
+			EE_MSG_ASSETS_URL . 'ee_message_editor.js',
894
+			['jquery'],
895
+			EVENT_ESPRESSO_VERSION
896
+		);
897
+
898
+		wp_enqueue_script('ee_admin_js');
899
+		wp_enqueue_script('ee_msgs_edit_js');
900
+
901
+		// add in special css for tiny_mce
902
+		add_filter('mce_css', [$this, 'wp_editor_css']);
903
+	}
904
+
905
+
906
+	/**
907
+	 * @throws EE_Error
908
+	 * @throws ReflectionException
909
+	 */
910
+	public function load_scripts_styles_display_preview_message()
911
+	{
912
+		$this->_set_message_template_group();
913
+		if ($this->_active_messenger_name) {
914
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
915
+				$this->_active_messenger_name
916
+			);
917
+		}
918
+
919
+		wp_enqueue_style(
920
+			'espresso_preview_css',
921
+			$this->_active_messenger->get_variation(
922
+				$this->_template_pack,
923
+				$this->_active_message_type_name,
924
+				true,
925
+				'preview',
926
+				$this->_variation
927
+			)
928
+		);
929
+	}
930
+
931
+
932
+	public function load_scripts_styles_settings()
933
+	{
934
+		wp_register_style(
935
+			'ee-message-settings',
936
+			EE_MSG_ASSETS_URL . 'ee_message_settings.css',
937
+			[],
938
+			EVENT_ESPRESSO_VERSION
939
+		);
940
+		wp_enqueue_style('ee-text-links');
941
+		wp_enqueue_style('ee-message-settings');
942
+		wp_enqueue_script('ee-messages-settings');
943
+	}
944
+
945
+
946
+	/**
947
+	 * set views array for List Table
948
+	 */
949
+	public function _set_list_table_views_global_mtps()
950
+	{
951
+		$this->_views = [
952
+			'in_use' => [
953
+				'slug'  => 'in_use',
954
+				'label' => esc_html__('In Use', 'event_espresso'),
955
+				'count' => 0,
956
+			],
957
+		];
958
+	}
959
+
960
+
961
+	/**
962
+	 * Set views array for the Custom Template List Table
963
+	 */
964
+	public function _set_list_table_views_custom_mtps()
965
+	{
966
+		$this->_set_list_table_views_global_mtps();
967
+		$this->_views['in_use']['bulk_action'] = [
968
+			'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
969
+		];
970
+	}
971
+
972
+
973
+	/**
974
+	 * set views array for message queue list table
975
+	 *
976
+	 * @throws InvalidDataTypeException
977
+	 * @throws InvalidInterfaceException
978
+	 * @throws InvalidArgumentException
979
+	 * @throws EE_Error
980
+	 * @throws ReflectionException
981
+	 */
982
+	public function _set_list_table_views_default()
983
+	{
984
+		EE_Registry::instance()->load_helper('Template');
985
+
986
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
987
+			'ee_send_message',
988
+			'message_list_table_bulk_actions'
989
+		)
990
+			? [
991
+				'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
992
+				'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
993
+				'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
994
+				'send_now'              => esc_html__('Send Now', 'event_espresso'),
995
+			]
996
+			: [];
997
+
998
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
999
+			'ee_delete_messages',
1000
+			'message_list_table_bulk_actions'
1001
+		)
1002
+			? ['delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso')]
1003
+			: [];
1004
+
1005
+
1006
+		$this->_views = [
1007
+			'all' => [
1008
+				'slug'        => 'all',
1009
+				'label'       => esc_html__('All', 'event_espresso'),
1010
+				'count'       => 0,
1011
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
1012
+			],
1013
+		];
1014
+
1015
+
1016
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
1017
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
1018
+				continue;
1019
+			}
1020
+			$status_bulk_actions = $common_bulk_actions;
1021
+			// unset bulk actions not applying to status
1022
+			if (! empty($status_bulk_actions)) {
1023
+				switch ($status) {
1024
+					case EEM_Message::status_idle:
1025
+					case EEM_Message::status_resend:
1026
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1027
+						break;
1028
+
1029
+					case EEM_Message::status_failed:
1030
+					case EEM_Message::status_debug_only:
1031
+					case EEM_Message::status_messenger_executing:
1032
+						$status_bulk_actions = [];
1033
+						break;
1034
+
1035
+					case EEM_Message::status_incomplete:
1036
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1037
+						break;
1038
+
1039
+					case EEM_Message::status_retry:
1040
+					case EEM_Message::status_sent:
1041
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1042
+						break;
1043
+				}
1044
+			}
1045
+
1046
+			// skip adding messenger executing status to views because it will be included with the Failed view.
1047
+			if ($status === EEM_Message::status_messenger_executing) {
1048
+				continue;
1049
+			}
1050
+
1051
+			$this->_views[ strtolower($status) ] = [
1052
+				'slug'        => strtolower($status),
1053
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1054
+				'count'       => 0,
1055
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1056
+			];
1057
+		}
1058
+	}
1059
+
1060
+
1061
+	/**
1062
+	 * @throws EE_Error
1063
+	 */
1064
+	protected function _ee_default_messages_overview_list_table()
1065
+	{
1066
+		$this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1067
+		$this->display_admin_list_table_page_with_no_sidebar();
1068
+	}
1069
+
1070
+
1071
+	/**
1072
+	 * @throws EE_Error
1073
+	 * @throws ReflectionException
1074
+	 */
1075
+	protected function _message_queue_list_table()
1076
+	{
1077
+		$this->_search_btn_label                   = esc_html__('Message Activity', 'event_espresso');
1078
+		$this->_template_args['per_column']        = 6;
1079
+		$this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
1080
+		$this->_template_args['before_list_table'] = '<h3>'
1081
+													 . EEM_Message::instance()->get_pretty_label_for_results()
1082
+													 . '</h3>';
1083
+		$this->display_admin_list_table_page_with_no_sidebar();
1084
+	}
1085
+
1086
+
1087
+	/**
1088
+	 * @throws EE_Error
1089
+	 */
1090
+	protected function _message_legend_items()
1091
+	{
1092
+
1093
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
1094
+		$action_items       = [];
1095
+
1096
+		foreach ($action_css_classes as $action_item => $action_details) {
1097
+			if ($action_item === 'see_notifications_for') {
1098
+				continue;
1099
+			}
1100
+			$action_items[ $action_item ] = [
1101
+				'class' => $action_details['css_class'],
1102
+				'desc'  => $action_details['label'],
1103
+			];
1104
+		}
1105
+
1106
+		/** @var array $status_items status legend setup */
1107
+		$status_items = [
1108
+			'sent_status'                => [
1109
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1110
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1111
+			],
1112
+			'idle_status'                => [
1113
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1114
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1115
+			],
1116
+			'failed_status'              => [
1117
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1118
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1119
+			],
1120
+			'messenger_executing_status' => [
1121
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1122
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1123
+			],
1124
+			'resend_status'              => [
1125
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1126
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1127
+			],
1128
+			'incomplete_status'          => [
1129
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1130
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1131
+			],
1132
+			'retry_status'               => [
1133
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1134
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1135
+			],
1136
+		];
1137
+		if (EEM_Message::debug()) {
1138
+			$status_items['debug_only_status'] = [
1139
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1140
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1141
+			];
1142
+		}
1143
+
1144
+		return array_merge($action_items, $status_items);
1145
+	}
1146
+
1147
+
1148
+	/**
1149
+	 * @throws EE_Error
1150
+	 */
1151
+	protected function _custom_mtps_preview()
1152
+	{
1153
+		$this->_admin_page_title              = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1154
+		$this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1155
+												. ' alt="' . esc_attr__(
1156
+													'Preview Custom Message Templates screenshot',
1157
+													'event_espresso'
1158
+												) . '" />';
1159
+		$this->_template_args['preview_text'] = '<strong>'
1160
+												. esc_html__(
1161
+													'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1162
+													'event_espresso'
1163
+												)
1164
+												. '</strong>';
1165
+
1166
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1167
+	}
1168
+
1169
+
1170
+	/**
1171
+	 * get_message_templates
1172
+	 * This gets all the message templates for listing on the overview list.
1173
+	 *
1174
+	 * @access public
1175
+	 * @param int    $per_page the amount of templates groups to show per page
1176
+	 * @param string $type     the current _view we're getting templates for
1177
+	 * @param bool   $count    return count?
1178
+	 * @param bool   $all      disregard any paging info (get all data);
1179
+	 * @param bool   $global   whether to return just global (true) or custom templates (false)
1180
+	 * @return array
1181
+	 * @throws EE_Error
1182
+	 * @throws InvalidArgumentException
1183
+	 * @throws InvalidDataTypeException
1184
+	 * @throws InvalidInterfaceException
1185
+	 */
1186
+	public function get_message_templates(
1187
+		$per_page = 10,
1188
+		$type = 'in_use',
1189
+		$count = false,
1190
+		$all = false,
1191
+		$global = true
1192
+	) {
1193
+
1194
+		$MTP = EEM_Message_Template_Group::instance();
1195
+
1196
+		$orderby = $this->request->getRequestParam('orderby', 'GRP_ID');
1197
+		$this->request->setRequestParam('orderby', $orderby);
1198
+
1199
+		$order        = $this->request->getRequestParam('order', 'ASC');
1200
+		$current_page = $this->request->getRequestParam('paged', 1, 'int');
1201
+		$per_page     = $this->request->getRequestParam('perpage', $per_page, 'int');
1202
+
1203
+		$offset = ($current_page - 1) * $per_page;
1204
+		$limit  = $all ? null : [$offset, $per_page];
1205
+
1206
+		// options will match what is in the _views array property
1207
+		switch ($type) {
1208
+			case 'in_use':
1209
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1210
+				break;
1211
+			default:
1212
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1213
+		}
1214
+
1215
+		return $templates;
1216
+	}
1217
+
1218
+
1219
+	/**
1220
+	 * filters etc might need a list of installed message_types
1221
+	 *
1222
+	 * @return array an array of message type objects
1223
+	 */
1224
+	public function get_installed_message_types()
1225
+	{
1226
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1227
+		$installed               = [];
1228
+
1229
+		foreach ($installed_message_types as $message_type) {
1230
+			$installed[ $message_type->name ] = $message_type;
1231
+		}
1232
+
1233
+		return $installed;
1234
+	}
1235
+
1236
+
1237
+	/**
1238
+	 * _add_message_template
1239
+	 *
1240
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1241
+	 *
1242
+	 * @param string $message_type
1243
+	 * @param string $messenger
1244
+	 * @param string $GRP_ID
1245
+	 *
1246
+	 * @throws EE_error
1247
+	 * @throws ReflectionException
1248
+	 */
1249
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1250
+	{
1251
+		// set values override any request data
1252
+		$message_type = ! empty($message_type) ? $message_type : $this->_active_message_type_name;
1253
+		$messenger    = ! empty($messenger) ? $messenger : $this->_active_messenger_name;
1254
+		$GRP_ID       = ! empty($GRP_ID) ? $GRP_ID : $this->request->getRequestParam('GRP_ID', 0, 'int');
1255
+
1256
+		// we need messenger and message type.  They should be coming from the event editor. If not here then return error
1257
+		if (empty($message_type) || empty($messenger)) {
1258
+			throw new EE_Error(
1259
+				esc_html__(
1260
+					'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1261
+					'event_espresso'
1262
+				)
1263
+			);
1264
+		}
1265
+
1266
+		// we need the GRP_ID for the template being used as the base for the new template
1267
+		if (empty($GRP_ID)) {
1268
+			throw new EE_Error(
1269
+				esc_html__(
1270
+					'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1271
+					'event_espresso'
1272
+				)
1273
+			);
1274
+		}
1275
+
1276
+		// let's just make sure the template gets generated!
1277
+
1278
+		// we need to reassign some variables for what the insert is expecting
1279
+		$this->request->setRequestParam('MTP_messenger', $messenger);
1280
+		$this->request->setRequestParam('MTP_message_type', $message_type);
1281
+		$this->request->setRequestParam('GRP_ID', $GRP_ID);
1282
+
1283
+		$this->_insert_or_update_message_template(true);
1284
+	}
1285
+
1286
+
1287
+	/**
1288
+	 * public wrapper for the _add_message_template method
1289
+	 *
1290
+	 * @param string $message_type     message type slug
1291
+	 * @param string $messenger        messenger slug
1292
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1293
+	 *                                 off of.
1294
+	 * @throws EE_error
1295
+	 * @throws ReflectionException
1296
+	 */
1297
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1298
+	{
1299
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1300
+	}
1301
+
1302
+
1303
+	/**
1304
+	 * _edit_message_template
1305
+	 *
1306
+	 * @access protected
1307
+	 * @return void
1308
+	 * @throws InvalidIdentifierException
1309
+	 * @throws DomainException
1310
+	 * @throws EE_Error
1311
+	 * @throws InvalidArgumentException
1312
+	 * @throws ReflectionException
1313
+	 * @throws InvalidDataTypeException
1314
+	 * @throws InvalidInterfaceException
1315
+	 */
1316
+	protected function _edit_message_template()
1317
+	{
1318
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1319
+		$template_fields = '';
1320
+		$sidebar_fields  = '';
1321
+		// we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1322
+		// valid html in the templates.
1323
+		add_filter('tiny_mce_before_init', [$this, 'filter_tinymce_init'], 10, 2);
1324
+
1325
+		$GRP_ID = $this->request->getRequestParam('id', 0, 'int');
1326
+		$EVT_ID = $this->request->getRequestParam('evt_id', 0, 'int');
1327
+
1328
+		$this->_set_shortcodes(); // this also sets the _message_template property.
1329
+		$message_template_group = $this->_message_template_group;
1330
+		$c_label                = $message_template_group->context_label();
1331
+		$c_config               = $message_template_group->contexts_config();
1332
+
1333
+		reset($c_config);
1334
+		$context = $this->request->getRequestParam('context', key($c_config));
1335
+		$context = strtolower($context);
1336
+
1337
+		$action = empty($GRP_ID) ? 'insert_message_template' : 'update_message_template';
1338
+
1339
+		$edit_message_template_form_url = add_query_arg(
1340
+			['action' => $action, 'noheader' => true],
1341
+			EE_MSG_ADMIN_URL
1342
+		);
1343
+
1344
+		// set active messenger for this view
1345
+		$this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1346
+			$message_template_group->messenger()
1347
+		);
1348
+		$this->_active_message_type_name = $message_template_group->message_type();
1349
+
1350
+
1351
+		// Do we have any validation errors?
1352
+		$validators = $this->_get_transient();
1353
+		$v_fields   = ! empty($validators) ? array_keys($validators) : [];
1354
+
1355
+
1356
+		// we need to assemble the title from Various details
1357
+		$context_label = sprintf(
1358
+			esc_html__('(%s %s)', 'event_espresso'),
1359
+			$c_config[ $context ]['label'],
1360
+			ucwords($c_label['label'])
1361
+		);
1362
+
1363
+		$title = sprintf(
1364
+			esc_html__(' %s %s Template %s', 'event_espresso'),
1365
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1366
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1367
+			$context_label
1368
+		);
1369
+
1370
+		$this->_template_args['GRP_ID']           = $GRP_ID;
1371
+		$this->_template_args['message_template'] = $message_template_group;
1372
+		$this->_template_args['is_extra_fields']  = false;
1373
+
1374
+
1375
+		// let's get EEH_MSG_Template so we can get template form fields
1376
+		$template_field_structure = EEH_MSG_Template::get_fields(
1377
+			$message_template_group->messenger(),
1378
+			$message_template_group->message_type()
1379
+		);
1380
+
1381
+		if (! $template_field_structure) {
1382
+			$template_field_structure = false;
1383
+			$template_fields          = esc_html__(
1384
+				'There was an error in assembling the fields for this display (you should see an error message)',
1385
+				'event_espresso'
1386
+			);
1387
+		}
1388
+
1389
+
1390
+		$message_templates = $message_template_group->context_templates();
1391
+
1392
+
1393
+		// if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1394
+		// will get handled in the "extra" array.
1395
+		if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1396
+			foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1397
+				unset($template_field_structure[ $context ][ $reference_field ]);
1398
+			}
1399
+		}
1400
+
1401
+		// let's loop through the template_field_structure and actually assemble the input fields!
1402
+		if (! empty($template_field_structure)) {
1403
+			foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1404
+				// if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1405
+				// the extra array and reset them.
1406
+				if ($template_field === 'extra') {
1407
+					$this->_template_args['is_extra_fields'] = true;
1408
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1409
+						$message_template = $message_templates[ $context ][ $reference_field ];
1410
+						$content          = $message_template instanceof EE_Message_Template
1411
+							? $message_template->get('MTP_content')
1412
+							: '';
1413
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1414
+							// let's verify if we need this extra field via the shortcodes parameter.
1415
+							$continue = false;
1416
+							if (isset($extra_array['shortcodes_required'])) {
1417
+								foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1418
+									if (! array_key_exists($shortcode, $this->_shortcodes)) {
1419
+										$continue = true;
1420
+									}
1421
+								}
1422
+								if ($continue) {
1423
+									continue;
1424
+								}
1425
+							}
1426
+
1427
+							$field_id                                  = $reference_field
1428
+																		 . '-'
1429
+																		 . $extra_field
1430
+																		 . '-content';
1431
+							$template_form_fields[ $field_id ]         = $extra_array;
1432
+							$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1433
+																		 . $reference_field
1434
+																		 . '][content]['
1435
+																		 . $extra_field . ']';
1436
+							$css_class                                 = isset($extra_array['css_class'])
1437
+								? $extra_array['css_class']
1438
+								: '';
1439
+
1440
+							$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1441
+																			  && in_array($extra_field, $v_fields, true)
1442
+																			  && (
1443
+																				  is_array($validators[ $extra_field ])
1444
+																				  && isset($validators[ $extra_field ]['msg'])
1445
+																			  )
1446
+								? 'validate-error ' . $css_class
1447
+								: $css_class;
1448
+
1449
+							$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1450
+																		  && isset($content[ $extra_field ])
1451
+								? $content[ $extra_field ]
1452
+								: '';
1453
+
1454
+							// do we have a validation error?  if we do then let's use that value instead
1455
+							$template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1456
+								? $validators[ $extra_field ]['value']
1457
+								: $template_form_fields[ $field_id ]['value'];
1458
+
1459
+
1460
+							$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1461
+
1462
+							// shortcode selector
1463
+							$field_name_to_use                                   = $extra_field === 'main'
1464
+								? 'content'
1465
+								: $extra_field;
1466
+							$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1467
+								$field_name_to_use,
1468
+								$field_id
1469
+							);
1470
+						}
1471
+						$template_field_MTP_id           = $reference_field . '-MTP_ID';
1472
+						$template_field_template_name_id = $reference_field . '-name';
1473
+
1474
+						$template_form_fields[ $template_field_MTP_id ] = [
1475
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1476
+							'label'      => null,
1477
+							'input'      => 'hidden',
1478
+							'type'       => 'int',
1479
+							'required'   => false,
1480
+							'validation' => false,
1481
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1482
+							'css_class'  => '',
1483
+							'format'     => '%d',
1484
+							'db-col'     => 'MTP_ID',
1485
+						];
1486
+
1487
+						$template_form_fields[ $template_field_template_name_id ] = [
1488
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1489
+							'label'      => null,
1490
+							'input'      => 'hidden',
1491
+							'type'       => 'string',
1492
+							'required'   => false,
1493
+							'validation' => true,
1494
+							'value'      => $reference_field,
1495
+							'css_class'  => '',
1496
+							'format'     => '%s',
1497
+							'db-col'     => 'MTP_template_field',
1498
+						];
1499
+					}
1500
+					continue; // skip the next stuff, we got the necessary fields here for this dataset.
1501
+				} else {
1502
+					$field_id                                   = $template_field . '-content';
1503
+					$template_form_fields[ $field_id ]          = $field_setup_array;
1504
+					$template_form_fields[ $field_id ]['name']  =
1505
+						'MTP_template_fields[' . $template_field . '][content]';
1506
+					$message_template                           =
1507
+						isset($message_templates[ $context ][ $template_field ])
1508
+							? $message_templates[ $context ][ $template_field ]
1509
+							: null;
1510
+					$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1511
+																  && is_array($message_templates[ $context ])
1512
+																  && $message_template instanceof EE_Message_Template
1513
+						? $message_template->get('MTP_content')
1514
+						: '';
1515
+
1516
+					// do we have a validator error for this field?  if we do then we'll use that value instead
1517
+					$template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1518
+						? $validators[ $template_field ]['value']
1519
+						: $template_form_fields[ $field_id ]['value'];
1520
+
1521
+
1522
+					$template_form_fields[ $field_id ]['db-col']    = 'MTP_content';
1523
+					$css_class                                      = isset($field_setup_array['css_class'])
1524
+						? $field_setup_array['css_class']
1525
+						: '';
1526
+					$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1527
+																	  && in_array($template_field, $v_fields, true)
1528
+																	  && isset($validators[ $template_field ]['msg'])
1529
+						? 'validate-error ' . $css_class
1530
+						: $css_class;
1531
+
1532
+					// shortcode selector
1533
+					$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1534
+						$template_field,
1535
+						$field_id
1536
+					);
1537
+				}
1538
+
1539
+				// k took care of content field(s) now let's take care of others.
1540
+
1541
+				$template_field_MTP_id                 = $template_field . '-MTP_ID';
1542
+				$template_field_field_template_name_id = $template_field . '-name';
1543
+
1544
+				// foreach template field there are actually two form fields created
1545
+				$template_form_fields[ $template_field_MTP_id ] = [
1546
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1547
+					'label'      => null,
1548
+					'input'      => 'hidden',
1549
+					'type'       => 'int',
1550
+					'required'   => false,
1551
+					'validation' => true,
1552
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1553
+					'css_class'  => '',
1554
+					'format'     => '%d',
1555
+					'db-col'     => 'MTP_ID',
1556
+				];
1557
+
1558
+				$template_form_fields[ $template_field_field_template_name_id ] = [
1559
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1560
+					'label'      => null,
1561
+					'input'      => 'hidden',
1562
+					'type'       => 'string',
1563
+					'required'   => false,
1564
+					'validation' => true,
1565
+					'value'      => $template_field,
1566
+					'css_class'  => '',
1567
+					'format'     => '%s',
1568
+					'db-col'     => 'MTP_template_field',
1569
+				];
1570
+			}
1571
+
1572
+			// add other fields
1573
+			$template_form_fields['ee-msg-current-context'] = [
1574
+				'name'       => 'MTP_context',
1575
+				'label'      => null,
1576
+				'input'      => 'hidden',
1577
+				'type'       => 'string',
1578
+				'required'   => false,
1579
+				'validation' => true,
1580
+				'value'      => $context,
1581
+				'css_class'  => '',
1582
+				'format'     => '%s',
1583
+				'db-col'     => 'MTP_context',
1584
+			];
1585
+
1586
+			$template_form_fields['ee-msg-grp-id'] = [
1587
+				'name'       => 'GRP_ID',
1588
+				'label'      => null,
1589
+				'input'      => 'hidden',
1590
+				'type'       => 'int',
1591
+				'required'   => false,
1592
+				'validation' => true,
1593
+				'value'      => $GRP_ID,
1594
+				'css_class'  => '',
1595
+				'format'     => '%d',
1596
+				'db-col'     => 'GRP_ID',
1597
+			];
1598
+
1599
+			$template_form_fields['ee-msg-messenger'] = [
1600
+				'name'       => 'MTP_messenger',
1601
+				'label'      => null,
1602
+				'input'      => 'hidden',
1603
+				'type'       => 'string',
1604
+				'required'   => false,
1605
+				'validation' => true,
1606
+				'value'      => $message_template_group->messenger(),
1607
+				'css_class'  => '',
1608
+				'format'     => '%s',
1609
+				'db-col'     => 'MTP_messenger',
1610
+			];
1611
+
1612
+			$template_form_fields['ee-msg-message-type'] = [
1613
+				'name'       => 'MTP_message_type',
1614
+				'label'      => null,
1615
+				'input'      => 'hidden',
1616
+				'type'       => 'string',
1617
+				'required'   => false,
1618
+				'validation' => true,
1619
+				'value'      => $message_template_group->message_type(),
1620
+				'css_class'  => '',
1621
+				'format'     => '%s',
1622
+				'db-col'     => 'MTP_message_type',
1623
+			];
1624
+
1625
+			$sidebar_form_fields['ee-msg-is-global'] = [
1626
+				'name'       => 'MTP_is_global',
1627
+				'label'      => esc_html__('Global Template', 'event_espresso'),
1628
+				'input'      => 'hidden',
1629
+				'type'       => 'int',
1630
+				'required'   => false,
1631
+				'validation' => true,
1632
+				'value'      => $message_template_group->get('MTP_is_global'),
1633
+				'css_class'  => '',
1634
+				'format'     => '%d',
1635
+				'db-col'     => 'MTP_is_global',
1636
+			];
1637
+
1638
+			$sidebar_form_fields['ee-msg-is-override'] = [
1639
+				'name'       => 'MTP_is_override',
1640
+				'label'      => esc_html__('Override all custom', 'event_espresso'),
1641
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1642
+				'type'       => 'int',
1643
+				'required'   => false,
1644
+				'validation' => true,
1645
+				'value'      => $message_template_group->get('MTP_is_override'),
1646
+				'css_class'  => '',
1647
+				'format'     => '%d',
1648
+				'db-col'     => 'MTP_is_override',
1649
+			];
1650
+
1651
+			$sidebar_form_fields['ee-msg-is-active'] = [
1652
+				'name'       => 'MTP_is_active',
1653
+				'label'      => esc_html__('Active Template', 'event_espresso'),
1654
+				'input'      => 'hidden',
1655
+				'type'       => 'int',
1656
+				'required'   => false,
1657
+				'validation' => true,
1658
+				'value'      => $message_template_group->is_active(),
1659
+				'css_class'  => '',
1660
+				'format'     => '%d',
1661
+				'db-col'     => 'MTP_is_active',
1662
+			];
1663
+
1664
+			$sidebar_form_fields['ee-msg-deleted'] = [
1665
+				'name'       => 'MTP_deleted',
1666
+				'label'      => null,
1667
+				'input'      => 'hidden',
1668
+				'type'       => 'int',
1669
+				'required'   => false,
1670
+				'validation' => true,
1671
+				'value'      => $message_template_group->get('MTP_deleted'),
1672
+				'css_class'  => '',
1673
+				'format'     => '%d',
1674
+				'db-col'     => 'MTP_deleted',
1675
+			];
1676
+			$sidebar_form_fields['ee-msg-author']  = [
1677
+				'name'       => 'MTP_user_id',
1678
+				'label'      => esc_html__('Author', 'event_espresso'),
1679
+				'input'      => 'hidden',
1680
+				'type'       => 'int',
1681
+				'required'   => false,
1682
+				'validation' => false,
1683
+				'value'      => $message_template_group->user(),
1684
+				'format'     => '%d',
1685
+				'db-col'     => 'MTP_user_id',
1686
+			];
1687
+
1688
+			$sidebar_form_fields['ee-msg-route'] = [
1689
+				'name'  => 'action',
1690
+				'input' => 'hidden',
1691
+				'type'  => 'string',
1692
+				'value' => $action,
1693
+			];
1694
+
1695
+			$sidebar_form_fields['ee-msg-id']        = [
1696
+				'name'  => 'id',
1697
+				'input' => 'hidden',
1698
+				'type'  => 'int',
1699
+				'value' => $GRP_ID,
1700
+			];
1701
+			$sidebar_form_fields['ee-msg-evt-nonce'] = [
1702
+				'name'  => $action . '_nonce',
1703
+				'input' => 'hidden',
1704
+				'type'  => 'string',
1705
+				'value' => wp_create_nonce($action . '_nonce'),
1706
+			];
1707
+
1708
+			$template_switch = $this->request->getRequestParam('template_switch');
1709
+			if ($template_switch) {
1710
+				$sidebar_form_fields['ee-msg-template-switch'] = [
1711
+					'name'  => 'template_switch',
1712
+					'input' => 'hidden',
1713
+					'type'  => 'int',
1714
+					'value' => 1,
1715
+				];
1716
+			}
1717
+
1718
+
1719
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1720
+			$sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1721
+		} //end if ( !empty($template_field_structure) )
1722
+
1723
+		// set extra content for publish box
1724
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1725
+		$this->_set_publish_post_box_vars(
1726
+			'id',
1727
+			$GRP_ID,
1728
+			false,
1729
+			add_query_arg(
1730
+				['action' => 'global_mtps'],
1731
+				$this->_admin_base_url
1732
+			)
1733
+		);
1734
+
1735
+		// add preview button
1736
+		$preview_url    = parent::add_query_args_and_nonce(
1737
+			[
1738
+				'message_type' => $message_template_group->message_type(),
1739
+				'messenger'    => $message_template_group->messenger(),
1740
+				'context'      => $context,
1741
+				'GRP_ID'       => $GRP_ID,
1742
+				'evt_id'       => $EVT_ID,
1743
+				'action'       => 'preview_message',
1744
+			],
1745
+			$this->_admin_base_url
1746
+		);
1747
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1748
+						  . esc_html__('Preview', 'event_espresso')
1749
+						  . '</a>';
1750
+
1751
+
1752
+		// setup context switcher
1753
+		$context_switcher_args = [
1754
+			'page'    => 'espresso_messages',
1755
+			'action'  => 'edit_message_template',
1756
+			'id'      => $GRP_ID,
1757
+			'evt_id'  => $EVT_ID,
1758
+			'context' => $context,
1759
+			'extra'   => $preview_button,
1760
+		];
1761
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1762
+
1763
+
1764
+		// main box
1765
+		$this->_template_args['template_fields']                         = $template_fields;
1766
+		$this->_template_args['sidebar_box_id']                          = 'details';
1767
+		$this->_template_args['action']                                  = $action;
1768
+		$this->_template_args['context']                                 = $context;
1769
+		$this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1770
+		$this->_template_args['learn_more_about_message_templates_link'] =
1771
+			$this->_learn_more_about_message_templates_link();
1772
+
1773
+
1774
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1775
+		$this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1776
+			$message_template_group,
1777
+			$context,
1778
+			$context_label
1779
+		);
1780
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1781
+		$this->_template_args['after_admin_page_content']  = $this->_add_form_element_after();
1782
+
1783
+		$this->_template_path = $this->_template_args['GRP_ID']
1784
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1785
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1786
+
1787
+		// send along EE_Message_Template_Group object for further template use.
1788
+		$this->_template_args['MTP'] = $message_template_group;
1789
+
1790
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1791
+			$this->_template_path,
1792
+			$this->_template_args,
1793
+			true
1794
+		);
1795
+
1796
+
1797
+		// finally, let's set the admin_page title
1798
+		$this->_admin_page_title = sprintf(esc_html__('Editing %s', 'event_espresso'), $title);
1799
+
1800
+
1801
+		// we need to take care of setting the shortcodes property for use elsewhere.
1802
+		$this->_set_shortcodes();
1803
+
1804
+
1805
+		// final template wrapper
1806
+		$this->display_admin_page_with_sidebar();
1807
+	}
1808
+
1809
+
1810
+	public function filter_tinymce_init($mceInit, $editor_id)
1811
+	{
1812
+		return $mceInit;
1813
+	}
1814
+
1815
+
1816
+	public function add_context_switcher()
1817
+	{
1818
+		return $this->_context_switcher;
1819
+	}
1820
+
1821
+
1822
+	/**
1823
+	 * Adds the activation/deactivation toggle for the message template context.
1824
+	 *
1825
+	 * @param EE_Message_Template_Group $message_template_group
1826
+	 * @param string                    $context
1827
+	 * @param string                    $context_label
1828
+	 * @return string
1829
+	 * @throws DomainException
1830
+	 * @throws EE_Error
1831
+	 * @throws InvalidIdentifierException
1832
+	 * @throws ReflectionException
1833
+	 */
1834
+	protected function add_active_context_element(
1835
+		EE_Message_Template_Group $message_template_group,
1836
+		$context,
1837
+		$context_label
1838
+	) {
1839
+		$template_args = [
1840
+			'context'                   => $context,
1841
+			'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1842
+			'is_active'                 => $message_template_group->is_context_active($context),
1843
+			'on_off_action'             => $message_template_group->is_context_active($context)
1844
+				? 'context-off'
1845
+				: 'context-on',
1846
+			'context_label'             => str_replace(['(', ')'], '', $context_label),
1847
+			'message_template_group_id' => $message_template_group->ID(),
1848
+		];
1849
+		return EEH_Template::display_template(
1850
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1851
+			$template_args,
1852
+			true
1853
+		);
1854
+	}
1855
+
1856
+
1857
+	/**
1858
+	 * Ajax callback for `toggle_context_template` ajax action.
1859
+	 * Handles toggling the message context on or off.
1860
+	 *
1861
+	 * @throws EE_Error
1862
+	 * @throws InvalidArgumentException
1863
+	 * @throws InvalidDataTypeException
1864
+	 * @throws InvalidIdentifierException
1865
+	 * @throws InvalidInterfaceException
1866
+	 */
1867
+	public function toggle_context_template()
1868
+	{
1869
+		$success = true;
1870
+		// check for required data
1871
+		if (
1872
+			! (
1873
+				$this->request->requestParamIsSet('message_template_group_id')
1874
+				&& $this->request->requestParamIsSet('context')
1875
+				&& $this->request->requestParamIsSet('status')
1876
+			)
1877
+		) {
1878
+			EE_Error::add_error(
1879
+				esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1880
+				__FILE__,
1881
+				__FUNCTION__,
1882
+				__LINE__
1883
+			);
1884
+			$success = false;
1885
+		}
1886
+
1887
+		$nonce   = $this->request->getRequestParam('toggle_context_nonce', '');
1888
+		$context = $this->request->getRequestParam('context', '');
1889
+		$status  = $this->request->getRequestParam('status', '');
1890
+
1891
+		$this->_verify_nonce($nonce, "activate_{$context}_toggle_nonce");
1892
+
1893
+		if ($status !== 'off' && $status !== 'on') {
1894
+			EE_Error::add_error(
1895
+				sprintf(
1896
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1897
+					$status
1898
+				),
1899
+				__FILE__,
1900
+				__FUNCTION__,
1901
+				__LINE__
1902
+			);
1903
+			$success = false;
1904
+		}
1905
+		$message_template_group_id = $this->request->getRequestParam('message_template_group_id', 0, 'int');
1906
+		$message_template_group    = EEM_Message_Template_Group::instance()->get_one_by_ID($message_template_group_id);
1907
+		if (! $message_template_group instanceof EE_Message_Template_Group) {
1908
+			EE_Error::add_error(
1909
+				sprintf(
1910
+					esc_html__(
1911
+						'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1912
+						'event_espresso'
1913
+					),
1914
+					$message_template_group_id,
1915
+					'EE_Message_Template_Group'
1916
+				),
1917
+				__FILE__,
1918
+				__FUNCTION__,
1919
+				__LINE__
1920
+			);
1921
+			$success = false;
1922
+		}
1923
+		if ($success) {
1924
+			$success = $status === 'off'
1925
+				? $message_template_group->deactivate_context($context)
1926
+				: $message_template_group->activate_context($context);
1927
+		}
1928
+		$this->_template_args['success'] = $success;
1929
+		$this->_return_json();
1930
+	}
1931
+
1932
+
1933
+	public function _add_form_element_before()
1934
+	{
1935
+		return '<form method="post" action="'
1936
+			   . $this->_template_args['edit_message_template_form_url']
1937
+			   . '" id="ee-msg-edit-frm">';
1938
+	}
1939
+
1940
+
1941
+	public function _add_form_element_after()
1942
+	{
1943
+		return '</form>';
1944
+	}
1945
+
1946
+
1947
+	/**
1948
+	 * This executes switching the template pack for a message template.
1949
+	 *
1950
+	 * @throws EE_Error
1951
+	 * @throws InvalidDataTypeException
1952
+	 * @throws InvalidInterfaceException
1953
+	 * @throws InvalidArgumentException
1954
+	 * @throws ReflectionException
1955
+	 * @since 4.5.0
1956
+	 */
1957
+	public function switch_template_pack()
1958
+	{
1959
+
1960
+		$GRP_ID        = $this->request->getRequestParam('GRP_ID', 0, 'int');
1961
+		$template_pack = $this->request->getRequestParam('template_pack', '');
1962
+
1963
+		// verify we have needed values.
1964
+		if (empty($GRP_ID) || empty($template_pack)) {
1965
+			$this->_template_args['error'] = true;
1966
+			EE_Error::add_error(
1967
+				esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1968
+				__FILE__,
1969
+				__FUNCTION__,
1970
+				__LINE__
1971
+			);
1972
+		} else {
1973
+			// get template, set the new template_pack and then reset to default
1974
+			/** @var EE_Message_Template_Group $message_template_group */
1975
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1976
+
1977
+			$message_template_group->set_template_pack_name($template_pack);
1978
+			$this->request->setRequestParam('msgr', $message_template_group->messenger());
1979
+			$this->request->setRequestParam('mt', $message_template_group->message_type());
1980
+
1981
+			$query_args = $this->_reset_to_default_template();
1982
+
1983
+			if (empty($query_args['id'])) {
1984
+				EE_Error::add_error(
1985
+					esc_html__(
1986
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1987
+						'event_espresso'
1988
+					),
1989
+					__FILE__,
1990
+					__FUNCTION__,
1991
+					__LINE__
1992
+				);
1993
+				$this->_template_args['error'] = true;
1994
+			} else {
1995
+				$template_label       = $message_template_group->get_template_pack()->label;
1996
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1997
+				EE_Error::add_success(
1998
+					sprintf(
1999
+						esc_html__(
2000
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
2001
+							'event_espresso'
2002
+						),
2003
+						$template_label,
2004
+						$template_pack_labels->template_pack
2005
+					)
2006
+				);
2007
+				// generate the redirect url for js.
2008
+				$url = self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2009
+
2010
+				$this->_template_args['data']['redirect_url'] = $url;
2011
+				$this->_template_args['success']              = true;
2012
+			}
2013
+
2014
+			$this->_return_json();
2015
+		}
2016
+	}
2017
+
2018
+
2019
+	/**
2020
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2021
+	 * they want.
2022
+	 *
2023
+	 * @access protected
2024
+	 * @return array|void
2025
+	 * @throws EE_Error
2026
+	 * @throws InvalidArgumentException
2027
+	 * @throws InvalidDataTypeException
2028
+	 * @throws InvalidInterfaceException
2029
+	 * @throws ReflectionException
2030
+	 */
2031
+	protected function _reset_to_default_template()
2032
+	{
2033
+		$templates    = [];
2034
+		$GRP_ID       = $this->request->getRequestParam('GRP_ID', 0, 'int');
2035
+		$messenger    = $this->request->getRequestParam('msgr');
2036
+		$message_type = $this->request->getRequestParam('mt');
2037
+		// we need to make sure we've got the info we need.
2038
+		if (! ($GRP_ID && $messenger && $message_type)) {
2039
+			EE_Error::add_error(
2040
+				esc_html__(
2041
+					'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
2042
+					'event_espresso'
2043
+				),
2044
+				__FILE__,
2045
+				__FUNCTION__,
2046
+				__LINE__
2047
+			);
2048
+		}
2049
+
2050
+		// all templates will be reset to whatever the defaults are
2051
+		// for the global template matching the messenger and message type.
2052
+		$success = ! empty($GRP_ID);
2053
+
2054
+		if ($success) {
2055
+			// let's first determine if the incoming template is a global template,
2056
+			// if it isn't then we need to get the global template matching messenger and message type.
2057
+			// $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2058
+
2059
+
2060
+			// note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2061
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
2062
+
2063
+			if ($success) {
2064
+				// if successfully deleted, lets generate the new ones.
2065
+				// Note. We set GLOBAL to true, because resets on ANY template
2066
+				// will use the related global template defaults for regeneration.
2067
+				// This means that if a custom template is reset it resets to whatever the related global template is.
2068
+				// HOWEVER, we DO keep the template pack and template variation set
2069
+				// for the current custom template when resetting.
2070
+				$templates = $this->_generate_new_templates($messenger, $message_type, $GRP_ID, true);
2071
+			}
2072
+		}
2073
+
2074
+		// any error messages?
2075
+		if (! $success) {
2076
+			EE_Error::add_error(
2077
+				esc_html__(
2078
+					'Something went wrong with deleting existing templates. Unable to reset to default',
2079
+					'event_espresso'
2080
+				),
2081
+				__FILE__,
2082
+				__FUNCTION__,
2083
+				__LINE__
2084
+			);
2085
+		}
2086
+
2087
+		// all good, let's add a success message!
2088
+		if ($success && ! empty($templates)) {
2089
+			// the info for the template we generated is the first element in the returned array
2090
+			// $templates = $templates[0];
2091
+			EE_Error::overwrite_success();
2092
+			EE_Error::add_success(esc_html__('Templates have been reset to defaults.', 'event_espresso'));
2093
+		}
2094
+
2095
+
2096
+		$query_args = [
2097
+			'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2098
+			'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2099
+			'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2100
+		];
2101
+
2102
+		// if called via ajax then we return query args otherwise redirect
2103
+		if ($this->request->isAjax()) {
2104
+			return $query_args;
2105
+		}
2106
+		$this->_redirect_after_action(false, '', '', $query_args, true);
2107
+	}
2108
+
2109
+
2110
+	/**
2111
+	 * Retrieve and set the message preview for display.
2112
+	 *
2113
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2114
+	 * @return string
2115
+	 * @throws ReflectionException
2116
+	 * @throws EE_Error
2117
+	 * @throws InvalidArgumentException
2118
+	 * @throws InvalidDataTypeException
2119
+	 * @throws InvalidInterfaceException
2120
+	 */
2121
+	public function _preview_message($send = false)
2122
+	{
2123
+		// first make sure we've got the necessary parameters
2124
+		$GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
2125
+		if (! ($GRP_ID && $this->_active_messenger_name && $this->_active_message_type_name)) {
2126
+			EE_Error::add_error(
2127
+				esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2128
+				__FILE__,
2129
+				__FUNCTION__,
2130
+				__LINE__
2131
+			);
2132
+		}
2133
+
2134
+		$context = $this->request->getRequestParam('context');
2135
+		// get the preview!
2136
+		$preview = EED_Messages::preview_message(
2137
+			$this->_active_message_type_name,
2138
+			$context,
2139
+			$this->_active_messenger_name,
2140
+			$send
2141
+		);
2142
+
2143
+		if ($send) {
2144
+			return $preview;
2145
+		}
2146
+
2147
+		// if we have an evt_id set on the request, use it.
2148
+		$EVT_ID = $this->request->getRequestParam('evt_id', 0, 'int');
2149
+
2150
+		// let's add a button to go back to the edit view
2151
+		$query_args             = [
2152
+			'id'      => $GRP_ID,
2153
+			'evt_id'  => $EVT_ID,
2154
+			'context' => $context,
2155
+			'action'  => 'edit_message_template',
2156
+		];
2157
+		$go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2158
+		$preview_button         = '<a href="'
2159
+								  . $go_back_url
2160
+								  . '" class="button-secondary messages-preview-go-back-button">'
2161
+								  . esc_html__('Go Back to Edit', 'event_espresso')
2162
+								  . '</a>';
2163
+		$message_types          = $this->get_installed_message_types();
2164
+		$active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_active_messenger_name);
2165
+		$active_messenger_label = $active_messenger instanceof EE_messenger
2166
+			? ucwords($active_messenger->label['singular'])
2167
+			: esc_html__('Unknown Messenger', 'event_espresso');
2168
+		// let's provide a helpful title for context
2169
+		$preview_title = sprintf(
2170
+			esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2171
+			$active_messenger_label,
2172
+			ucwords($message_types[ $this->_active_message_type_name ]->label['singular'])
2173
+		);
2174
+		if (empty($preview)) {
2175
+			$this->noEventsErrorMessage();
2176
+		}
2177
+		// setup display of preview.
2178
+		$this->_admin_page_title                    = $preview_title;
2179
+		$this->_template_args['admin_page_title']   = $preview_title;
2180
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2181
+		$this->_template_args['data']['force_json'] = true;
2182
+
2183
+		return '';
2184
+	}
2185
+
2186
+
2187
+	/**
2188
+	 * Used to set an error if there are no events available for generating a preview/test send.
2189
+	 *
2190
+	 * @param bool $test_send Whether the error should be generated for the context of a test send.
2191
+	 */
2192
+	protected function noEventsErrorMessage($test_send = false)
2193
+	{
2194
+		$events_url = parent::add_query_args_and_nonce(
2195
+			[
2196
+				'action' => 'default',
2197
+				'page'   => 'espresso_events',
2198
+			],
2199
+			admin_url('admin.php')
2200
+		);
2201
+		$message    = $test_send
2202
+			? esc_html__(
2203
+				'A test message could not be sent for this message template because there are no events created yet. The preview system uses actual events for generating the test message. %1$sGo see your events%2$s!',
2204
+				'event_espresso'
2205
+			)
2206
+			: esc_html__(
2207
+				'There is no preview for this message template available because there are no events created yet. The preview system uses actual events for generating the preview. %1$sGo see your events%2$s!',
2208
+				'event_espresso'
2209
+			);
2210
+
2211
+		EE_Error::add_attention(
2212
+			sprintf(
2213
+				$message,
2214
+				"<a href='{$events_url}'>",
2215
+				'</a>'
2216
+			)
2217
+		);
2218
+	}
2219
+
2220
+
2221
+	/**
2222
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2223
+	 * gets called automatically.
2224
+	 *
2225
+	 * @return void
2226
+	 * @throws EE_Error
2227
+	 * @since 4.5.0
2228
+	 *
2229
+	 */
2230
+	protected function _display_preview_message()
2231
+	{
2232
+		$this->display_admin_page_with_no_sidebar();
2233
+	}
2234
+
2235
+
2236
+	/**
2237
+	 * registers metaboxes that should show up on the "edit_message_template" page
2238
+	 *
2239
+	 * @access protected
2240
+	 * @return void
2241
+	 */
2242
+	protected function _register_edit_meta_boxes()
2243
+	{
2244
+		add_meta_box(
2245
+			'mtp_valid_shortcodes',
2246
+			esc_html__('Valid Shortcodes', 'event_espresso'),
2247
+			[$this, 'shortcode_meta_box'],
2248
+			$this->_current_screen->id,
2249
+			'side'
2250
+		);
2251
+		add_meta_box(
2252
+			'mtp_extra_actions',
2253
+			esc_html__('Extra Actions', 'event_espresso'),
2254
+			[$this, 'extra_actions_meta_box'],
2255
+			$this->_current_screen->id,
2256
+			'side',
2257
+			'high'
2258
+		);
2259
+		add_meta_box(
2260
+			'mtp_templates',
2261
+			esc_html__('Template Styles', 'event_espresso'),
2262
+			[$this, 'template_pack_meta_box'],
2263
+			$this->_current_screen->id,
2264
+			'side',
2265
+			'high'
2266
+		);
2267
+	}
2268
+
2269
+
2270
+	/**
2271
+	 * metabox content for all template pack and variation selection.
2272
+	 *
2273
+	 * @return void
2274
+	 * @throws DomainException
2275
+	 * @throws EE_Error
2276
+	 * @throws InvalidArgumentException
2277
+	 * @throws ReflectionException
2278
+	 * @throws InvalidDataTypeException
2279
+	 * @throws InvalidInterfaceException
2280
+	 * @since 4.5.0
2281
+	 */
2282
+	public function template_pack_meta_box()
2283
+	{
2284
+		$this->_set_message_template_group();
2285
+
2286
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
2287
+
2288
+		$tp_select_values = [];
2289
+
2290
+		foreach ($tp_collection as $tp) {
2291
+			// only include template packs that support this messenger and message type!
2292
+			$supports = $tp->get_supports();
2293
+			if (
2294
+				! isset($supports[ $this->_message_template_group->messenger() ])
2295
+				|| ! in_array(
2296
+					$this->_message_template_group->message_type(),
2297
+					$supports[ $this->_message_template_group->messenger() ],
2298
+					true
2299
+				)
2300
+			) {
2301
+				// not supported
2302
+				continue;
2303
+			}
2304
+
2305
+			$tp_select_values[] = [
2306
+				'text' => $tp->label,
2307
+				'id'   => $tp->dbref,
2308
+			];
2309
+		}
2310
+
2311
+		// if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2312
+		// the default template pack.  This still allows for the odd template pack to override.
2313
+		if (empty($tp_select_values)) {
2314
+			$tp_select_values[] = [
2315
+				'text' => esc_html__('Default', 'event_espresso'),
2316
+				'id'   => 'default',
2317
+			];
2318
+		}
2319
+
2320
+		// setup variation select values for the currently selected template.
2321
+		$variations               = $this->_message_template_group->get_template_pack()->get_variations(
2322
+			$this->_message_template_group->messenger(),
2323
+			$this->_message_template_group->message_type()
2324
+		);
2325
+		$variations_select_values = [];
2326
+		foreach ($variations as $variation => $label) {
2327
+			$variations_select_values[] = [
2328
+				'text' => $label,
2329
+				'id'   => $variation,
2330
+			];
2331
+		}
2332
+
2333
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2334
+
2335
+		$template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
2336
+			'MTP_template_pack',
2337
+			$tp_select_values,
2338
+			$this->_message_template_group->get_template_pack_name()
2339
+		);
2340
+		$template_args['variations_selector']            = EEH_Form_Fields::select_input(
2341
+			'MTP_template_variation',
2342
+			$variations_select_values,
2343
+			$this->_message_template_group->get_template_pack_variation()
2344
+		);
2345
+		$template_args['template_pack_label']            = $template_pack_labels->template_pack;
2346
+		$template_args['template_variation_label']       = $template_pack_labels->template_variation;
2347
+		$template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
2348
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2349
+
2350
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2351
+
2352
+		EEH_Template::display_template($template, $template_args);
2353
+	}
2354
+
2355
+
2356
+	/**
2357
+	 * This meta box holds any extra actions related to Message Templates
2358
+	 * For now, this includes Resetting templates to defaults and sending a test email.
2359
+	 *
2360
+	 * @access  public
2361
+	 * @return void
2362
+	 * @throws EE_Error
2363
+	 */
2364
+	public function extra_actions_meta_box()
2365
+	{
2366
+		$template_form_fields = [];
2367
+
2368
+		$extra_args = [
2369
+			'msgr'   => $this->_message_template_group->messenger(),
2370
+			'mt'     => $this->_message_template_group->message_type(),
2371
+			'GRP_ID' => $this->_message_template_group->GRP_ID(),
2372
+		];
2373
+		// first we need to see if there are any fields
2374
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2375
+
2376
+		if (! empty($fields)) {
2377
+			// yup there be fields
2378
+			foreach ($fields as $field => $config) {
2379
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2380
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2381
+				$default  = isset($config['default']) ? $config['default'] : '';
2382
+				$default  = isset($config['value']) ? $config['value'] : $default;
2383
+
2384
+				// if type is hidden and the value is empty
2385
+				// something may have gone wrong so let's correct with the defaults
2386
+				$fix                = $config['input'] === 'hidden'
2387
+									  && isset($existing[ $field ])
2388
+									  && empty($existing[ $field ])
2389
+					? $default
2390
+					: '';
2391
+				$existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2392
+					? $existing[ $field ]
2393
+					: $fix;
2394
+
2395
+				$template_form_fields[ $field_id ] = [
2396
+					'name'       => 'test_settings_fld[' . $field . ']',
2397
+					'label'      => $config['label'],
2398
+					'input'      => $config['input'],
2399
+					'type'       => $config['type'],
2400
+					'required'   => $config['required'],
2401
+					'validation' => $config['validation'],
2402
+					'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2403
+					'css_class'  => $config['css_class'],
2404
+					'options'    => isset($config['options']) ? $config['options'] : [],
2405
+					'default'    => $default,
2406
+					'format'     => $config['format'],
2407
+				];
2408
+			}
2409
+		}
2410
+
2411
+		$test_settings_html = ! empty($template_form_fields)
2412
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2413
+			: '';
2414
+
2415
+		// print out $test_settings_fields
2416
+		if (! empty($test_settings_html)) {
2417
+			$test_settings_html .= '<input type="submit" class="button-primary mtp-test-button alignright" ';
2418
+			$test_settings_html .= 'name="test_button" value="';
2419
+			$test_settings_html .= esc_html__('Test Send', 'event_espresso');
2420
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2421
+		}
2422
+
2423
+		// and button
2424
+		$test_settings_html .= '<p>';
2425
+		$test_settings_html .= esc_html__('Need to reset this message type and start over?', 'event_espresso');
2426
+		$test_settings_html .= '</p>';
2427
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2428
+		$test_settings_html .= $this->get_action_link_or_button(
2429
+			'reset_to_default',
2430
+			'reset',
2431
+			$extra_args,
2432
+			'button-primary reset-default-button'
2433
+		);
2434
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2435
+		echo $test_settings_html; // already escaped
2436
+	}
2437
+
2438
+
2439
+	/**
2440
+	 * This returns the shortcode selector skeleton for a given context and field.
2441
+	 *
2442
+	 * @param string $field           The name of the field retrieving shortcodes for.
2443
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2444
+	 * @return string
2445
+	 * @throws DomainException
2446
+	 * @throws EE_Error
2447
+	 * @throws InvalidArgumentException
2448
+	 * @throws ReflectionException
2449
+	 * @throws InvalidDataTypeException
2450
+	 * @throws InvalidInterfaceException
2451
+	 * @since 4.9.rc.000
2452
+	 */
2453
+	protected function _get_shortcode_selector($field, $linked_input_id)
2454
+	{
2455
+		$template_args = [
2456
+			'shortcodes'      => $this->_get_shortcodes([$field]),
2457
+			'fieldname'       => $field,
2458
+			'linked_input_id' => $linked_input_id,
2459
+		];
2460
+
2461
+		return EEH_Template::display_template(
2462
+			EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2463
+			$template_args,
2464
+			true
2465
+		);
2466
+	}
2467
+
2468
+
2469
+	/**
2470
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2471
+	 * page)
2472
+	 *
2473
+	 * @access public
2474
+	 * @return void
2475
+	 * @throws EE_Error
2476
+	 * @throws InvalidArgumentException
2477
+	 * @throws ReflectionException
2478
+	 * @throws InvalidDataTypeException
2479
+	 * @throws InvalidInterfaceException
2480
+	 */
2481
+	public function shortcode_meta_box()
2482
+	{
2483
+		$shortcodes = $this->_get_shortcodes([], false);
2484
+		// just make sure the shortcodes property is set
2485
+		// $messenger = $this->_message_template_group->messenger_obj();
2486
+		// now let's set the content depending on the status of the shortcodes array
2487
+		if (empty($shortcodes)) {
2488
+			echo '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2489
+			return;
2490
+		}
2491
+		?>
2492 2492
         <div style="float:right; margin-top:10px">
2493 2493
             <?php echo $this->_get_help_tab_link('message_template_shortcodes'); // already escaped
2494
-            ?>
2494
+			?>
2495 2495
         </div>
2496 2496
         <p class="small-text">
2497 2497
             <?php printf(
2498
-                esc_html__(
2499
-                    'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2500
-                    'event_espresso'
2501
-                ),
2502
-                '<span class="dashicons dashicons-menu"></span>'
2503
-            ); ?>
2498
+				esc_html__(
2499
+					'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2500
+					'event_espresso'
2501
+				),
2502
+				'<span class="dashicons dashicons-menu"></span>'
2503
+			); ?>
2504 2504
         </p>
2505 2505
         <?php
2506
-    }
2507
-
2508
-
2509
-    /**
2510
-     * used to set the $_shortcodes property for when its needed elsewhere.
2511
-     *
2512
-     * @access protected
2513
-     * @return void
2514
-     * @throws EE_Error
2515
-     * @throws InvalidArgumentException
2516
-     * @throws ReflectionException
2517
-     * @throws InvalidDataTypeException
2518
-     * @throws InvalidInterfaceException
2519
-     */
2520
-    protected function _set_shortcodes()
2521
-    {
2522
-
2523
-        // no need to run this if the property is already set
2524
-        if (! empty($this->_shortcodes)) {
2525
-            return;
2526
-        }
2527
-
2528
-        $this->_shortcodes = $this->_get_shortcodes();
2529
-    }
2530
-
2531
-
2532
-    /**
2533
-     * gets all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2534
-     * property)
2535
-     *
2536
-     * @access  protected
2537
-     * @param array   $fields  include an array of specific field names that you want to be used to get the shortcodes
2538
-     *                         for. Defaults to all (for the given context)
2539
-     * @param boolean $merged  Whether to merge all the shortcodes into one list of unique shortcodes
2540
-     * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2541
-     *                         true just an array of shortcode/label pairs.
2542
-     * @throws EE_Error
2543
-     * @throws InvalidArgumentException
2544
-     * @throws ReflectionException
2545
-     * @throws InvalidDataTypeException
2546
-     * @throws InvalidInterfaceException
2547
-     */
2548
-    protected function _get_shortcodes($fields = [], $merged = true)
2549
-    {
2550
-        $this->_set_message_template_group();
2551
-
2552
-        // we need the messenger and message template to retrieve the valid shortcodes array.
2553
-        $GRP_ID = $this->request->getRequestParam('id', 0, 'int');
2554
-        if (empty($GRP_ID)) {
2555
-            return [];
2556
-        }
2557
-        $context = $this->request->getRequestParam(
2558
-            'messenger',
2559
-            key($this->_message_template_group->contexts_config())
2560
-        );
2561
-        return $this->_message_template_group->get_shortcodes($context, $fields, $merged);
2562
-    }
2563
-
2564
-
2565
-    /**
2566
-     * This sets the _message_template property (containing the called message_template object)
2567
-     *
2568
-     * @access protected
2569
-     * @return void
2570
-     * @throws EE_Error
2571
-     * @throws InvalidArgumentException
2572
-     * @throws ReflectionException
2573
-     * @throws InvalidDataTypeException
2574
-     * @throws InvalidInterfaceException
2575
-     */
2576
-    protected function _set_message_template_group()
2577
-    {
2578
-
2579
-        if (! empty($this->_message_template_group)) {
2580
-            return;
2581
-        } //get out if this is already set.
2582
-
2583
-        $GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
2584
-        $GRP_ID = $this->request->getRequestParam('id', $GRP_ID, 'int');
2585
-
2586
-        // let's get the message templates
2587
-        $MTP = EEM_Message_Template_Group::instance();
2588
-
2589
-        if (empty($GRP_ID)) {
2590
-            $this->_message_template_group = $MTP->create_default_object();
2591
-        } else {
2592
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2593
-        }
2594
-
2595
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2596
-        $this->_variation     = $this->_message_template_group->get_template_pack_variation();
2597
-    }
2598
-
2599
-
2600
-    /**
2601
-     * sets up a context switcher for edit forms
2602
-     *
2603
-     * @access  protected
2604
-     * @param EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2605
-     * @param array                     $args                  various things the context switcher needs.
2606
-     * @throws EE_Error
2607
-     */
2608
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2609
-    {
2610
-        $context_details = $template_group_object->contexts_config();
2611
-        $context_label   = $template_group_object->context_label();
2612
-        ob_start();
2613
-        ?>
2506
+	}
2507
+
2508
+
2509
+	/**
2510
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2511
+	 *
2512
+	 * @access protected
2513
+	 * @return void
2514
+	 * @throws EE_Error
2515
+	 * @throws InvalidArgumentException
2516
+	 * @throws ReflectionException
2517
+	 * @throws InvalidDataTypeException
2518
+	 * @throws InvalidInterfaceException
2519
+	 */
2520
+	protected function _set_shortcodes()
2521
+	{
2522
+
2523
+		// no need to run this if the property is already set
2524
+		if (! empty($this->_shortcodes)) {
2525
+			return;
2526
+		}
2527
+
2528
+		$this->_shortcodes = $this->_get_shortcodes();
2529
+	}
2530
+
2531
+
2532
+	/**
2533
+	 * gets all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2534
+	 * property)
2535
+	 *
2536
+	 * @access  protected
2537
+	 * @param array   $fields  include an array of specific field names that you want to be used to get the shortcodes
2538
+	 *                         for. Defaults to all (for the given context)
2539
+	 * @param boolean $merged  Whether to merge all the shortcodes into one list of unique shortcodes
2540
+	 * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2541
+	 *                         true just an array of shortcode/label pairs.
2542
+	 * @throws EE_Error
2543
+	 * @throws InvalidArgumentException
2544
+	 * @throws ReflectionException
2545
+	 * @throws InvalidDataTypeException
2546
+	 * @throws InvalidInterfaceException
2547
+	 */
2548
+	protected function _get_shortcodes($fields = [], $merged = true)
2549
+	{
2550
+		$this->_set_message_template_group();
2551
+
2552
+		// we need the messenger and message template to retrieve the valid shortcodes array.
2553
+		$GRP_ID = $this->request->getRequestParam('id', 0, 'int');
2554
+		if (empty($GRP_ID)) {
2555
+			return [];
2556
+		}
2557
+		$context = $this->request->getRequestParam(
2558
+			'messenger',
2559
+			key($this->_message_template_group->contexts_config())
2560
+		);
2561
+		return $this->_message_template_group->get_shortcodes($context, $fields, $merged);
2562
+	}
2563
+
2564
+
2565
+	/**
2566
+	 * This sets the _message_template property (containing the called message_template object)
2567
+	 *
2568
+	 * @access protected
2569
+	 * @return void
2570
+	 * @throws EE_Error
2571
+	 * @throws InvalidArgumentException
2572
+	 * @throws ReflectionException
2573
+	 * @throws InvalidDataTypeException
2574
+	 * @throws InvalidInterfaceException
2575
+	 */
2576
+	protected function _set_message_template_group()
2577
+	{
2578
+
2579
+		if (! empty($this->_message_template_group)) {
2580
+			return;
2581
+		} //get out if this is already set.
2582
+
2583
+		$GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
2584
+		$GRP_ID = $this->request->getRequestParam('id', $GRP_ID, 'int');
2585
+
2586
+		// let's get the message templates
2587
+		$MTP = EEM_Message_Template_Group::instance();
2588
+
2589
+		if (empty($GRP_ID)) {
2590
+			$this->_message_template_group = $MTP->create_default_object();
2591
+		} else {
2592
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2593
+		}
2594
+
2595
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2596
+		$this->_variation     = $this->_message_template_group->get_template_pack_variation();
2597
+	}
2598
+
2599
+
2600
+	/**
2601
+	 * sets up a context switcher for edit forms
2602
+	 *
2603
+	 * @access  protected
2604
+	 * @param EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2605
+	 * @param array                     $args                  various things the context switcher needs.
2606
+	 * @throws EE_Error
2607
+	 */
2608
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2609
+	{
2610
+		$context_details = $template_group_object->contexts_config();
2611
+		$context_label   = $template_group_object->context_label();
2612
+		ob_start();
2613
+		?>
2614 2614
         <div class="ee-msg-switcher-container">
2615 2615
             <form method="get" action="<?php echo esc_url_raw(EE_MSG_ADMIN_URL); ?>" id="ee-msg-context-switcher-frm">
2616 2616
                 <?php
2617
-                foreach ($args as $name => $value) {
2618
-                    if ($name === 'context' || empty($value) || $name === 'extra') {
2619
-                        continue;
2620
-                    }
2621
-                    ?>
2617
+				foreach ($args as $name => $value) {
2618
+					if ($name === 'context' || empty($value) || $name === 'extra') {
2619
+						continue;
2620
+					}
2621
+					?>
2622 2622
                     <input type="hidden"
2623 2623
                            name="<?php echo esc_attr($name); ?>"
2624 2624
                            value="<?php echo esc_attr($value); ?>"
2625 2625
                     />
2626 2626
                     <?php
2627
-                }
2628
-                // setup nonce_url
2629
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2630
-                $id = 'ee-' . sanitize_key($context_label['label']) . '-select';
2631
-                ?>
2627
+				}
2628
+				// setup nonce_url
2629
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2630
+				$id = 'ee-' . sanitize_key($context_label['label']) . '-select';
2631
+				?>
2632 2632
                 <label for='<?php echo esc_attr($id); ?>' class='screen-reader-text'>
2633 2633
                     <?php esc_html_e('message context options', 'event_espresso'); ?>
2634 2634
                 </label>
2635 2635
                 <select id="<?php echo esc_attr($id); ?>" name="context">
2636 2636
                     <?php
2637
-                    $context_templates = $template_group_object->context_templates();
2638
-                    if (is_array($context_templates)) :
2639
-                        foreach ($context_templates as $context => $template_fields) :
2640
-                            $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2641
-                            ?>
2637
+					$context_templates = $template_group_object->context_templates();
2638
+					if (is_array($context_templates)) :
2639
+						foreach ($context_templates as $context => $template_fields) :
2640
+							$checked = ($context === $args['context']) ? 'selected="selected"' : '';
2641
+							?>
2642 2642
                             <option value="<?php echo esc_attr($context); ?>" <?php echo esc_attr($checked); ?>>
2643 2643
                                 <?php echo $context_details[ $context ]['label']; // already escaped ?>
2644 2644
                             </option>
2645 2645
                         <?php endforeach;
2646
-                    endif; ?>
2646
+					endif; ?>
2647 2647
                 </select>
2648 2648
                 <?php $button_text = sprintf(
2649
-                    esc_html__('Switch %s', 'event_espresso'),
2650
-                    ucwords($context_label['label'])
2651
-                ); ?>
2649
+					esc_html__('Switch %s', 'event_espresso'),
2650
+					ucwords($context_label['label'])
2651
+				); ?>
2652 2652
                 <input class='button-secondary'
2653 2653
                        id="submit-msg-context-switcher-sbmt"
2654 2654
                        type="submit"
@@ -2658,1870 +2658,1870 @@  discard block
 block discarded – undo
2658 2658
             <?php echo $args['extra']; // already escaped ?>
2659 2659
         </div> <!-- end .ee-msg-switcher-container -->
2660 2660
         <?php
2661
-        $this->_context_switcher = ob_get_clean();
2662
-    }
2663
-
2664
-
2665
-    /**
2666
-     * utility for sanitizing new values coming in.
2667
-     * Note: this is only used when updating a context.
2668
-     *
2669
-     * @access protected
2670
-     *
2671
-     * @param int $index This helps us know which template field to select from the request array.
2672
-     *
2673
-     * @return array
2674
-     */
2675
-    protected function _set_message_template_column_values($index)
2676
-    {
2677
-        return [
2678
-            'MTP_ID'             => $this->request->getRequestParam("MTP_template_fields[{$index}][MTP_ID]", 0, 'int'),
2679
-            'GRP_ID'             => $this->request->getRequestParam('GRP_ID', 0, 'int'),
2680
-            'MTP_user_id'        => $this->request->getRequestParam('MTP_user_id', 0, 'int'),
2681
-            'MTP_messenger'      => strtolower($this->request->getRequestParam('MTP_messenger', '')),
2682
-            'MTP_message_type'   => strtolower($this->request->getRequestParam('MTP_message_type', '')),
2683
-            'MTP_template_field' => strtolower(
2684
-                $this->request->getRequestParam("MTP_template_fields[{$index}][name]", '')
2685
-            ),
2686
-            'MTP_context'        => strtolower($this->request->getRequestParam('MTP_context', '')),
2687
-            'MTP_content'        => $this->request->getRequestParam(
2688
-                "MTP_template_fields[{$index}][content]",
2689
-                '',
2690
-                'html'
2691
-            ),
2692
-            'MTP_is_global'      => $this->request->getRequestParam('MTP_is_global', 0, 'int'),
2693
-            'MTP_is_override'    => $this->request->getRequestParam('MTP_is_override', 0, 'int'),
2694
-            'MTP_deleted'        => $this->request->getRequestParam('MTP_deleted', 0, 'int'),
2695
-            'MTP_is_active'      => $this->request->getRequestParam('MTP_is_active', 0, 'int'),
2696
-        ];
2697
-    }
2698
-
2699
-
2700
-    /**
2701
-     * @param bool $new
2702
-     * @throws EE_Error
2703
-     * @throws ReflectionException
2704
-     */
2705
-    protected function _insert_or_update_message_template($new = false)
2706
-    {
2707
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2708
-        $success  = 0;
2709
-        $override = false;
2710
-
2711
-        // setup notices description
2712
-        $messenger_slug = $this->request->getRequestParam('MTP_messenger', '');
2713
-
2714
-        // need the message type and messenger objects to be able to use the labels for the notices
2715
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2716
-        $messenger_label  = $messenger_object instanceof EE_messenger
2717
-            ? ucwords($messenger_object->label['singular'])
2718
-            : '';
2719
-
2720
-        $message_type_slug   = $this->request->getRequestParam('MTP_message_type', '');
2721
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2722
-
2723
-        $message_type_label = $message_type_object instanceof EE_message_type
2724
-            ? ucwords($message_type_object->label['singular'])
2725
-            : '';
2726
-
2727
-        $context_slug = $this->request->getRequestParam('MTP_context', '');
2728
-        $context      = ucwords(str_replace('_', ' ', $context_slug));
2729
-
2730
-        $item_desc   = $messenger_label && $message_type_label
2731
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2732
-            : '';
2733
-        $item_desc   .= 'Message Template';
2734
-        $query_args  = [];
2735
-        $edit_array  = [];
2736
-        $action_desc = '';
2737
-
2738
-        $GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
2739
-        // if this is "new" then we need to generate the default contexts
2740
-        // for the selected messenger/message_type for user to edit.
2741
-        if ($new) {
2742
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2743
-                if (empty($edit_array)) {
2744
-                    $success = 0;
2745
-                } else {
2746
-                    $success    = 1;
2747
-                    $edit_array = $edit_array[0];
2748
-                    $query_args = [
2749
-                        'id'      => $edit_array['GRP_ID'],
2750
-                        'context' => $edit_array['MTP_context'],
2751
-                        'action'  => 'edit_message_template',
2752
-                    ];
2753
-                }
2754
-            }
2755
-            $action_desc = 'created';
2756
-        } else {
2757
-            $MTPG = EEM_Message_Template_Group::instance();
2758
-            $MTP  = EEM_Message_Template::instance();
2759
-
2760
-            // run update for each template field in displayed context
2761
-            $template_fields = $this->request->getRequestParam('MTP_template_fields', null, 'html', true);
2762
-            // messages content is expected to be escaped
2763
-            $template_fields = EEH_Array::addSlashesRecursively($template_fields);
2764
-
2765
-            if (! $template_fields) {
2766
-                EE_Error::add_error(
2767
-                    esc_html__(
2768
-                        'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2769
-                        'event_espresso'
2770
-                    ),
2771
-                    __FILE__,
2772
-                    __FUNCTION__,
2773
-                    __LINE__
2774
-                );
2775
-                $success = 0;
2776
-            } else {
2777
-                // first validate all fields!
2778
-                // this filter allows client code to add its own validation to the template fields as well.
2779
-                // returning an empty array means everything passed validation.
2780
-                // errors in validation should be represented in an array with the following shape:
2781
-                // array(
2782
-                //   'fieldname' => array(
2783
-                //          'msg' => 'error message'
2784
-                //          'value' => 'value for field producing error'
2785
-                // )
2786
-                $custom_validation = (array) apply_filters(
2787
-                    'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2788
-                    [],
2789
-                    $template_fields,
2790
-                    $context_slug,
2791
-                    $messenger_slug,
2792
-                    $message_type_slug
2793
-                );
2794
-
2795
-                $system_validation = $MTPG->validate(
2796
-                    $template_fields,
2797
-                    $context_slug,
2798
-                    $messenger_slug,
2799
-                    $message_type_slug
2800
-                );
2801
-
2802
-
2803
-                $system_validation = ! is_array($system_validation) && $system_validation ? [] : $system_validation;
2804
-                $validates         = array_merge($custom_validation, $system_validation);
2805
-
2806
-                // if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2807
-                // appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2808
-                //  WE need to make sure there is no actual error messages in validates.
2809
-                if (! empty($validates)) {
2810
-                    // add the transient so when the form loads we know which fields to highlight
2811
-                    $this->_add_transient('edit_message_template', $validates);
2812
-
2813
-                    $success = 0;
2814
-
2815
-                    // setup notices
2816
-                    foreach ($validates as $error) {
2817
-                        if (isset($error['msg'])) {
2818
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2819
-                        }
2820
-                    }
2821
-                } else {
2822
-                    $success           = 1;
2823
-                    $action_desc       = 'updated';
2824
-                    $set_column_values = [];
2825
-                    foreach ($template_fields as $template_field => $content) {
2826
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2827
-
2828
-                        // if they aren't allowed to use all JS, restrict them to just posty-y tags
2829
-                        if (! current_user_can('unfiltered_html')) {
2830
-                            $set_column_values['MTP_content'] = $this->sanitizeMessageTemplateContent(
2831
-                                $set_column_values['MTP_content']
2832
-                            );
2833
-                        }
2834
-                        $message_template_fields = [
2835
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2836
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2837
-                            'MTP_context'        => $set_column_values['MTP_context'],
2838
-                            'MTP_content'        => $set_column_values['MTP_content'],
2839
-                        ];
2840
-
2841
-                        $hasMtpID = ! empty($content['MTP_ID']);
2842
-                        // if we have a MTP_ID for this field then update it, otherwise insert.
2843
-                        // this has already been through the template field validator and sanitized, so it will be
2844
-                        // safe to insert this field.  Why insert?  This typically happens when we introduce a new
2845
-                        // message template field in a messenger/message type and existing users don't have the
2846
-                        // default setup for it.
2847
-                        // @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2848
-                        $updated = $hasMtpID
2849
-                            ? $MTP->update($message_template_fields, [['MTP_ID' => $content['MTP_ID']]])
2850
-                            : $MTP->insert($message_template_fields);
2851
-
2852
-                        $insert_failed = ! $hasMtpID && ! $updated;
2853
-                        // updates will return 0 if the field was not changed (ie: nothing actually updated)
2854
-                        // but we won't consider that a problem, but if it returns false, then something went BOOM!
2855
-                        $update_failed = ! $hasMtpID && $updated === false;
2856
-
2857
-                        if ($insert_failed || $update_failed) {
2858
-                            EE_Error::add_error(
2859
-                                sprintf(
2860
-                                    esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2861
-                                    $template_field
2862
-                                ),
2863
-                                __FILE__,
2864
-                                __FUNCTION__,
2865
-                                __LINE__
2866
-                            );
2867
-                            $success = 0;
2868
-                        }
2869
-                    }
2870
-
2871
-                    // we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2872
-                    $mtpg_fields = [
2873
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2874
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2875
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2876
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2877
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2878
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2879
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2880
-                        'MTP_name'         => $this->request->getRequestParam('ee_msg_non_global_fields[MTP_name]', ''),
2881
-                        'MTP_description'  => $this->request->getRequestParam(
2882
-                            'ee_msg_non_global_fields[MTP_description]',
2883
-                            ''
2884
-                        ),
2885
-                    ];
2886
-
2887
-                    $updated = $MTPG->update($mtpg_fields, [['GRP_ID' => $set_column_values['GRP_ID']]]);
2888
-
2889
-                    if ($updated === false) {
2890
-                        EE_Error::add_error(
2891
-                            sprintf(
2892
-                                esc_html__(
2893
-                                    'The Message Template Group (%d) was NOT updated for some reason',
2894
-                                    'event_espresso'
2895
-                                ),
2896
-                                $set_column_values['GRP_ID']
2897
-                            ),
2898
-                            __FILE__,
2899
-                            __FUNCTION__,
2900
-                            __LINE__
2901
-                        );
2902
-                        $success = 0;
2903
-                    } else {
2904
-                        // k now we need to ensure the template_pack and template_variation fields are set.
2905
-                        $template_pack      = $this->request->getRequestParam('MTP_template_pack', 'default');
2906
-                        $template_variation = $this->request->getRequestParam('MTP_template_variation', 'default');
2907
-
2908
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2909
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2910
-                            $mtpg_obj->set_template_pack_name($template_pack);
2911
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2912
-                        }
2913
-                    }
2914
-                }
2915
-            }
2916
-        }
2917
-
2918
-        // we return things differently if doing ajax
2919
-        if ($this->request->isAjax()) {
2920
-            $this->_template_args['success'] = $success;
2921
-            $this->_template_args['error']   = ! $success;
2922
-            $this->_template_args['content'] = '';
2923
-            $this->_template_args['data']    = [
2924
-                'grpID'        => $edit_array['GRP_ID'],
2925
-                'templateName' => $edit_array['template_name'],
2926
-            ];
2927
-            if ($success) {
2928
-                EE_Error::overwrite_success();
2929
-                EE_Error::add_success(
2930
-                    esc_html__(
2931
-                        'The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2932
-                        'event_espresso'
2933
-                    )
2934
-                );
2935
-            }
2936
-
2937
-            $this->_return_json();
2938
-        }
2939
-
2940
-
2941
-        // was a test send triggered?
2942
-        if ($this->request->getRequestParam('test_button', false, 'bool')) {
2943
-            EE_Error::overwrite_success();
2944
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2945
-            $override = true;
2946
-        }
2947
-
2948
-        $query_args = ! empty($query_args)
2949
-            ? $query_args
2950
-            : [
2951
-                'id'      => $GRP_ID,
2952
-                'context' => $context_slug,
2953
-                'action'  => 'edit_message_template',
2954
-            ];
2955
-
2956
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2957
-    }
2958
-
2959
-
2960
-    /**
2961
-     * recursively runs wp_kses() on message template content in a model safe manner
2962
-     *
2963
-     * @param array|string $content
2964
-     * @return array|string
2965
-     * @since   $VID:$
2966
-     */
2967
-    private function sanitizeMessageTemplateContent($content)
2968
-    {
2969
-        if (is_array($content)) {
2970
-            foreach ($content as $key => $value) {
2971
-                $content[ $key ] = $this->sanitizeMessageTemplateContent($value);
2972
-            }
2973
-            return $content;
2974
-        }
2975
-        // remove slashes so wp_kses() works properly
2976
-        // wp_kses_stripslashes() only removes slashes from double-quotes,
2977
-        // so attributes using single quotes always appear invalid.
2978
-        $content = stripslashes($content);
2979
-        $content = wp_kses($content, wp_kses_allowed_html('post'));
2980
-        // But currently the models expect slashed data, so after wp_kses()
2981
-        // runs we need to re-slash the data. Sheesh.
2982
-        // See https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2983
-        return addslashes($content);
2984
-    }
2985
-
2986
-
2987
-    /**
2988
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
2989
-     *
2990
-     * @param string $context      what context being tested
2991
-     * @param string $messenger    messenger being tested
2992
-     * @param string $message_type message type being tested
2993
-     * @throws EE_Error
2994
-     * @throws InvalidArgumentException
2995
-     * @throws InvalidDataTypeException
2996
-     * @throws InvalidInterfaceException
2997
-     * @throws ReflectionException
2998
-     */
2999
-    protected function _do_test_send($context, $messenger, $message_type)
3000
-    {
3001
-        // set things up for preview
3002
-        $this->request->setRequestParam('messenger', $messenger);
3003
-        $this->request->setRequestParam('message_type', $message_type);
3004
-        $this->request->setRequestParam('context', $context);
3005
-        $GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
3006
-        $this->request->setRequestParam('GRP_ID', $GRP_ID);
3007
-
3008
-        $active_messenger  = $this->_message_resource_manager->get_active_messenger($messenger);
3009
-        $test_settings_fld = $this->request->getRequestParam('test_settings_fld', [], 'string', true);
3010
-
3011
-        // let's save any existing fields that might be required by the messenger
3012
-        if (
3013
-            ! empty($test_settings_fld)
3014
-            && $active_messenger instanceof EE_messenger
3015
-            && apply_filters(
3016
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3017
-                true,
3018
-                $test_settings_fld,
3019
-                $active_messenger
3020
-            )
3021
-        ) {
3022
-            $active_messenger->set_existing_test_settings($test_settings_fld);
3023
-        }
3024
-
3025
-        /**
3026
-         * Use filter to add additional controls on whether message can send or not
3027
-         */
3028
-        if (
3029
-            apply_filters(
3030
-                'FHEE__Messages_Admin_Page__do_test_send__can_send',
3031
-                true,
3032
-                $context,
3033
-                $this->request->requestParams(),
3034
-                $messenger,
3035
-                $message_type
3036
-            )
3037
-        ) {
3038
-            if (EEM_Event::instance()->count() > 0) {
3039
-                $success = $this->_preview_message(true);
3040
-                if ($success) {
3041
-                    EE_Error::add_success(esc_html__('Test message sent', 'event_espresso'));
3042
-                } else {
3043
-                    EE_Error::add_error(
3044
-                        esc_html__('The test message was not sent', 'event_espresso'),
3045
-                        __FILE__,
3046
-                        __FUNCTION__,
3047
-                        __LINE__
3048
-                    );
3049
-                }
3050
-            } else {
3051
-                $this->noEventsErrorMessage(true);
3052
-            }
3053
-        }
3054
-    }
3055
-
3056
-
3057
-    /**
3058
-     * _generate_new_templates
3059
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3060
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3061
-     * for the event.
3062
-     *
3063
-     *
3064
-     * @param string $messenger      the messenger we are generating templates for
3065
-     * @param array  $message_types  array of message types that the templates are generated for.
3066
-     * @param int    $GRP_ID         If this is a custom template being generated then a GRP_ID needs to be included to
3067
-     *                               indicate the message_template_group being used as the base.
3068
-     *
3069
-     * @param bool   $global
3070
-     *
3071
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
3072
-     *                               encountering problems.
3073
-     * @throws EE_Error
3074
-     * @throws ReflectionException
3075
-     */
3076
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3077
-    {
3078
-
3079
-        // if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3080
-        // just don't generate any templates.
3081
-        if (empty($message_types)) {
3082
-            return true;
3083
-        }
3084
-
3085
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3086
-    }
3087
-
3088
-
3089
-    /**
3090
-     * [_trash_or_restore_message_template]
3091
-     *
3092
-     * @param boolean $trash  whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3093
-     * @param boolean $all    whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3094
-     *                        an individual context (FALSE).
3095
-     * @return void
3096
-     * @throws EE_Error
3097
-     * @throws InvalidArgumentException
3098
-     * @throws InvalidDataTypeException
3099
-     * @throws InvalidInterfaceException
3100
-     */
3101
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
3102
-    {
3103
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3104
-        $MTP = EEM_Message_Template_Group::instance();
3105
-
3106
-        $success = 1;
3107
-
3108
-        // incoming GRP_IDs
3109
-        if ($all) {
3110
-            // Checkboxes
3111
-            $checkboxes = $this->request->getRequestParam('checkbox', [], 'int', true);
3112
-            if (! empty($checkboxes)) {
3113
-                // if array has more than one element then success message should be plural.
3114
-                // todo: what about nonce?
3115
-                $success = count($checkboxes) > 1 ? 2 : 1;
3116
-
3117
-                // cycle through checkboxes
3118
-                while (list($GRP_ID, $value) = each($checkboxes)) {
3119
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3120
-                    if (! $trashed_or_restored) {
3121
-                        $success = 0;
3122
-                    }
3123
-                }
3124
-            } else {
3125
-                // grab single GRP_ID and handle
3126
-                $GRP_ID = $this->request->getRequestParam('id', 0, 'int');
3127
-                if (! empty($GRP_ID)) {
3128
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3129
-                    if (! $trashed_or_restored) {
3130
-                        $success = 0;
3131
-                    }
3132
-                } else {
3133
-                    $success = 0;
3134
-                }
3135
-            }
3136
-        }
3137
-
3138
-        $action_desc = $trash
3139
-            ? esc_html__('moved to the trash', 'event_espresso')
3140
-            : esc_html__('restored', 'event_espresso');
3141
-
3142
-        $template_switch = $this->request->getRequestParam('template_switch', false, 'bool');
3143
-        $action_desc     = $template_switch ? esc_html__('switched', 'event_espresso') : $action_desc;
3144
-
3145
-        $item_desc = $all ? _n(
3146
-            'Message Template Group',
3147
-            'Message Template Groups',
3148
-            $success,
3149
-            'event_espresso'
3150
-        ) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3151
-
3152
-        $item_desc = $template_switch
3153
-            ? _n('template', 'templates', $success, 'event_espresso')
3154
-            : $item_desc;
3155
-
3156
-        $this->_redirect_after_action($success, $item_desc, $action_desc, []);
3157
-    }
3158
-
3159
-
3160
-    /**
3161
-     * [_delete_message_template]
3162
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3163
-     *
3164
-     * @return void
3165
-     * @throws EE_Error
3166
-     * @throws InvalidArgumentException
3167
-     * @throws InvalidDataTypeException
3168
-     * @throws InvalidInterfaceException
3169
-     * @throws ReflectionException
3170
-     */
3171
-    protected function _delete_message_template()
3172
-    {
3173
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3174
-
3175
-        // checkboxes
3176
-        $checkboxes = $this->request->getRequestParam('checkbox', [], 'int', true);
3177
-        if (! empty($checkboxes)) {
3178
-            // if array has more than one element then success message should be plural
3179
-            $success = count($checkboxes) > 1 ? 2 : 1;
3180
-
3181
-            // cycle through bulk action checkboxes
3182
-            while (list($GRP_ID, $value) = each($checkboxes)) {
3183
-                $success = $this->_delete_mtp_permanently($GRP_ID) ? $success : false;
3184
-            }
3185
-        } else {
3186
-            // grab single grp_id and delete
3187
-            $GRP_ID  = $this->request->getRequestParam('id', 0, 'int');
3188
-            $success = $this->_delete_mtp_permanently($GRP_ID);
3189
-        }
3190
-
3191
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', []);
3192
-    }
3193
-
3194
-
3195
-    /**
3196
-     * helper for permanently deleting a mtP group and all related message_templates
3197
-     *
3198
-     * @param int  $GRP_ID        The group being deleted
3199
-     * @param bool $include_group whether to delete the Message Template Group as well.
3200
-     * @return bool boolean to indicate the success of the deletes or not.
3201
-     * @throws EE_Error
3202
-     * @throws InvalidArgumentException
3203
-     * @throws InvalidDataTypeException
3204
-     * @throws InvalidInterfaceException
3205
-     * @throws ReflectionException
3206
-     * @throws ReflectionException
3207
-     */
3208
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3209
-    {
3210
-        $success = true;
3211
-        $MTPG    = EEM_Message_Template_Group::instance();
3212
-        // first let's GET this group
3213
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
3214
-        // then delete permanently all the related Message Templates
3215
-        $deleted = $MTG->delete_related_permanently('Message_Template');
3216
-
3217
-        if ($deleted === 0) {
3218
-            $success = false;
3219
-        }
3220
-
3221
-        // now delete permanently this particular group
3222
-
3223
-        if ($include_group && ! $MTG->delete_permanently()) {
3224
-            $success = false;
3225
-        }
3226
-
3227
-        return $success;
3228
-    }
3229
-
3230
-
3231
-    /**
3232
-     *    _learn_more_about_message_templates_link
3233
-     *
3234
-     * @access protected
3235
-     * @return string
3236
-     */
3237
-    protected function _learn_more_about_message_templates_link()
3238
-    {
3239
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3240
-               . esc_html__('learn more about how message templates works', 'event_espresso')
3241
-               . '</a>';
3242
-    }
3243
-
3244
-
3245
-    /**
3246
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3247
-     * ajax and other routes.
3248
-     *
3249
-     * @return void
3250
-     * @throws DomainException
3251
-     * @throws EE_Error
3252
-     */
3253
-    protected function _settings()
3254
-    {
3255
-        $this->_set_m_mt_settings();
3256
-
3257
-        // let's setup the messenger tabs
3258
-        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3259
-            $this->_m_mt_settings['messenger_tabs'],
3260
-            'messenger_links',
3261
-            '|',
3262
-            $this->request->getRequestParam('selected_messenger', 'email')
3263
-        );
3264
-
3265
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3266
-        $this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
3267
-
3268
-        $this->display_admin_page_with_sidebar();
3269
-    }
3270
-
3271
-
3272
-    /**
3273
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3274
-     *
3275
-     * @access protected
3276
-     * @return void
3277
-     * @throws DomainException
3278
-     */
3279
-    protected function _set_m_mt_settings()
3280
-    {
3281
-        // first if this is already set then lets get out no need to regenerate data.
3282
-        if (! empty($this->_m_mt_settings)) {
3283
-            return;
3284
-        }
3285
-
3286
-        // get all installed messengers and message_types
3287
-        $messengers    = $this->_message_resource_manager->installed_messengers();
3288
-        $message_types = $this->_message_resource_manager->installed_message_types();
3289
-
3290
-
3291
-        // assemble the array for the _tab_text_links helper
3292
-
3293
-        foreach ($messengers as $messenger) {
3294
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = [
3295
-                'label' => ucwords($messenger->label['singular']),
3296
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3297
-                    ? 'messenger-active'
3298
-                    : '',
3299
-                'href'  => $messenger->name,
3300
-                'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3301
-                'slug'  => $messenger->name,
3302
-                'obj'   => $messenger,
3303
-            ];
3304
-
3305
-
3306
-            $message_types_for_messenger = $messenger->get_valid_message_types();
3307
-
3308
-            foreach ($message_types as $message_type) {
3309
-                // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3310
-                // it shouldn't show in either the inactive OR active metabox.
3311
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3312
-                    continue;
3313
-                }
3314
-
3315
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3316
-                    $messenger->name,
3317
-                    $message_type->name
3318
-                )
3319
-                    ? 'active'
3320
-                    : 'inactive';
3321
-
3322
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = [
3323
-                    'label'    => ucwords($message_type->label['singular']),
3324
-                    'class'    => 'message-type-' . $a_or_i,
3325
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3326
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3327
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3328
-                    'title'    => $a_or_i === 'active'
3329
-                        ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3330
-                        : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3331
-                    'content'  => $a_or_i === 'active'
3332
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
3333
-                        : $this->_message_type_settings_content($message_type, $messenger),
3334
-                    'slug'     => $message_type->name,
3335
-                    'active'   => $a_or_i === 'active',
3336
-                    'obj'      => $message_type,
3337
-                ];
3338
-            }
3339
-        }
3340
-    }
3341
-
3342
-
3343
-    /**
3344
-     * This just prepares the content for the message type settings
3345
-     *
3346
-     * @param EE_message_type $message_type The message type object
3347
-     * @param EE_messenger    $messenger    The messenger object
3348
-     * @param boolean         $active       Whether the message type is active or not
3349
-     * @return string html output for the content
3350
-     * @throws DomainException
3351
-     */
3352
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
3353
-    {
3354
-        // get message type fields
3355
-        $fields                                         = $message_type->get_admin_settings_fields();
3356
-        $settings_template_args['template_form_fields'] = '';
3357
-
3358
-        if (! empty($fields) && $active) {
3359
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3360
-            foreach ($fields as $fldname => $fldprops) {
3361
-                $field_id                         = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3362
-                $template_form_field[ $field_id ] = [
3363
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3364
-                    'label'      => $fldprops['label'],
3365
-                    'input'      => $fldprops['field_type'],
3366
-                    'type'       => $fldprops['value_type'],
3367
-                    'required'   => $fldprops['required'],
3368
-                    'validation' => $fldprops['validation'],
3369
-                    'value'      => isset($existing_settings[ $fldname ])
3370
-                        ? $existing_settings[ $fldname ]
3371
-                        : $fldprops['default'],
3372
-                    'options'    => isset($fldprops['options'])
3373
-                        ? $fldprops['options']
3374
-                        : [],
3375
-                    'default'    => isset($existing_settings[ $fldname ])
3376
-                        ? $existing_settings[ $fldname ]
3377
-                        : $fldprops['default'],
3378
-                    'css_class'  => 'no-drag',
3379
-                    'format'     => $fldprops['format'],
3380
-                ];
3381
-            }
3382
-
3383
-
3384
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3385
-                ? $this->_generate_admin_form_fields(
3386
-                    $template_form_field,
3387
-                    'string',
3388
-                    'ee_mt_activate_form'
3389
-                )
3390
-                : '';
3391
-        }
3392
-
3393
-        $settings_template_args['description'] = $message_type->description;
3394
-        // we also need some hidden fields
3395
-        $hidden_fields = [
3396
-            'message_type_settings[messenger]' . $message_type->name    => [
3397
-                'type'  => 'hidden',
3398
-                'value' => $messenger->name,
3399
-            ],
3400
-            'message_type_settings[message_type]' . $message_type->name => [
3401
-                'type'  => 'hidden',
3402
-                'value' => $message_type->name,
3403
-            ],
3404
-            'type' . $message_type->name                                => [
3405
-                'type'  => 'hidden',
3406
-                'value' => 'message_type',
3407
-            ],
3408
-        ];
3409
-
3410
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3411
-            $hidden_fields,
3412
-            'array'
3413
-        );
3414
-        $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields'])
3415
-            ? ' hidden'
3416
-            : '';
3417
-
3418
-
3419
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3420
-        return EEH_Template::display_template($template, $settings_template_args, true);
3421
-    }
3422
-
3423
-
3424
-    /**
3425
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
3426
-     *
3427
-     * @access protected
3428
-     * @return void
3429
-     * @throws DomainException
3430
-     */
3431
-    protected function _messages_settings_metaboxes()
3432
-    {
3433
-        $this->_set_m_mt_settings();
3434
-        $m_boxes         = $mt_boxes = [];
3435
-        $m_template_args = $mt_template_args = [];
3436
-
3437
-        $selected_messenger = $this->request->getRequestParam('selected_messenger', 'email');
3438
-
3439
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
3440
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3441
-                $is_messenger_active = $this->_message_resource_manager->is_messenger_active($messenger);
3442
-                $hide_on_message     = $is_messenger_active ? '' : 'hidden';
3443
-                $hide_off_message    = $is_messenger_active ? 'hidden' : '';
3444
-
3445
-                // messenger meta boxes
3446
-                $active         = $selected_messenger === $messenger;
3447
-                $active_mt_tabs = isset($this->_m_mt_settings['message_type_tabs'][ $messenger ]['active'])
3448
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3449
-                    : '';
3450
-
3451
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3452
-                    esc_html__('%s Settings', 'event_espresso'),
3453
-                    $tab_array['label']
3454
-                );
3455
-
3456
-                $m_template_args[ $messenger . '_a_box' ] = [
3457
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3458
-                    'inactive_message_types' => isset(
3459
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3460
-                    )
3461
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3462
-                        : '',
3463
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3464
-                    'hidden'                 => $active ? '' : ' hidden',
3465
-                    'hide_on_message'        => $hide_on_message,
3466
-                    'messenger'              => $messenger,
3467
-                    'active'                 => $active,
3468
-                ];
3469
-
3470
-                // message type meta boxes
3471
-                // (which is really just the inactive container for each messenger
3472
-                // showing inactive message types for that messenger)
3473
-                $mt_boxes[ $messenger . '_i_box' ]         = esc_html__('Inactive Message Types', 'event_espresso');
3474
-                $mt_template_args[ $messenger . '_i_box' ] = [
3475
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3476
-                    'inactive_message_types' => isset(
3477
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3478
-                    )
3479
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3480
-                        : '',
3481
-                    'hidden'                 => $active ? '' : ' hidden',
3482
-                    'hide_on_message'        => $hide_on_message,
3483
-                    'hide_off_message'       => $hide_off_message,
3484
-                    'messenger'              => $messenger,
3485
-                    'active'                 => $active,
3486
-                ];
3487
-            }
3488
-        }
3489
-
3490
-
3491
-        // register messenger metaboxes
3492
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3493
-        foreach ($m_boxes as $box => $label) {
3494
-            $callback_args = ['template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]];
3495
-            $msgr          = str_replace('_a_box', '', $box);
3496
-            add_meta_box(
3497
-                'espresso_' . $msgr . '_settings',
3498
-                $label,
3499
-                function ($post, $metabox) {
3500
-                    EEH_Template::display_template(
3501
-                        $metabox['args']['template_path'],
3502
-                        $metabox['args']['template_args']
3503
-                    );
3504
-                },
3505
-                $this->_current_screen->id,
3506
-                'normal',
3507
-                'high',
3508
-                $callback_args
3509
-            );
3510
-        }
3511
-
3512
-        // register message type metaboxes
3513
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3514
-        foreach ($mt_boxes as $box => $label) {
3515
-            $callback_args = [
3516
-                'template_path' => $mt_template_path,
3517
-                'template_args' => $mt_template_args[ $box ],
3518
-            ];
3519
-            $mt            = str_replace('_i_box', '', $box);
3520
-            add_meta_box(
3521
-                'espresso_' . $mt . '_inactive_mts',
3522
-                $label,
3523
-                function ($post, $metabox) {
3524
-                    EEH_Template::display_template(
3525
-                        $metabox['args']['template_path'],
3526
-                        $metabox['args']['template_args']
3527
-                    );
3528
-                },
3529
-                $this->_current_screen->id,
3530
-                'side',
3531
-                'high',
3532
-                $callback_args
3533
-            );
3534
-        }
3535
-
3536
-        // register metabox for global messages settings but only when on the main site.  On single site installs this
3537
-        // will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3538
-        if (is_main_site()) {
3539
-            add_meta_box(
3540
-                'espresso_global_message_settings',
3541
-                esc_html__('Global Message Settings', 'event_espresso'),
3542
-                [$this, 'global_messages_settings_metabox_content'],
3543
-                $this->_current_screen->id,
3544
-                'normal',
3545
-                'low',
3546
-                []
3547
-            );
3548
-        }
3549
-    }
3550
-
3551
-
3552
-    /**
3553
-     *  This generates the content for the global messages settings metabox.
3554
-     *
3555
-     * @return void
3556
-     * @throws EE_Error
3557
-     * @throws InvalidArgumentException
3558
-     * @throws ReflectionException
3559
-     * @throws InvalidDataTypeException
3560
-     * @throws InvalidInterfaceException
3561
-     */
3562
-    public function global_messages_settings_metabox_content()
3563
-    {
3564
-        $form = $this->_generate_global_settings_form();
3565
-        // already escaped
3566
-        echo $form->form_open(
3567
-            $this->add_query_args_and_nonce(['action' => 'update_global_settings'], EE_MSG_ADMIN_URL),
3568
-            'POST'
3569
-        );
3570
-        echo $form->get_html();
3571
-        echo $form->form_close();
3572
-    }
3573
-
3574
-
3575
-    /**
3576
-     * This generates and returns the form object for the global messages settings.
3577
-     *
3578
-     * @return EE_Form_Section_Proper
3579
-     * @throws EE_Error
3580
-     * @throws InvalidArgumentException
3581
-     * @throws ReflectionException
3582
-     * @throws InvalidDataTypeException
3583
-     * @throws InvalidInterfaceException
3584
-     */
3585
-    protected function _generate_global_settings_form()
3586
-    {
3587
-        /** @var EE_Network_Core_Config $network_config */
3588
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3589
-
3590
-        return new EE_Form_Section_Proper(
3591
-            [
3592
-                'name'            => 'global_messages_settings',
3593
-                'html_id'         => 'global_messages_settings',
3594
-                'html_class'      => 'form-table',
3595
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3596
-                'subsections'     => apply_filters(
3597
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3598
-                    [
3599
-                        'do_messages_on_same_request' => new EE_Select_Input(
3600
-                            [
3601
-                                true  => esc_html__('On the same request', 'event_espresso'),
3602
-                                false => esc_html__('On a separate request', 'event_espresso'),
3603
-                            ],
3604
-                            [
3605
-                                'default'         => $network_config->do_messages_on_same_request,
3606
-                                'html_label_text' => esc_html__(
3607
-                                    'Generate and send all messages:',
3608
-                                    'event_espresso'
3609
-                                ),
3610
-                                'html_help_text'  => esc_html__(
3611
-                                    'By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3612
-                                    'event_espresso'
3613
-                                ),
3614
-                            ]
3615
-                        ),
3616
-                        'delete_threshold'            => new EE_Select_Input(
3617
-                            [
3618
-                                0  => esc_html__('Forever', 'event_espresso'),
3619
-                                3  => esc_html__('3 Months', 'event_espresso'),
3620
-                                6  => esc_html__('6 Months', 'event_espresso'),
3621
-                                9  => esc_html__('9 Months', 'event_espresso'),
3622
-                                12 => esc_html__('12 Months', 'event_espresso'),
3623
-                                24 => esc_html__('24 Months', 'event_espresso'),
3624
-                                36 => esc_html__('36 Months', 'event_espresso'),
3625
-                            ],
3626
-                            [
3627
-                                'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3628
-                                'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3629
-                                'html_help_text'  => esc_html__(
3630
-                                    'You can control how long a record of processed messages is kept via this option.',
3631
-                                    'event_espresso'
3632
-                                ),
3633
-                            ]
3634
-                        ),
3635
-                        'update_settings'             => new EE_Submit_Input(
3636
-                            [
3637
-                                'default'         => esc_html__('Update', 'event_espresso'),
3638
-                                'html_label_text' => '&nbsp',
3639
-                            ]
3640
-                        ),
3641
-                    ]
3642
-                ),
3643
-            ]
3644
-        );
3645
-    }
3646
-
3647
-
3648
-    /**
3649
-     * This handles updating the global settings set on the admin page.
3650
-     *
3651
-     * @throws EE_Error
3652
-     * @throws InvalidDataTypeException
3653
-     * @throws InvalidInterfaceException
3654
-     * @throws InvalidArgumentException
3655
-     * @throws ReflectionException
3656
-     */
3657
-    protected function _update_global_settings()
3658
-    {
3659
-        /** @var EE_Network_Core_Config $network_config */
3660
-        $network_config  = EE_Registry::instance()->NET_CFG->core;
3661
-        $messages_config = EE_Registry::instance()->CFG->messages;
3662
-        $form            = $this->_generate_global_settings_form();
3663
-        if ($form->was_submitted()) {
3664
-            $form->receive_form_submission();
3665
-            if ($form->is_valid()) {
3666
-                $valid_data = $form->valid_data();
3667
-                foreach ($valid_data as $property => $value) {
3668
-                    $setter = 'set_' . $property;
3669
-                    if (method_exists($network_config, $setter)) {
3670
-                        $network_config->{$setter}($value);
3671
-                    } elseif (
3672
-                        property_exists($network_config, $property)
3673
-                        && $network_config->{$property} !== $value
3674
-                    ) {
3675
-                        $network_config->{$property} = $value;
3676
-                    } elseif (
3677
-                        property_exists($messages_config, $property)
3678
-                        && $messages_config->{$property} !== $value
3679
-                    ) {
3680
-                        $messages_config->{$property} = $value;
3681
-                    }
3682
-                }
3683
-                // only update if the form submission was valid!
3684
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3685
-                EE_Registry::instance()->CFG->update_espresso_config();
3686
-                EE_Error::overwrite_success();
3687
-                EE_Error::add_success(esc_html__('Global message settings were updated', 'event_espresso'));
3688
-            }
3689
-        }
3690
-        $this->_redirect_after_action(0, '', '', ['action' => 'settings'], true);
3691
-    }
3692
-
3693
-
3694
-    /**
3695
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3696
-     *
3697
-     * @param array $tab_array This is an array of message type tab details used to generate the tabs
3698
-     * @return string html formatted tabs
3699
-     * @throws DomainException
3700
-     */
3701
-    protected function _get_mt_tabs($tab_array)
3702
-    {
3703
-        $tab_array = (array) $tab_array;
3704
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3705
-        $tabs      = '';
3706
-
3707
-        foreach ($tab_array as $tab) {
3708
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3709
-        }
3710
-
3711
-        return $tabs;
3712
-    }
3713
-
3714
-
3715
-    /**
3716
-     * This prepares the content of the messenger meta box admin settings
3717
-     *
3718
-     * @param EE_messenger $messenger The messenger we're setting up content for
3719
-     * @return string html formatted content
3720
-     * @throws DomainException
3721
-     */
3722
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3723
-    {
3724
-
3725
-        $fields                                         = $messenger->get_admin_settings_fields();
3726
-        $settings_template_args['template_form_fields'] = '';
3727
-
3728
-        // is $messenger active?
3729
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3730
-
3731
-
3732
-        if (! empty($fields)) {
3733
-            $existing_settings = $messenger->get_existing_admin_settings();
3734
-
3735
-            foreach ($fields as $fldname => $fldprops) {
3736
-                $field_id                         = $messenger->name . '-' . $fldname;
3737
-                $template_form_field[ $field_id ] = [
3738
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3739
-                    'label'      => $fldprops['label'],
3740
-                    'input'      => $fldprops['field_type'],
3741
-                    'type'       => $fldprops['value_type'],
3742
-                    'required'   => $fldprops['required'],
3743
-                    'validation' => $fldprops['validation'],
3744
-                    'value'      => isset($existing_settings[ $field_id ])
3745
-                        ? $existing_settings[ $field_id ]
3746
-                        : $fldprops['default'],
3747
-                    'css_class'  => '',
3748
-                    'format'     => $fldprops['format'],
3749
-                ];
3750
-            }
3751
-
3752
-
3753
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3754
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3755
-                : '';
3756
-        }
3757
-
3758
-        // we also need some hidden fields
3759
-        $settings_template_args['hidden_fields'] = [
3760
-            'messenger_settings[messenger]' . $messenger->name => [
3761
-                'type'  => 'hidden',
3762
-                'value' => $messenger->name,
3763
-            ],
3764
-            'type' . $messenger->name                          => [
3765
-                'type'  => 'hidden',
3766
-                'value' => 'messenger',
3767
-            ],
3768
-        ];
3769
-
3770
-        // make sure any active message types that are existing are included in the hidden fields
3771
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3772
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3773
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = [
3774
-                    'type'  => 'hidden',
3775
-                    'value' => $mt,
3776
-                ];
3777
-            }
3778
-        }
3779
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3780
-            $settings_template_args['hidden_fields'],
3781
-            'array'
3782
-        );
3783
-        $active                                  =
3784
-            $this->_message_resource_manager->is_messenger_active($messenger->name);
3785
-
3786
-        $settings_template_args['messenger']           = $messenger->name;
3787
-        $settings_template_args['description']         = $messenger->description;
3788
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3789
-
3790
-
3791
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3792
-            $messenger->name
3793
-        )
3794
-            ? $settings_template_args['show_hide_edit_form']
3795
-            : ' hidden';
3796
-
3797
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3798
-            ? ' hidden'
3799
-            : $settings_template_args['show_hide_edit_form'];
3800
-
3801
-
3802
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3803
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3804
-        $settings_template_args['on_off_status'] = $active;
3805
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3806
-        return EEH_Template::display_template(
3807
-            $template,
3808
-            $settings_template_args,
3809
-            true
3810
-        );
3811
-    }
3812
-
3813
-
3814
-    /**
3815
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3816
-     *
3817
-     * @throws DomainException
3818
-     * @throws EE_Error
3819
-     * @throws InvalidDataTypeException
3820
-     * @throws InvalidInterfaceException
3821
-     * @throws InvalidArgumentException
3822
-     * @throws ReflectionException
3823
-     */
3824
-    public function activate_messenger_toggle()
3825
-    {
3826
-        $success = true;
3827
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3828
-        // let's check that we have required data
3829
-
3830
-        if (! $this->_active_messenger_name) {
3831
-            EE_Error::add_error(
3832
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3833
-                __FILE__,
3834
-                __FUNCTION__,
3835
-                __LINE__
3836
-            );
3837
-            $success = false;
3838
-        }
3839
-
3840
-        // do a nonce check here since we're not arriving via a normal route
3841
-        $nonce     = $this->request->getRequestParam('activate_nonce', '');
3842
-        $nonce_ref = "activate_{$this->_active_messenger_name}_toggle_nonce";
3843
-
3844
-        $this->_verify_nonce($nonce, $nonce_ref);
3845
-
3846
-
3847
-        $status = $this->request->getRequestParam('status');
3848
-        if (! $status) {
3849
-            EE_Error::add_error(
3850
-                esc_html__(
3851
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3852
-                    'event_espresso'
3853
-                ),
3854
-                __FILE__,
3855
-                __FUNCTION__,
3856
-                __LINE__
3857
-            );
3858
-            $success = false;
3859
-        }
3860
-
3861
-        // do check to verify we have a valid status.
3862
-        if ($status !== 'off' && $status !== 'on') {
3863
-            EE_Error::add_error(
3864
-                sprintf(
3865
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3866
-                    $status
3867
-                ),
3868
-                __FILE__,
3869
-                __FUNCTION__,
3870
-                __LINE__
3871
-            );
3872
-            $success = false;
3873
-        }
3874
-
3875
-        if ($success) {
3876
-            // made it here?  Stop dawdling then!!
3877
-            $success = $status === 'off'
3878
-                ? $this->_deactivate_messenger($this->_active_messenger_name)
3879
-                : $this->_activate_messenger($this->_active_messenger_name);
3880
-        }
3881
-
3882
-        $this->_template_args['success'] = $success;
3883
-
3884
-        // no special instructions so let's just do the json return (which should automatically do all the special stuff).
3885
-        $this->_return_json();
3886
-    }
3887
-
3888
-
3889
-    /**
3890
-     * used by ajax from the messages settings page to activate|deactivate a message type
3891
-     *
3892
-     * @throws DomainException
3893
-     * @throws EE_Error
3894
-     * @throws ReflectionException
3895
-     * @throws InvalidDataTypeException
3896
-     * @throws InvalidInterfaceException
3897
-     * @throws InvalidArgumentException
3898
-     */
3899
-    public function activate_mt_toggle()
3900
-    {
3901
-        $success = true;
3902
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3903
-
3904
-        // let's make sure we have the necessary data
3905
-        if (! $this->_active_message_type_name) {
3906
-            EE_Error::add_error(
3907
-                esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3908
-                __FILE__,
3909
-                __FUNCTION__,
3910
-                __LINE__
3911
-            );
3912
-            $success = false;
3913
-        }
3914
-
3915
-        if (! $this->_active_messenger_name) {
3916
-            EE_Error::add_error(
3917
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3918
-                __FILE__,
3919
-                __FUNCTION__,
3920
-                __LINE__
3921
-            );
3922
-            $success = false;
3923
-        }
3924
-
3925
-        $status = $this->request->getRequestParam('status');
3926
-        if (! $status) {
3927
-            EE_Error::add_error(
3928
-                esc_html__(
3929
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3930
-                    'event_espresso'
3931
-                ),
3932
-                __FILE__,
3933
-                __FUNCTION__,
3934
-                __LINE__
3935
-            );
3936
-            $success = false;
3937
-        }
3938
-
3939
-
3940
-        // do check to verify we have a valid status.
3941
-        if ($status !== 'activate' && $status !== 'deactivate') {
3942
-            EE_Error::add_error(
3943
-                sprintf(
3944
-                    esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3945
-                    $status
3946
-                ),
3947
-                __FILE__,
3948
-                __FUNCTION__,
3949
-                __LINE__
3950
-            );
3951
-            $success = false;
3952
-        }
3953
-
3954
-
3955
-        // do a nonce check here since we're not arriving via a normal route
3956
-        $nonce = $this->request->getRequestParam('mt_nonce', '');
3957
-        $this->_verify_nonce($nonce, "{$this->_active_message_type_name}_nonce");
3958
-
3959
-        if ($success) {
3960
-            // made it here? um, what are you waiting for then?
3961
-            $success = $status === 'deactivate'
3962
-                ? $this->_deactivate_message_type_for_messenger(
3963
-                    $this->_active_messenger_name,
3964
-                    $this->_active_message_type_name
3965
-                )
3966
-                : $this->_activate_message_type_for_messenger(
3967
-                    $this->_active_messenger_name,
3968
-                    $this->_active_message_type_name
3969
-                );
3970
-        }
3971
-
3972
-        $this->_template_args['success'] = $success;
3973
-        $this->_return_json();
3974
-    }
3975
-
3976
-
3977
-    /**
3978
-     * Takes care of processing activating a messenger and preparing the appropriate response.
3979
-     *
3980
-     * @param string $messenger_name The name of the messenger being activated
3981
-     * @return bool
3982
-     * @throws DomainException
3983
-     * @throws EE_Error
3984
-     * @throws InvalidArgumentException
3985
-     * @throws ReflectionException
3986
-     * @throws InvalidDataTypeException
3987
-     * @throws InvalidInterfaceException
3988
-     */
3989
-    protected function _activate_messenger($messenger_name)
3990
-    {
3991
-        $active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3992
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger
3993
-            ? $active_messenger->get_default_message_types()
3994
-            : [];
3995
-
3996
-        // ensure is active
3997
-        $this->_message_resource_manager->activate_messenger($active_messenger, $message_types_to_activate);
3998
-
3999
-        // set response_data for reload
4000
-        foreach ($message_types_to_activate as $message_type_name) {
4001
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4002
-            if (
4003
-                $this->_message_resource_manager->is_message_type_active_for_messenger(
4004
-                    $messenger_name,
4005
-                    $message_type_name
4006
-                )
4007
-                && $message_type instanceof EE_message_type
4008
-            ) {
4009
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
4010
-                if ($message_type->get_admin_settings_fields()) {
4011
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
4012
-                }
4013
-            }
4014
-        }
4015
-
4016
-        // add success message for activating messenger
4017
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4018
-    }
4019
-
4020
-
4021
-    /**
4022
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
4023
-     *
4024
-     * @param string $messenger_name The name of the messenger being activated
4025
-     * @return bool
4026
-     * @throws DomainException
4027
-     * @throws EE_Error
4028
-     * @throws InvalidArgumentException
4029
-     * @throws ReflectionException
4030
-     * @throws InvalidDataTypeException
4031
-     * @throws InvalidInterfaceException
4032
-     */
4033
-    protected function _deactivate_messenger($messenger_name)
4034
-    {
4035
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4036
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
4037
-
4038
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4039
-    }
4040
-
4041
-
4042
-    /**
4043
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4044
-     *
4045
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
4046
-     * @param string $message_type_name The name of the message type being activated for the messenger
4047
-     * @return bool
4048
-     * @throws DomainException
4049
-     * @throws EE_Error
4050
-     * @throws InvalidArgumentException
4051
-     * @throws ReflectionException
4052
-     * @throws InvalidDataTypeException
4053
-     * @throws InvalidInterfaceException
4054
-     */
4055
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4056
-    {
4057
-        $active_messenger         = $this->_message_resource_manager->get_messenger($messenger_name);
4058
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4059
-
4060
-        // ensure is active
4061
-        $this->_message_resource_manager->activate_messenger($active_messenger, $message_type_name);
4062
-
4063
-        // set response for load
4064
-        if (
4065
-            $this->_message_resource_manager->is_message_type_active_for_messenger(
4066
-                $messenger_name,
4067
-                $message_type_name
4068
-            )
4069
-        ) {
4070
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
4071
-            if ($message_type_to_activate->get_admin_settings_fields()) {
4072
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
4073
-            }
4074
-        }
4075
-
4076
-        return $this->_setup_response_message_for_activating_messenger_with_message_types(
4077
-            $active_messenger,
4078
-            $message_type_to_activate
4079
-        );
4080
-    }
4081
-
4082
-
4083
-    /**
4084
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4085
-     *
4086
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4087
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
4088
-     * @return bool
4089
-     * @throws DomainException
4090
-     * @throws EE_Error
4091
-     * @throws InvalidArgumentException
4092
-     * @throws ReflectionException
4093
-     * @throws InvalidDataTypeException
4094
-     * @throws InvalidInterfaceException
4095
-     */
4096
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4097
-    {
4098
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4099
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4100
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4101
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4102
-
4103
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4104
-            $active_messenger,
4105
-            $message_type_to_deactivate
4106
-        );
4107
-    }
4108
-
4109
-
4110
-    /**
4111
-     * This just initializes the defaults for activating messenger and message type responses.
4112
-     */
4113
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
4114
-    {
4115
-        $this->_template_args['data']['active_mts'] = [];
4116
-        $this->_template_args['data']['mt_reload']  = [];
4117
-    }
4118
-
4119
-
4120
-    /**
4121
-     * Setup appropriate response for activating a messenger and/or message types
4122
-     *
4123
-     * @param EE_messenger         $messenger
4124
-     * @param EE_message_type|null $message_type
4125
-     * @return bool
4126
-     * @throws DomainException
4127
-     * @throws EE_Error
4128
-     * @throws InvalidArgumentException
4129
-     * @throws ReflectionException
4130
-     * @throws InvalidDataTypeException
4131
-     * @throws InvalidInterfaceException
4132
-     */
4133
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
4134
-        $messenger,
4135
-        EE_Message_Type $message_type = null
4136
-    ) {
4137
-        // if $messenger isn't a valid messenger object then get out.
4138
-        if (! $messenger instanceof EE_Messenger) {
4139
-            EE_Error::add_error(
4140
-                esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4141
-                __FILE__,
4142
-                __FUNCTION__,
4143
-                __LINE__
4144
-            );
4145
-            return false;
4146
-        }
4147
-        // activated
4148
-        if ($this->_template_args['data']['active_mts']) {
4149
-            EE_Error::overwrite_success();
4150
-            // activated a message type with the messenger
4151
-            if ($message_type instanceof EE_message_type) {
4152
-                EE_Error::add_success(
4153
-                    sprintf(
4154
-                        esc_html__(
4155
-                            '%s message type has been successfully activated with the %s messenger',
4156
-                            'event_espresso'
4157
-                        ),
4158
-                        ucwords($message_type->label['singular']),
4159
-                        ucwords($messenger->label['singular'])
4160
-                    )
4161
-                );
4162
-
4163
-                // if message type was invoice then let's make sure we activate the invoice payment method.
4164
-                if ($message_type->name === 'invoice') {
4165
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
4166
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4167
-                    if ($pm instanceof EE_Payment_Method) {
4168
-                        EE_Error::add_attention(
4169
-                            esc_html__(
4170
-                                'Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
4171
-                                'event_espresso'
4172
-                            )
4173
-                        );
4174
-                    }
4175
-                }
4176
-                // just toggles the entire messenger
4177
-            } else {
4178
-                EE_Error::add_success(
4179
-                    sprintf(
4180
-                        esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4181
-                        ucwords($messenger->label['singular'])
4182
-                    )
4183
-                );
4184
-            }
4185
-
4186
-            return true;
4187
-
4188
-            // possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4189
-            // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4190
-            // in which case we just give a success message for the messenger being successfully activated.
4191
-        } else {
4192
-            if (! $messenger->get_default_message_types()) {
4193
-                // messenger doesn't have any default message types so still a success.
4194
-                EE_Error::add_success(
4195
-                    sprintf(
4196
-                        esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4197
-                        ucwords($messenger->label['singular'])
4198
-                    )
4199
-                );
4200
-
4201
-                return true;
4202
-            } else {
4203
-                EE_Error::add_error(
4204
-                    $message_type instanceof EE_message_type
4205
-                        ? sprintf(
4206
-                            esc_html__(
4207
-                                '%s message type was not successfully activated with the %s messenger',
4208
-                                'event_espresso'
4209
-                            ),
4210
-                            ucwords($message_type->label['singular']),
4211
-                            ucwords($messenger->label['singular'])
4212
-                        )
4213
-                        : sprintf(
4214
-                            esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4215
-                            ucwords($messenger->label['singular'])
4216
-                        ),
4217
-                    __FILE__,
4218
-                    __FUNCTION__,
4219
-                    __LINE__
4220
-                );
4221
-
4222
-                return false;
4223
-            }
4224
-        }
4225
-    }
4226
-
4227
-
4228
-    /**
4229
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
4230
-     *
4231
-     * @param EE_messenger         $messenger
4232
-     * @param EE_message_type|null $message_type
4233
-     * @return bool
4234
-     * @throws DomainException
4235
-     * @throws EE_Error
4236
-     * @throws InvalidArgumentException
4237
-     * @throws ReflectionException
4238
-     * @throws InvalidDataTypeException
4239
-     * @throws InvalidInterfaceException
4240
-     */
4241
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4242
-        $messenger,
4243
-        EE_message_type $message_type = null
4244
-    ) {
4245
-        EE_Error::overwrite_success();
4246
-
4247
-        // if $messenger isn't a valid messenger object then get out.
4248
-        if (! $messenger instanceof EE_Messenger) {
4249
-            EE_Error::add_error(
4250
-                esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4251
-                __FILE__,
4252
-                __FUNCTION__,
4253
-                __LINE__
4254
-            );
4255
-
4256
-            return false;
4257
-        }
4258
-
4259
-        if ($message_type instanceof EE_message_type) {
4260
-            $message_type_name = $message_type->name;
4261
-            EE_Error::add_success(
4262
-                sprintf(
4263
-                    esc_html__(
4264
-                        '%s message type has been successfully deactivated for the %s messenger.',
4265
-                        'event_espresso'
4266
-                    ),
4267
-                    ucwords($message_type->label['singular']),
4268
-                    ucwords($messenger->label['singular'])
4269
-                )
4270
-            );
4271
-        } else {
4272
-            $message_type_name = '';
4273
-            EE_Error::add_success(
4274
-                sprintf(
4275
-                    esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4276
-                    ucwords($messenger->label['singular'])
4277
-                )
4278
-            );
4279
-        }
4280
-
4281
-        // if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4282
-        if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4283
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
4284
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4285
-            if ($count_updated > 0) {
4286
-                $msg = $message_type_name === 'invoice'
4287
-                    ? esc_html__(
4288
-                        'Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
4289
-                        'event_espresso'
4290
-                    )
4291
-                    : esc_html__(
4292
-                        'Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
4293
-                        'event_espresso'
4294
-                    );
4295
-                EE_Error::add_attention($msg);
4296
-            }
4297
-        }
4298
-
4299
-        return true;
4300
-    }
4301
-
4302
-
4303
-    /**
4304
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4305
-     *
4306
-     * @throws DomainException
4307
-     * @throws EE_Error
4308
-     * @throws EE_Error
4309
-     */
4310
-    public function update_mt_form()
4311
-    {
4312
-        if (! $this->_active_messenger_name || ! $this->_active_message_type_name) {
4313
-            EE_Error::add_error(
4314
-                esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4315
-                __FILE__,
4316
-                __FUNCTION__,
4317
-                __LINE__
4318
-            );
4319
-            $this->_return_json();
4320
-        }
4321
-
4322
-        $message_types = $this->get_installed_message_types();
4323
-        $message_type  = $message_types[ $this->_active_message_type_name ];
4324
-        $messenger     = $this->_message_resource_manager->get_active_messenger($this->_active_messenger_name);
4325
-        $content       = $this->_message_type_settings_content($message_type, $messenger, true);
4326
-
4327
-        $this->_template_args['success'] = true;
4328
-        $this->_template_args['content'] = $content;
4329
-        $this->_return_json();
4330
-    }
4331
-
4332
-
4333
-    /**
4334
-     * this handles saving the settings for a messenger or message type
4335
-     *
4336
-     * @throws EE_Error
4337
-     * @throws EE_Error
4338
-     */
4339
-    public function save_settings()
4340
-    {
4341
-        $type = $this->request->getRequestParam('type');
4342
-        if (! $type) {
4343
-            EE_Error::add_error(
4344
-                esc_html__(
4345
-                    'Cannot save settings because type is unknown (messenger settings or message type settings?)',
4346
-                    'event_espresso'
4347
-                ),
4348
-                __FILE__,
4349
-                __FUNCTION__,
4350
-                __LINE__
4351
-            );
4352
-            $this->_template_args['error'] = true;
4353
-            $this->_return_json();
4354
-        }
4355
-
4356
-
4357
-        if ($type === 'messenger') {
4358
-            // this should be an array.
4359
-            $settings  = $this->request->getRequestParam('messenger_settings', [], 'string', true);
4360
-            $messenger = $settings['messenger'];
4361
-            // remove messenger and message_types from settings array
4362
-            unset($settings['messenger'], $settings['message_types']);
4363
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4364
-        } elseif ($type === 'message_type') {
4365
-            $settings     = $this->request->getRequestParam('message_type_settings', [], 'string', true);
4366
-            $messenger    = $settings['messenger'];
4367
-            $message_type = $settings['message_type'];
4368
-            // remove messenger and message_types from settings array
4369
-            unset($settings['messenger'], $settings['message_types']);
4370
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4371
-        }
4372
-
4373
-        // okay we should have the data all setup.  Now we just update!
4374
-        $success = $this->_message_resource_manager->update_active_messengers_option();
4375
-
4376
-        if ($success) {
4377
-            EE_Error::add_success(esc_html__('Settings updated', 'event_espresso'));
4378
-        } else {
4379
-            EE_Error::add_error(
4380
-                esc_html__('Settings did not get updated', 'event_espresso'),
4381
-                __FILE__,
4382
-                __FUNCTION__,
4383
-                __LINE__
4384
-            );
4385
-        }
4386
-
4387
-        $this->_template_args['success'] = $success;
4388
-        $this->_return_json();
4389
-    }
4390
-
4391
-
4392
-
4393
-
4394
-    /**  EE MESSAGE PROCESSING ACTIONS **/
4395
-
4396
-
4397
-    /**
4398
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4399
-     * However, this does not send immediately, it just queues for sending.
4400
-     *
4401
-     * @throws EE_Error
4402
-     * @throws InvalidDataTypeException
4403
-     * @throws InvalidInterfaceException
4404
-     * @throws InvalidArgumentException
4405
-     * @throws ReflectionException
4406
-     * @since 4.9.0
4407
-     */
4408
-    protected function _generate_now()
4409
-    {
4410
-        EED_Messages::generate_now($this->_get_msg_ids_from_request());
4411
-        $this->_redirect_after_action(false, '', '', [], true);
4412
-    }
4413
-
4414
-
4415
-    /**
4416
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4417
-     * are EEM_Message::status_resend or EEM_Message::status_idle
4418
-     *
4419
-     * @throws EE_Error
4420
-     * @throws InvalidDataTypeException
4421
-     * @throws InvalidInterfaceException
4422
-     * @throws InvalidArgumentException
4423
-     * @throws ReflectionException
4424
-     * @since 4.9.0
4425
-     */
4426
-    protected function _generate_and_send_now()
4427
-    {
4428
-        EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4429
-        $this->_redirect_after_action(false, '', '', [], true);
4430
-    }
4431
-
4432
-
4433
-    /**
4434
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4435
-     *
4436
-     * @throws EE_Error
4437
-     * @throws InvalidDataTypeException
4438
-     * @throws InvalidInterfaceException
4439
-     * @throws InvalidArgumentException
4440
-     * @throws ReflectionException
4441
-     * @since 4.9.0
4442
-     */
4443
-    protected function _queue_for_resending()
4444
-    {
4445
-        EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4446
-        $this->_redirect_after_action(false, '', '', [], true);
4447
-    }
4448
-
4449
-
4450
-    /**
4451
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4452
-     *
4453
-     * @throws EE_Error
4454
-     * @throws InvalidDataTypeException
4455
-     * @throws InvalidInterfaceException
4456
-     * @throws InvalidArgumentException
4457
-     * @throws ReflectionException
4458
-     * @since 4.9.0
4459
-     */
4460
-    protected function _send_now()
4461
-    {
4462
-        EED_Messages::send_now($this->_get_msg_ids_from_request());
4463
-        $this->_redirect_after_action(false, '', '', [], true);
4464
-    }
4465
-
4466
-
4467
-    /**
4468
-     * Deletes EE_messages for IDs in the request.
4469
-     *
4470
-     * @throws EE_Error
4471
-     * @throws InvalidDataTypeException
4472
-     * @throws InvalidInterfaceException
4473
-     * @throws InvalidArgumentException
4474
-     * @since 4.9.0
4475
-     */
4476
-    protected function _delete_ee_messages()
4477
-    {
4478
-        $MSG_IDs       = $this->_get_msg_ids_from_request();
4479
-        $deleted_count = 0;
4480
-        foreach ($MSG_IDs as $MSG_ID) {
4481
-            if (EEM_Message::instance()->delete_by_ID($MSG_ID)) {
4482
-                $deleted_count++;
4483
-            }
4484
-        }
4485
-        if ($deleted_count) {
4486
-            EE_Error::add_success(
4487
-                esc_html(
4488
-                    _n(
4489
-                        'Message successfully deleted',
4490
-                        'Messages successfully deleted',
4491
-                        $deleted_count,
4492
-                        'event_espresso'
4493
-                    )
4494
-                )
4495
-            );
4496
-        } else {
4497
-            EE_Error::add_error(
4498
-                _n('The message was not deleted.', 'The messages were not deleted', count($MSG_IDs), 'event_espresso'),
4499
-                __FILE__,
4500
-                __FUNCTION__,
4501
-                __LINE__
4502
-            );
4503
-        }
4504
-        $this->_redirect_after_action(false, '', '', [], true);
4505
-    }
4506
-
4507
-
4508
-    /**
4509
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4510
-     *
4511
-     * @return array
4512
-     * @since 4.9.0
4513
-     */
4514
-    protected function _get_msg_ids_from_request()
4515
-    {
4516
-        $MSG_IDs = $this->request->getRequestParam('MSG_ID', [], 'string', true);
4517
-        if (empty($MSG_IDs)) {
4518
-            return [];
4519
-        }
4520
-        // if 'MSG_ID' was just a single ID (not an array)
4521
-        // then $MSG_IDs will be something like [123] so $MSG_IDs[0] should be 123
4522
-        // otherwise, $MSG_IDs was already an array where message IDs were used as the keys
4523
-        return count($MSG_IDs) === 1 && isset($MSG_IDs[0])
4524
-            ? $MSG_IDs
4525
-            : array_keys($MSG_IDs);
4526
-    }
2661
+		$this->_context_switcher = ob_get_clean();
2662
+	}
2663
+
2664
+
2665
+	/**
2666
+	 * utility for sanitizing new values coming in.
2667
+	 * Note: this is only used when updating a context.
2668
+	 *
2669
+	 * @access protected
2670
+	 *
2671
+	 * @param int $index This helps us know which template field to select from the request array.
2672
+	 *
2673
+	 * @return array
2674
+	 */
2675
+	protected function _set_message_template_column_values($index)
2676
+	{
2677
+		return [
2678
+			'MTP_ID'             => $this->request->getRequestParam("MTP_template_fields[{$index}][MTP_ID]", 0, 'int'),
2679
+			'GRP_ID'             => $this->request->getRequestParam('GRP_ID', 0, 'int'),
2680
+			'MTP_user_id'        => $this->request->getRequestParam('MTP_user_id', 0, 'int'),
2681
+			'MTP_messenger'      => strtolower($this->request->getRequestParam('MTP_messenger', '')),
2682
+			'MTP_message_type'   => strtolower($this->request->getRequestParam('MTP_message_type', '')),
2683
+			'MTP_template_field' => strtolower(
2684
+				$this->request->getRequestParam("MTP_template_fields[{$index}][name]", '')
2685
+			),
2686
+			'MTP_context'        => strtolower($this->request->getRequestParam('MTP_context', '')),
2687
+			'MTP_content'        => $this->request->getRequestParam(
2688
+				"MTP_template_fields[{$index}][content]",
2689
+				'',
2690
+				'html'
2691
+			),
2692
+			'MTP_is_global'      => $this->request->getRequestParam('MTP_is_global', 0, 'int'),
2693
+			'MTP_is_override'    => $this->request->getRequestParam('MTP_is_override', 0, 'int'),
2694
+			'MTP_deleted'        => $this->request->getRequestParam('MTP_deleted', 0, 'int'),
2695
+			'MTP_is_active'      => $this->request->getRequestParam('MTP_is_active', 0, 'int'),
2696
+		];
2697
+	}
2698
+
2699
+
2700
+	/**
2701
+	 * @param bool $new
2702
+	 * @throws EE_Error
2703
+	 * @throws ReflectionException
2704
+	 */
2705
+	protected function _insert_or_update_message_template($new = false)
2706
+	{
2707
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2708
+		$success  = 0;
2709
+		$override = false;
2710
+
2711
+		// setup notices description
2712
+		$messenger_slug = $this->request->getRequestParam('MTP_messenger', '');
2713
+
2714
+		// need the message type and messenger objects to be able to use the labels for the notices
2715
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2716
+		$messenger_label  = $messenger_object instanceof EE_messenger
2717
+			? ucwords($messenger_object->label['singular'])
2718
+			: '';
2719
+
2720
+		$message_type_slug   = $this->request->getRequestParam('MTP_message_type', '');
2721
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2722
+
2723
+		$message_type_label = $message_type_object instanceof EE_message_type
2724
+			? ucwords($message_type_object->label['singular'])
2725
+			: '';
2726
+
2727
+		$context_slug = $this->request->getRequestParam('MTP_context', '');
2728
+		$context      = ucwords(str_replace('_', ' ', $context_slug));
2729
+
2730
+		$item_desc   = $messenger_label && $message_type_label
2731
+			? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2732
+			: '';
2733
+		$item_desc   .= 'Message Template';
2734
+		$query_args  = [];
2735
+		$edit_array  = [];
2736
+		$action_desc = '';
2737
+
2738
+		$GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
2739
+		// if this is "new" then we need to generate the default contexts
2740
+		// for the selected messenger/message_type for user to edit.
2741
+		if ($new) {
2742
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2743
+				if (empty($edit_array)) {
2744
+					$success = 0;
2745
+				} else {
2746
+					$success    = 1;
2747
+					$edit_array = $edit_array[0];
2748
+					$query_args = [
2749
+						'id'      => $edit_array['GRP_ID'],
2750
+						'context' => $edit_array['MTP_context'],
2751
+						'action'  => 'edit_message_template',
2752
+					];
2753
+				}
2754
+			}
2755
+			$action_desc = 'created';
2756
+		} else {
2757
+			$MTPG = EEM_Message_Template_Group::instance();
2758
+			$MTP  = EEM_Message_Template::instance();
2759
+
2760
+			// run update for each template field in displayed context
2761
+			$template_fields = $this->request->getRequestParam('MTP_template_fields', null, 'html', true);
2762
+			// messages content is expected to be escaped
2763
+			$template_fields = EEH_Array::addSlashesRecursively($template_fields);
2764
+
2765
+			if (! $template_fields) {
2766
+				EE_Error::add_error(
2767
+					esc_html__(
2768
+						'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2769
+						'event_espresso'
2770
+					),
2771
+					__FILE__,
2772
+					__FUNCTION__,
2773
+					__LINE__
2774
+				);
2775
+				$success = 0;
2776
+			} else {
2777
+				// first validate all fields!
2778
+				// this filter allows client code to add its own validation to the template fields as well.
2779
+				// returning an empty array means everything passed validation.
2780
+				// errors in validation should be represented in an array with the following shape:
2781
+				// array(
2782
+				//   'fieldname' => array(
2783
+				//          'msg' => 'error message'
2784
+				//          'value' => 'value for field producing error'
2785
+				// )
2786
+				$custom_validation = (array) apply_filters(
2787
+					'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2788
+					[],
2789
+					$template_fields,
2790
+					$context_slug,
2791
+					$messenger_slug,
2792
+					$message_type_slug
2793
+				);
2794
+
2795
+				$system_validation = $MTPG->validate(
2796
+					$template_fields,
2797
+					$context_slug,
2798
+					$messenger_slug,
2799
+					$message_type_slug
2800
+				);
2801
+
2802
+
2803
+				$system_validation = ! is_array($system_validation) && $system_validation ? [] : $system_validation;
2804
+				$validates         = array_merge($custom_validation, $system_validation);
2805
+
2806
+				// if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2807
+				// appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2808
+				//  WE need to make sure there is no actual error messages in validates.
2809
+				if (! empty($validates)) {
2810
+					// add the transient so when the form loads we know which fields to highlight
2811
+					$this->_add_transient('edit_message_template', $validates);
2812
+
2813
+					$success = 0;
2814
+
2815
+					// setup notices
2816
+					foreach ($validates as $error) {
2817
+						if (isset($error['msg'])) {
2818
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2819
+						}
2820
+					}
2821
+				} else {
2822
+					$success           = 1;
2823
+					$action_desc       = 'updated';
2824
+					$set_column_values = [];
2825
+					foreach ($template_fields as $template_field => $content) {
2826
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2827
+
2828
+						// if they aren't allowed to use all JS, restrict them to just posty-y tags
2829
+						if (! current_user_can('unfiltered_html')) {
2830
+							$set_column_values['MTP_content'] = $this->sanitizeMessageTemplateContent(
2831
+								$set_column_values['MTP_content']
2832
+							);
2833
+						}
2834
+						$message_template_fields = [
2835
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2836
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2837
+							'MTP_context'        => $set_column_values['MTP_context'],
2838
+							'MTP_content'        => $set_column_values['MTP_content'],
2839
+						];
2840
+
2841
+						$hasMtpID = ! empty($content['MTP_ID']);
2842
+						// if we have a MTP_ID for this field then update it, otherwise insert.
2843
+						// this has already been through the template field validator and sanitized, so it will be
2844
+						// safe to insert this field.  Why insert?  This typically happens when we introduce a new
2845
+						// message template field in a messenger/message type and existing users don't have the
2846
+						// default setup for it.
2847
+						// @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2848
+						$updated = $hasMtpID
2849
+							? $MTP->update($message_template_fields, [['MTP_ID' => $content['MTP_ID']]])
2850
+							: $MTP->insert($message_template_fields);
2851
+
2852
+						$insert_failed = ! $hasMtpID && ! $updated;
2853
+						// updates will return 0 if the field was not changed (ie: nothing actually updated)
2854
+						// but we won't consider that a problem, but if it returns false, then something went BOOM!
2855
+						$update_failed = ! $hasMtpID && $updated === false;
2856
+
2857
+						if ($insert_failed || $update_failed) {
2858
+							EE_Error::add_error(
2859
+								sprintf(
2860
+									esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2861
+									$template_field
2862
+								),
2863
+								__FILE__,
2864
+								__FUNCTION__,
2865
+								__LINE__
2866
+							);
2867
+							$success = 0;
2868
+						}
2869
+					}
2870
+
2871
+					// we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2872
+					$mtpg_fields = [
2873
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2874
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2875
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2876
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2877
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2878
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2879
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2880
+						'MTP_name'         => $this->request->getRequestParam('ee_msg_non_global_fields[MTP_name]', ''),
2881
+						'MTP_description'  => $this->request->getRequestParam(
2882
+							'ee_msg_non_global_fields[MTP_description]',
2883
+							''
2884
+						),
2885
+					];
2886
+
2887
+					$updated = $MTPG->update($mtpg_fields, [['GRP_ID' => $set_column_values['GRP_ID']]]);
2888
+
2889
+					if ($updated === false) {
2890
+						EE_Error::add_error(
2891
+							sprintf(
2892
+								esc_html__(
2893
+									'The Message Template Group (%d) was NOT updated for some reason',
2894
+									'event_espresso'
2895
+								),
2896
+								$set_column_values['GRP_ID']
2897
+							),
2898
+							__FILE__,
2899
+							__FUNCTION__,
2900
+							__LINE__
2901
+						);
2902
+						$success = 0;
2903
+					} else {
2904
+						// k now we need to ensure the template_pack and template_variation fields are set.
2905
+						$template_pack      = $this->request->getRequestParam('MTP_template_pack', 'default');
2906
+						$template_variation = $this->request->getRequestParam('MTP_template_variation', 'default');
2907
+
2908
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2909
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2910
+							$mtpg_obj->set_template_pack_name($template_pack);
2911
+							$mtpg_obj->set_template_pack_variation($template_variation);
2912
+						}
2913
+					}
2914
+				}
2915
+			}
2916
+		}
2917
+
2918
+		// we return things differently if doing ajax
2919
+		if ($this->request->isAjax()) {
2920
+			$this->_template_args['success'] = $success;
2921
+			$this->_template_args['error']   = ! $success;
2922
+			$this->_template_args['content'] = '';
2923
+			$this->_template_args['data']    = [
2924
+				'grpID'        => $edit_array['GRP_ID'],
2925
+				'templateName' => $edit_array['template_name'],
2926
+			];
2927
+			if ($success) {
2928
+				EE_Error::overwrite_success();
2929
+				EE_Error::add_success(
2930
+					esc_html__(
2931
+						'The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2932
+						'event_espresso'
2933
+					)
2934
+				);
2935
+			}
2936
+
2937
+			$this->_return_json();
2938
+		}
2939
+
2940
+
2941
+		// was a test send triggered?
2942
+		if ($this->request->getRequestParam('test_button', false, 'bool')) {
2943
+			EE_Error::overwrite_success();
2944
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2945
+			$override = true;
2946
+		}
2947
+
2948
+		$query_args = ! empty($query_args)
2949
+			? $query_args
2950
+			: [
2951
+				'id'      => $GRP_ID,
2952
+				'context' => $context_slug,
2953
+				'action'  => 'edit_message_template',
2954
+			];
2955
+
2956
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2957
+	}
2958
+
2959
+
2960
+	/**
2961
+	 * recursively runs wp_kses() on message template content in a model safe manner
2962
+	 *
2963
+	 * @param array|string $content
2964
+	 * @return array|string
2965
+	 * @since   $VID:$
2966
+	 */
2967
+	private function sanitizeMessageTemplateContent($content)
2968
+	{
2969
+		if (is_array($content)) {
2970
+			foreach ($content as $key => $value) {
2971
+				$content[ $key ] = $this->sanitizeMessageTemplateContent($value);
2972
+			}
2973
+			return $content;
2974
+		}
2975
+		// remove slashes so wp_kses() works properly
2976
+		// wp_kses_stripslashes() only removes slashes from double-quotes,
2977
+		// so attributes using single quotes always appear invalid.
2978
+		$content = stripslashes($content);
2979
+		$content = wp_kses($content, wp_kses_allowed_html('post'));
2980
+		// But currently the models expect slashed data, so after wp_kses()
2981
+		// runs we need to re-slash the data. Sheesh.
2982
+		// See https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2983
+		return addslashes($content);
2984
+	}
2985
+
2986
+
2987
+	/**
2988
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
2989
+	 *
2990
+	 * @param string $context      what context being tested
2991
+	 * @param string $messenger    messenger being tested
2992
+	 * @param string $message_type message type being tested
2993
+	 * @throws EE_Error
2994
+	 * @throws InvalidArgumentException
2995
+	 * @throws InvalidDataTypeException
2996
+	 * @throws InvalidInterfaceException
2997
+	 * @throws ReflectionException
2998
+	 */
2999
+	protected function _do_test_send($context, $messenger, $message_type)
3000
+	{
3001
+		// set things up for preview
3002
+		$this->request->setRequestParam('messenger', $messenger);
3003
+		$this->request->setRequestParam('message_type', $message_type);
3004
+		$this->request->setRequestParam('context', $context);
3005
+		$GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
3006
+		$this->request->setRequestParam('GRP_ID', $GRP_ID);
3007
+
3008
+		$active_messenger  = $this->_message_resource_manager->get_active_messenger($messenger);
3009
+		$test_settings_fld = $this->request->getRequestParam('test_settings_fld', [], 'string', true);
3010
+
3011
+		// let's save any existing fields that might be required by the messenger
3012
+		if (
3013
+			! empty($test_settings_fld)
3014
+			&& $active_messenger instanceof EE_messenger
3015
+			&& apply_filters(
3016
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3017
+				true,
3018
+				$test_settings_fld,
3019
+				$active_messenger
3020
+			)
3021
+		) {
3022
+			$active_messenger->set_existing_test_settings($test_settings_fld);
3023
+		}
3024
+
3025
+		/**
3026
+		 * Use filter to add additional controls on whether message can send or not
3027
+		 */
3028
+		if (
3029
+			apply_filters(
3030
+				'FHEE__Messages_Admin_Page__do_test_send__can_send',
3031
+				true,
3032
+				$context,
3033
+				$this->request->requestParams(),
3034
+				$messenger,
3035
+				$message_type
3036
+			)
3037
+		) {
3038
+			if (EEM_Event::instance()->count() > 0) {
3039
+				$success = $this->_preview_message(true);
3040
+				if ($success) {
3041
+					EE_Error::add_success(esc_html__('Test message sent', 'event_espresso'));
3042
+				} else {
3043
+					EE_Error::add_error(
3044
+						esc_html__('The test message was not sent', 'event_espresso'),
3045
+						__FILE__,
3046
+						__FUNCTION__,
3047
+						__LINE__
3048
+					);
3049
+				}
3050
+			} else {
3051
+				$this->noEventsErrorMessage(true);
3052
+			}
3053
+		}
3054
+	}
3055
+
3056
+
3057
+	/**
3058
+	 * _generate_new_templates
3059
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3060
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3061
+	 * for the event.
3062
+	 *
3063
+	 *
3064
+	 * @param string $messenger      the messenger we are generating templates for
3065
+	 * @param array  $message_types  array of message types that the templates are generated for.
3066
+	 * @param int    $GRP_ID         If this is a custom template being generated then a GRP_ID needs to be included to
3067
+	 *                               indicate the message_template_group being used as the base.
3068
+	 *
3069
+	 * @param bool   $global
3070
+	 *
3071
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
3072
+	 *                               encountering problems.
3073
+	 * @throws EE_Error
3074
+	 * @throws ReflectionException
3075
+	 */
3076
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3077
+	{
3078
+
3079
+		// if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3080
+		// just don't generate any templates.
3081
+		if (empty($message_types)) {
3082
+			return true;
3083
+		}
3084
+
3085
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3086
+	}
3087
+
3088
+
3089
+	/**
3090
+	 * [_trash_or_restore_message_template]
3091
+	 *
3092
+	 * @param boolean $trash  whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3093
+	 * @param boolean $all    whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3094
+	 *                        an individual context (FALSE).
3095
+	 * @return void
3096
+	 * @throws EE_Error
3097
+	 * @throws InvalidArgumentException
3098
+	 * @throws InvalidDataTypeException
3099
+	 * @throws InvalidInterfaceException
3100
+	 */
3101
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
3102
+	{
3103
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3104
+		$MTP = EEM_Message_Template_Group::instance();
3105
+
3106
+		$success = 1;
3107
+
3108
+		// incoming GRP_IDs
3109
+		if ($all) {
3110
+			// Checkboxes
3111
+			$checkboxes = $this->request->getRequestParam('checkbox', [], 'int', true);
3112
+			if (! empty($checkboxes)) {
3113
+				// if array has more than one element then success message should be plural.
3114
+				// todo: what about nonce?
3115
+				$success = count($checkboxes) > 1 ? 2 : 1;
3116
+
3117
+				// cycle through checkboxes
3118
+				while (list($GRP_ID, $value) = each($checkboxes)) {
3119
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3120
+					if (! $trashed_or_restored) {
3121
+						$success = 0;
3122
+					}
3123
+				}
3124
+			} else {
3125
+				// grab single GRP_ID and handle
3126
+				$GRP_ID = $this->request->getRequestParam('id', 0, 'int');
3127
+				if (! empty($GRP_ID)) {
3128
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3129
+					if (! $trashed_or_restored) {
3130
+						$success = 0;
3131
+					}
3132
+				} else {
3133
+					$success = 0;
3134
+				}
3135
+			}
3136
+		}
3137
+
3138
+		$action_desc = $trash
3139
+			? esc_html__('moved to the trash', 'event_espresso')
3140
+			: esc_html__('restored', 'event_espresso');
3141
+
3142
+		$template_switch = $this->request->getRequestParam('template_switch', false, 'bool');
3143
+		$action_desc     = $template_switch ? esc_html__('switched', 'event_espresso') : $action_desc;
3144
+
3145
+		$item_desc = $all ? _n(
3146
+			'Message Template Group',
3147
+			'Message Template Groups',
3148
+			$success,
3149
+			'event_espresso'
3150
+		) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3151
+
3152
+		$item_desc = $template_switch
3153
+			? _n('template', 'templates', $success, 'event_espresso')
3154
+			: $item_desc;
3155
+
3156
+		$this->_redirect_after_action($success, $item_desc, $action_desc, []);
3157
+	}
3158
+
3159
+
3160
+	/**
3161
+	 * [_delete_message_template]
3162
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3163
+	 *
3164
+	 * @return void
3165
+	 * @throws EE_Error
3166
+	 * @throws InvalidArgumentException
3167
+	 * @throws InvalidDataTypeException
3168
+	 * @throws InvalidInterfaceException
3169
+	 * @throws ReflectionException
3170
+	 */
3171
+	protected function _delete_message_template()
3172
+	{
3173
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3174
+
3175
+		// checkboxes
3176
+		$checkboxes = $this->request->getRequestParam('checkbox', [], 'int', true);
3177
+		if (! empty($checkboxes)) {
3178
+			// if array has more than one element then success message should be plural
3179
+			$success = count($checkboxes) > 1 ? 2 : 1;
3180
+
3181
+			// cycle through bulk action checkboxes
3182
+			while (list($GRP_ID, $value) = each($checkboxes)) {
3183
+				$success = $this->_delete_mtp_permanently($GRP_ID) ? $success : false;
3184
+			}
3185
+		} else {
3186
+			// grab single grp_id and delete
3187
+			$GRP_ID  = $this->request->getRequestParam('id', 0, 'int');
3188
+			$success = $this->_delete_mtp_permanently($GRP_ID);
3189
+		}
3190
+
3191
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', []);
3192
+	}
3193
+
3194
+
3195
+	/**
3196
+	 * helper for permanently deleting a mtP group and all related message_templates
3197
+	 *
3198
+	 * @param int  $GRP_ID        The group being deleted
3199
+	 * @param bool $include_group whether to delete the Message Template Group as well.
3200
+	 * @return bool boolean to indicate the success of the deletes or not.
3201
+	 * @throws EE_Error
3202
+	 * @throws InvalidArgumentException
3203
+	 * @throws InvalidDataTypeException
3204
+	 * @throws InvalidInterfaceException
3205
+	 * @throws ReflectionException
3206
+	 * @throws ReflectionException
3207
+	 */
3208
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3209
+	{
3210
+		$success = true;
3211
+		$MTPG    = EEM_Message_Template_Group::instance();
3212
+		// first let's GET this group
3213
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
3214
+		// then delete permanently all the related Message Templates
3215
+		$deleted = $MTG->delete_related_permanently('Message_Template');
3216
+
3217
+		if ($deleted === 0) {
3218
+			$success = false;
3219
+		}
3220
+
3221
+		// now delete permanently this particular group
3222
+
3223
+		if ($include_group && ! $MTG->delete_permanently()) {
3224
+			$success = false;
3225
+		}
3226
+
3227
+		return $success;
3228
+	}
3229
+
3230
+
3231
+	/**
3232
+	 *    _learn_more_about_message_templates_link
3233
+	 *
3234
+	 * @access protected
3235
+	 * @return string
3236
+	 */
3237
+	protected function _learn_more_about_message_templates_link()
3238
+	{
3239
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3240
+			   . esc_html__('learn more about how message templates works', 'event_espresso')
3241
+			   . '</a>';
3242
+	}
3243
+
3244
+
3245
+	/**
3246
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3247
+	 * ajax and other routes.
3248
+	 *
3249
+	 * @return void
3250
+	 * @throws DomainException
3251
+	 * @throws EE_Error
3252
+	 */
3253
+	protected function _settings()
3254
+	{
3255
+		$this->_set_m_mt_settings();
3256
+
3257
+		// let's setup the messenger tabs
3258
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3259
+			$this->_m_mt_settings['messenger_tabs'],
3260
+			'messenger_links',
3261
+			'|',
3262
+			$this->request->getRequestParam('selected_messenger', 'email')
3263
+		);
3264
+
3265
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3266
+		$this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
3267
+
3268
+		$this->display_admin_page_with_sidebar();
3269
+	}
3270
+
3271
+
3272
+	/**
3273
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3274
+	 *
3275
+	 * @access protected
3276
+	 * @return void
3277
+	 * @throws DomainException
3278
+	 */
3279
+	protected function _set_m_mt_settings()
3280
+	{
3281
+		// first if this is already set then lets get out no need to regenerate data.
3282
+		if (! empty($this->_m_mt_settings)) {
3283
+			return;
3284
+		}
3285
+
3286
+		// get all installed messengers and message_types
3287
+		$messengers    = $this->_message_resource_manager->installed_messengers();
3288
+		$message_types = $this->_message_resource_manager->installed_message_types();
3289
+
3290
+
3291
+		// assemble the array for the _tab_text_links helper
3292
+
3293
+		foreach ($messengers as $messenger) {
3294
+			$this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = [
3295
+				'label' => ucwords($messenger->label['singular']),
3296
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3297
+					? 'messenger-active'
3298
+					: '',
3299
+				'href'  => $messenger->name,
3300
+				'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3301
+				'slug'  => $messenger->name,
3302
+				'obj'   => $messenger,
3303
+			];
3304
+
3305
+
3306
+			$message_types_for_messenger = $messenger->get_valid_message_types();
3307
+
3308
+			foreach ($message_types as $message_type) {
3309
+				// first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3310
+				// it shouldn't show in either the inactive OR active metabox.
3311
+				if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3312
+					continue;
3313
+				}
3314
+
3315
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3316
+					$messenger->name,
3317
+					$message_type->name
3318
+				)
3319
+					? 'active'
3320
+					: 'inactive';
3321
+
3322
+				$this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = [
3323
+					'label'    => ucwords($message_type->label['singular']),
3324
+					'class'    => 'message-type-' . $a_or_i,
3325
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3326
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3327
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3328
+					'title'    => $a_or_i === 'active'
3329
+						? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3330
+						: esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3331
+					'content'  => $a_or_i === 'active'
3332
+						? $this->_message_type_settings_content($message_type, $messenger, true)
3333
+						: $this->_message_type_settings_content($message_type, $messenger),
3334
+					'slug'     => $message_type->name,
3335
+					'active'   => $a_or_i === 'active',
3336
+					'obj'      => $message_type,
3337
+				];
3338
+			}
3339
+		}
3340
+	}
3341
+
3342
+
3343
+	/**
3344
+	 * This just prepares the content for the message type settings
3345
+	 *
3346
+	 * @param EE_message_type $message_type The message type object
3347
+	 * @param EE_messenger    $messenger    The messenger object
3348
+	 * @param boolean         $active       Whether the message type is active or not
3349
+	 * @return string html output for the content
3350
+	 * @throws DomainException
3351
+	 */
3352
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
3353
+	{
3354
+		// get message type fields
3355
+		$fields                                         = $message_type->get_admin_settings_fields();
3356
+		$settings_template_args['template_form_fields'] = '';
3357
+
3358
+		if (! empty($fields) && $active) {
3359
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3360
+			foreach ($fields as $fldname => $fldprops) {
3361
+				$field_id                         = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3362
+				$template_form_field[ $field_id ] = [
3363
+					'name'       => 'message_type_settings[' . $fldname . ']',
3364
+					'label'      => $fldprops['label'],
3365
+					'input'      => $fldprops['field_type'],
3366
+					'type'       => $fldprops['value_type'],
3367
+					'required'   => $fldprops['required'],
3368
+					'validation' => $fldprops['validation'],
3369
+					'value'      => isset($existing_settings[ $fldname ])
3370
+						? $existing_settings[ $fldname ]
3371
+						: $fldprops['default'],
3372
+					'options'    => isset($fldprops['options'])
3373
+						? $fldprops['options']
3374
+						: [],
3375
+					'default'    => isset($existing_settings[ $fldname ])
3376
+						? $existing_settings[ $fldname ]
3377
+						: $fldprops['default'],
3378
+					'css_class'  => 'no-drag',
3379
+					'format'     => $fldprops['format'],
3380
+				];
3381
+			}
3382
+
3383
+
3384
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3385
+				? $this->_generate_admin_form_fields(
3386
+					$template_form_field,
3387
+					'string',
3388
+					'ee_mt_activate_form'
3389
+				)
3390
+				: '';
3391
+		}
3392
+
3393
+		$settings_template_args['description'] = $message_type->description;
3394
+		// we also need some hidden fields
3395
+		$hidden_fields = [
3396
+			'message_type_settings[messenger]' . $message_type->name    => [
3397
+				'type'  => 'hidden',
3398
+				'value' => $messenger->name,
3399
+			],
3400
+			'message_type_settings[message_type]' . $message_type->name => [
3401
+				'type'  => 'hidden',
3402
+				'value' => $message_type->name,
3403
+			],
3404
+			'type' . $message_type->name                                => [
3405
+				'type'  => 'hidden',
3406
+				'value' => 'message_type',
3407
+			],
3408
+		];
3409
+
3410
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3411
+			$hidden_fields,
3412
+			'array'
3413
+		);
3414
+		$settings_template_args['show_form']     = empty($settings_template_args['template_form_fields'])
3415
+			? ' hidden'
3416
+			: '';
3417
+
3418
+
3419
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3420
+		return EEH_Template::display_template($template, $settings_template_args, true);
3421
+	}
3422
+
3423
+
3424
+	/**
3425
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
3426
+	 *
3427
+	 * @access protected
3428
+	 * @return void
3429
+	 * @throws DomainException
3430
+	 */
3431
+	protected function _messages_settings_metaboxes()
3432
+	{
3433
+		$this->_set_m_mt_settings();
3434
+		$m_boxes         = $mt_boxes = [];
3435
+		$m_template_args = $mt_template_args = [];
3436
+
3437
+		$selected_messenger = $this->request->getRequestParam('selected_messenger', 'email');
3438
+
3439
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
3440
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3441
+				$is_messenger_active = $this->_message_resource_manager->is_messenger_active($messenger);
3442
+				$hide_on_message     = $is_messenger_active ? '' : 'hidden';
3443
+				$hide_off_message    = $is_messenger_active ? 'hidden' : '';
3444
+
3445
+				// messenger meta boxes
3446
+				$active         = $selected_messenger === $messenger;
3447
+				$active_mt_tabs = isset($this->_m_mt_settings['message_type_tabs'][ $messenger ]['active'])
3448
+					? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3449
+					: '';
3450
+
3451
+				$m_boxes[ $messenger . '_a_box' ] = sprintf(
3452
+					esc_html__('%s Settings', 'event_espresso'),
3453
+					$tab_array['label']
3454
+				);
3455
+
3456
+				$m_template_args[ $messenger . '_a_box' ] = [
3457
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3458
+					'inactive_message_types' => isset(
3459
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3460
+					)
3461
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3462
+						: '',
3463
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3464
+					'hidden'                 => $active ? '' : ' hidden',
3465
+					'hide_on_message'        => $hide_on_message,
3466
+					'messenger'              => $messenger,
3467
+					'active'                 => $active,
3468
+				];
3469
+
3470
+				// message type meta boxes
3471
+				// (which is really just the inactive container for each messenger
3472
+				// showing inactive message types for that messenger)
3473
+				$mt_boxes[ $messenger . '_i_box' ]         = esc_html__('Inactive Message Types', 'event_espresso');
3474
+				$mt_template_args[ $messenger . '_i_box' ] = [
3475
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3476
+					'inactive_message_types' => isset(
3477
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3478
+					)
3479
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3480
+						: '',
3481
+					'hidden'                 => $active ? '' : ' hidden',
3482
+					'hide_on_message'        => $hide_on_message,
3483
+					'hide_off_message'       => $hide_off_message,
3484
+					'messenger'              => $messenger,
3485
+					'active'                 => $active,
3486
+				];
3487
+			}
3488
+		}
3489
+
3490
+
3491
+		// register messenger metaboxes
3492
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3493
+		foreach ($m_boxes as $box => $label) {
3494
+			$callback_args = ['template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]];
3495
+			$msgr          = str_replace('_a_box', '', $box);
3496
+			add_meta_box(
3497
+				'espresso_' . $msgr . '_settings',
3498
+				$label,
3499
+				function ($post, $metabox) {
3500
+					EEH_Template::display_template(
3501
+						$metabox['args']['template_path'],
3502
+						$metabox['args']['template_args']
3503
+					);
3504
+				},
3505
+				$this->_current_screen->id,
3506
+				'normal',
3507
+				'high',
3508
+				$callback_args
3509
+			);
3510
+		}
3511
+
3512
+		// register message type metaboxes
3513
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3514
+		foreach ($mt_boxes as $box => $label) {
3515
+			$callback_args = [
3516
+				'template_path' => $mt_template_path,
3517
+				'template_args' => $mt_template_args[ $box ],
3518
+			];
3519
+			$mt            = str_replace('_i_box', '', $box);
3520
+			add_meta_box(
3521
+				'espresso_' . $mt . '_inactive_mts',
3522
+				$label,
3523
+				function ($post, $metabox) {
3524
+					EEH_Template::display_template(
3525
+						$metabox['args']['template_path'],
3526
+						$metabox['args']['template_args']
3527
+					);
3528
+				},
3529
+				$this->_current_screen->id,
3530
+				'side',
3531
+				'high',
3532
+				$callback_args
3533
+			);
3534
+		}
3535
+
3536
+		// register metabox for global messages settings but only when on the main site.  On single site installs this
3537
+		// will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3538
+		if (is_main_site()) {
3539
+			add_meta_box(
3540
+				'espresso_global_message_settings',
3541
+				esc_html__('Global Message Settings', 'event_espresso'),
3542
+				[$this, 'global_messages_settings_metabox_content'],
3543
+				$this->_current_screen->id,
3544
+				'normal',
3545
+				'low',
3546
+				[]
3547
+			);
3548
+		}
3549
+	}
3550
+
3551
+
3552
+	/**
3553
+	 *  This generates the content for the global messages settings metabox.
3554
+	 *
3555
+	 * @return void
3556
+	 * @throws EE_Error
3557
+	 * @throws InvalidArgumentException
3558
+	 * @throws ReflectionException
3559
+	 * @throws InvalidDataTypeException
3560
+	 * @throws InvalidInterfaceException
3561
+	 */
3562
+	public function global_messages_settings_metabox_content()
3563
+	{
3564
+		$form = $this->_generate_global_settings_form();
3565
+		// already escaped
3566
+		echo $form->form_open(
3567
+			$this->add_query_args_and_nonce(['action' => 'update_global_settings'], EE_MSG_ADMIN_URL),
3568
+			'POST'
3569
+		);
3570
+		echo $form->get_html();
3571
+		echo $form->form_close();
3572
+	}
3573
+
3574
+
3575
+	/**
3576
+	 * This generates and returns the form object for the global messages settings.
3577
+	 *
3578
+	 * @return EE_Form_Section_Proper
3579
+	 * @throws EE_Error
3580
+	 * @throws InvalidArgumentException
3581
+	 * @throws ReflectionException
3582
+	 * @throws InvalidDataTypeException
3583
+	 * @throws InvalidInterfaceException
3584
+	 */
3585
+	protected function _generate_global_settings_form()
3586
+	{
3587
+		/** @var EE_Network_Core_Config $network_config */
3588
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3589
+
3590
+		return new EE_Form_Section_Proper(
3591
+			[
3592
+				'name'            => 'global_messages_settings',
3593
+				'html_id'         => 'global_messages_settings',
3594
+				'html_class'      => 'form-table',
3595
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3596
+				'subsections'     => apply_filters(
3597
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3598
+					[
3599
+						'do_messages_on_same_request' => new EE_Select_Input(
3600
+							[
3601
+								true  => esc_html__('On the same request', 'event_espresso'),
3602
+								false => esc_html__('On a separate request', 'event_espresso'),
3603
+							],
3604
+							[
3605
+								'default'         => $network_config->do_messages_on_same_request,
3606
+								'html_label_text' => esc_html__(
3607
+									'Generate and send all messages:',
3608
+									'event_espresso'
3609
+								),
3610
+								'html_help_text'  => esc_html__(
3611
+									'By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3612
+									'event_espresso'
3613
+								),
3614
+							]
3615
+						),
3616
+						'delete_threshold'            => new EE_Select_Input(
3617
+							[
3618
+								0  => esc_html__('Forever', 'event_espresso'),
3619
+								3  => esc_html__('3 Months', 'event_espresso'),
3620
+								6  => esc_html__('6 Months', 'event_espresso'),
3621
+								9  => esc_html__('9 Months', 'event_espresso'),
3622
+								12 => esc_html__('12 Months', 'event_espresso'),
3623
+								24 => esc_html__('24 Months', 'event_espresso'),
3624
+								36 => esc_html__('36 Months', 'event_espresso'),
3625
+							],
3626
+							[
3627
+								'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3628
+								'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3629
+								'html_help_text'  => esc_html__(
3630
+									'You can control how long a record of processed messages is kept via this option.',
3631
+									'event_espresso'
3632
+								),
3633
+							]
3634
+						),
3635
+						'update_settings'             => new EE_Submit_Input(
3636
+							[
3637
+								'default'         => esc_html__('Update', 'event_espresso'),
3638
+								'html_label_text' => '&nbsp',
3639
+							]
3640
+						),
3641
+					]
3642
+				),
3643
+			]
3644
+		);
3645
+	}
3646
+
3647
+
3648
+	/**
3649
+	 * This handles updating the global settings set on the admin page.
3650
+	 *
3651
+	 * @throws EE_Error
3652
+	 * @throws InvalidDataTypeException
3653
+	 * @throws InvalidInterfaceException
3654
+	 * @throws InvalidArgumentException
3655
+	 * @throws ReflectionException
3656
+	 */
3657
+	protected function _update_global_settings()
3658
+	{
3659
+		/** @var EE_Network_Core_Config $network_config */
3660
+		$network_config  = EE_Registry::instance()->NET_CFG->core;
3661
+		$messages_config = EE_Registry::instance()->CFG->messages;
3662
+		$form            = $this->_generate_global_settings_form();
3663
+		if ($form->was_submitted()) {
3664
+			$form->receive_form_submission();
3665
+			if ($form->is_valid()) {
3666
+				$valid_data = $form->valid_data();
3667
+				foreach ($valid_data as $property => $value) {
3668
+					$setter = 'set_' . $property;
3669
+					if (method_exists($network_config, $setter)) {
3670
+						$network_config->{$setter}($value);
3671
+					} elseif (
3672
+						property_exists($network_config, $property)
3673
+						&& $network_config->{$property} !== $value
3674
+					) {
3675
+						$network_config->{$property} = $value;
3676
+					} elseif (
3677
+						property_exists($messages_config, $property)
3678
+						&& $messages_config->{$property} !== $value
3679
+					) {
3680
+						$messages_config->{$property} = $value;
3681
+					}
3682
+				}
3683
+				// only update if the form submission was valid!
3684
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3685
+				EE_Registry::instance()->CFG->update_espresso_config();
3686
+				EE_Error::overwrite_success();
3687
+				EE_Error::add_success(esc_html__('Global message settings were updated', 'event_espresso'));
3688
+			}
3689
+		}
3690
+		$this->_redirect_after_action(0, '', '', ['action' => 'settings'], true);
3691
+	}
3692
+
3693
+
3694
+	/**
3695
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3696
+	 *
3697
+	 * @param array $tab_array This is an array of message type tab details used to generate the tabs
3698
+	 * @return string html formatted tabs
3699
+	 * @throws DomainException
3700
+	 */
3701
+	protected function _get_mt_tabs($tab_array)
3702
+	{
3703
+		$tab_array = (array) $tab_array;
3704
+		$template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3705
+		$tabs      = '';
3706
+
3707
+		foreach ($tab_array as $tab) {
3708
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3709
+		}
3710
+
3711
+		return $tabs;
3712
+	}
3713
+
3714
+
3715
+	/**
3716
+	 * This prepares the content of the messenger meta box admin settings
3717
+	 *
3718
+	 * @param EE_messenger $messenger The messenger we're setting up content for
3719
+	 * @return string html formatted content
3720
+	 * @throws DomainException
3721
+	 */
3722
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3723
+	{
3724
+
3725
+		$fields                                         = $messenger->get_admin_settings_fields();
3726
+		$settings_template_args['template_form_fields'] = '';
3727
+
3728
+		// is $messenger active?
3729
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3730
+
3731
+
3732
+		if (! empty($fields)) {
3733
+			$existing_settings = $messenger->get_existing_admin_settings();
3734
+
3735
+			foreach ($fields as $fldname => $fldprops) {
3736
+				$field_id                         = $messenger->name . '-' . $fldname;
3737
+				$template_form_field[ $field_id ] = [
3738
+					'name'       => 'messenger_settings[' . $field_id . ']',
3739
+					'label'      => $fldprops['label'],
3740
+					'input'      => $fldprops['field_type'],
3741
+					'type'       => $fldprops['value_type'],
3742
+					'required'   => $fldprops['required'],
3743
+					'validation' => $fldprops['validation'],
3744
+					'value'      => isset($existing_settings[ $field_id ])
3745
+						? $existing_settings[ $field_id ]
3746
+						: $fldprops['default'],
3747
+					'css_class'  => '',
3748
+					'format'     => $fldprops['format'],
3749
+				];
3750
+			}
3751
+
3752
+
3753
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3754
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3755
+				: '';
3756
+		}
3757
+
3758
+		// we also need some hidden fields
3759
+		$settings_template_args['hidden_fields'] = [
3760
+			'messenger_settings[messenger]' . $messenger->name => [
3761
+				'type'  => 'hidden',
3762
+				'value' => $messenger->name,
3763
+			],
3764
+			'type' . $messenger->name                          => [
3765
+				'type'  => 'hidden',
3766
+				'value' => 'messenger',
3767
+			],
3768
+		];
3769
+
3770
+		// make sure any active message types that are existing are included in the hidden fields
3771
+		if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3772
+			foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3773
+				$settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = [
3774
+					'type'  => 'hidden',
3775
+					'value' => $mt,
3776
+				];
3777
+			}
3778
+		}
3779
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3780
+			$settings_template_args['hidden_fields'],
3781
+			'array'
3782
+		);
3783
+		$active                                  =
3784
+			$this->_message_resource_manager->is_messenger_active($messenger->name);
3785
+
3786
+		$settings_template_args['messenger']           = $messenger->name;
3787
+		$settings_template_args['description']         = $messenger->description;
3788
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3789
+
3790
+
3791
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3792
+			$messenger->name
3793
+		)
3794
+			? $settings_template_args['show_hide_edit_form']
3795
+			: ' hidden';
3796
+
3797
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3798
+			? ' hidden'
3799
+			: $settings_template_args['show_hide_edit_form'];
3800
+
3801
+
3802
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3803
+		$settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3804
+		$settings_template_args['on_off_status'] = $active;
3805
+		$template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3806
+		return EEH_Template::display_template(
3807
+			$template,
3808
+			$settings_template_args,
3809
+			true
3810
+		);
3811
+	}
3812
+
3813
+
3814
+	/**
3815
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3816
+	 *
3817
+	 * @throws DomainException
3818
+	 * @throws EE_Error
3819
+	 * @throws InvalidDataTypeException
3820
+	 * @throws InvalidInterfaceException
3821
+	 * @throws InvalidArgumentException
3822
+	 * @throws ReflectionException
3823
+	 */
3824
+	public function activate_messenger_toggle()
3825
+	{
3826
+		$success = true;
3827
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3828
+		// let's check that we have required data
3829
+
3830
+		if (! $this->_active_messenger_name) {
3831
+			EE_Error::add_error(
3832
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3833
+				__FILE__,
3834
+				__FUNCTION__,
3835
+				__LINE__
3836
+			);
3837
+			$success = false;
3838
+		}
3839
+
3840
+		// do a nonce check here since we're not arriving via a normal route
3841
+		$nonce     = $this->request->getRequestParam('activate_nonce', '');
3842
+		$nonce_ref = "activate_{$this->_active_messenger_name}_toggle_nonce";
3843
+
3844
+		$this->_verify_nonce($nonce, $nonce_ref);
3845
+
3846
+
3847
+		$status = $this->request->getRequestParam('status');
3848
+		if (! $status) {
3849
+			EE_Error::add_error(
3850
+				esc_html__(
3851
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3852
+					'event_espresso'
3853
+				),
3854
+				__FILE__,
3855
+				__FUNCTION__,
3856
+				__LINE__
3857
+			);
3858
+			$success = false;
3859
+		}
3860
+
3861
+		// do check to verify we have a valid status.
3862
+		if ($status !== 'off' && $status !== 'on') {
3863
+			EE_Error::add_error(
3864
+				sprintf(
3865
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3866
+					$status
3867
+				),
3868
+				__FILE__,
3869
+				__FUNCTION__,
3870
+				__LINE__
3871
+			);
3872
+			$success = false;
3873
+		}
3874
+
3875
+		if ($success) {
3876
+			// made it here?  Stop dawdling then!!
3877
+			$success = $status === 'off'
3878
+				? $this->_deactivate_messenger($this->_active_messenger_name)
3879
+				: $this->_activate_messenger($this->_active_messenger_name);
3880
+		}
3881
+
3882
+		$this->_template_args['success'] = $success;
3883
+
3884
+		// no special instructions so let's just do the json return (which should automatically do all the special stuff).
3885
+		$this->_return_json();
3886
+	}
3887
+
3888
+
3889
+	/**
3890
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3891
+	 *
3892
+	 * @throws DomainException
3893
+	 * @throws EE_Error
3894
+	 * @throws ReflectionException
3895
+	 * @throws InvalidDataTypeException
3896
+	 * @throws InvalidInterfaceException
3897
+	 * @throws InvalidArgumentException
3898
+	 */
3899
+	public function activate_mt_toggle()
3900
+	{
3901
+		$success = true;
3902
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3903
+
3904
+		// let's make sure we have the necessary data
3905
+		if (! $this->_active_message_type_name) {
3906
+			EE_Error::add_error(
3907
+				esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3908
+				__FILE__,
3909
+				__FUNCTION__,
3910
+				__LINE__
3911
+			);
3912
+			$success = false;
3913
+		}
3914
+
3915
+		if (! $this->_active_messenger_name) {
3916
+			EE_Error::add_error(
3917
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3918
+				__FILE__,
3919
+				__FUNCTION__,
3920
+				__LINE__
3921
+			);
3922
+			$success = false;
3923
+		}
3924
+
3925
+		$status = $this->request->getRequestParam('status');
3926
+		if (! $status) {
3927
+			EE_Error::add_error(
3928
+				esc_html__(
3929
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3930
+					'event_espresso'
3931
+				),
3932
+				__FILE__,
3933
+				__FUNCTION__,
3934
+				__LINE__
3935
+			);
3936
+			$success = false;
3937
+		}
3938
+
3939
+
3940
+		// do check to verify we have a valid status.
3941
+		if ($status !== 'activate' && $status !== 'deactivate') {
3942
+			EE_Error::add_error(
3943
+				sprintf(
3944
+					esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3945
+					$status
3946
+				),
3947
+				__FILE__,
3948
+				__FUNCTION__,
3949
+				__LINE__
3950
+			);
3951
+			$success = false;
3952
+		}
3953
+
3954
+
3955
+		// do a nonce check here since we're not arriving via a normal route
3956
+		$nonce = $this->request->getRequestParam('mt_nonce', '');
3957
+		$this->_verify_nonce($nonce, "{$this->_active_message_type_name}_nonce");
3958
+
3959
+		if ($success) {
3960
+			// made it here? um, what are you waiting for then?
3961
+			$success = $status === 'deactivate'
3962
+				? $this->_deactivate_message_type_for_messenger(
3963
+					$this->_active_messenger_name,
3964
+					$this->_active_message_type_name
3965
+				)
3966
+				: $this->_activate_message_type_for_messenger(
3967
+					$this->_active_messenger_name,
3968
+					$this->_active_message_type_name
3969
+				);
3970
+		}
3971
+
3972
+		$this->_template_args['success'] = $success;
3973
+		$this->_return_json();
3974
+	}
3975
+
3976
+
3977
+	/**
3978
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
3979
+	 *
3980
+	 * @param string $messenger_name The name of the messenger being activated
3981
+	 * @return bool
3982
+	 * @throws DomainException
3983
+	 * @throws EE_Error
3984
+	 * @throws InvalidArgumentException
3985
+	 * @throws ReflectionException
3986
+	 * @throws InvalidDataTypeException
3987
+	 * @throws InvalidInterfaceException
3988
+	 */
3989
+	protected function _activate_messenger($messenger_name)
3990
+	{
3991
+		$active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3992
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger
3993
+			? $active_messenger->get_default_message_types()
3994
+			: [];
3995
+
3996
+		// ensure is active
3997
+		$this->_message_resource_manager->activate_messenger($active_messenger, $message_types_to_activate);
3998
+
3999
+		// set response_data for reload
4000
+		foreach ($message_types_to_activate as $message_type_name) {
4001
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4002
+			if (
4003
+				$this->_message_resource_manager->is_message_type_active_for_messenger(
4004
+					$messenger_name,
4005
+					$message_type_name
4006
+				)
4007
+				&& $message_type instanceof EE_message_type
4008
+			) {
4009
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
4010
+				if ($message_type->get_admin_settings_fields()) {
4011
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
4012
+				}
4013
+			}
4014
+		}
4015
+
4016
+		// add success message for activating messenger
4017
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4018
+	}
4019
+
4020
+
4021
+	/**
4022
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
4023
+	 *
4024
+	 * @param string $messenger_name The name of the messenger being activated
4025
+	 * @return bool
4026
+	 * @throws DomainException
4027
+	 * @throws EE_Error
4028
+	 * @throws InvalidArgumentException
4029
+	 * @throws ReflectionException
4030
+	 * @throws InvalidDataTypeException
4031
+	 * @throws InvalidInterfaceException
4032
+	 */
4033
+	protected function _deactivate_messenger($messenger_name)
4034
+	{
4035
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4036
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
4037
+
4038
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4039
+	}
4040
+
4041
+
4042
+	/**
4043
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4044
+	 *
4045
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
4046
+	 * @param string $message_type_name The name of the message type being activated for the messenger
4047
+	 * @return bool
4048
+	 * @throws DomainException
4049
+	 * @throws EE_Error
4050
+	 * @throws InvalidArgumentException
4051
+	 * @throws ReflectionException
4052
+	 * @throws InvalidDataTypeException
4053
+	 * @throws InvalidInterfaceException
4054
+	 */
4055
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4056
+	{
4057
+		$active_messenger         = $this->_message_resource_manager->get_messenger($messenger_name);
4058
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4059
+
4060
+		// ensure is active
4061
+		$this->_message_resource_manager->activate_messenger($active_messenger, $message_type_name);
4062
+
4063
+		// set response for load
4064
+		if (
4065
+			$this->_message_resource_manager->is_message_type_active_for_messenger(
4066
+				$messenger_name,
4067
+				$message_type_name
4068
+			)
4069
+		) {
4070
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
4071
+			if ($message_type_to_activate->get_admin_settings_fields()) {
4072
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
4073
+			}
4074
+		}
4075
+
4076
+		return $this->_setup_response_message_for_activating_messenger_with_message_types(
4077
+			$active_messenger,
4078
+			$message_type_to_activate
4079
+		);
4080
+	}
4081
+
4082
+
4083
+	/**
4084
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4085
+	 *
4086
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4087
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
4088
+	 * @return bool
4089
+	 * @throws DomainException
4090
+	 * @throws EE_Error
4091
+	 * @throws InvalidArgumentException
4092
+	 * @throws ReflectionException
4093
+	 * @throws InvalidDataTypeException
4094
+	 * @throws InvalidInterfaceException
4095
+	 */
4096
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4097
+	{
4098
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4099
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4100
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4101
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4102
+
4103
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4104
+			$active_messenger,
4105
+			$message_type_to_deactivate
4106
+		);
4107
+	}
4108
+
4109
+
4110
+	/**
4111
+	 * This just initializes the defaults for activating messenger and message type responses.
4112
+	 */
4113
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
4114
+	{
4115
+		$this->_template_args['data']['active_mts'] = [];
4116
+		$this->_template_args['data']['mt_reload']  = [];
4117
+	}
4118
+
4119
+
4120
+	/**
4121
+	 * Setup appropriate response for activating a messenger and/or message types
4122
+	 *
4123
+	 * @param EE_messenger         $messenger
4124
+	 * @param EE_message_type|null $message_type
4125
+	 * @return bool
4126
+	 * @throws DomainException
4127
+	 * @throws EE_Error
4128
+	 * @throws InvalidArgumentException
4129
+	 * @throws ReflectionException
4130
+	 * @throws InvalidDataTypeException
4131
+	 * @throws InvalidInterfaceException
4132
+	 */
4133
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
4134
+		$messenger,
4135
+		EE_Message_Type $message_type = null
4136
+	) {
4137
+		// if $messenger isn't a valid messenger object then get out.
4138
+		if (! $messenger instanceof EE_Messenger) {
4139
+			EE_Error::add_error(
4140
+				esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4141
+				__FILE__,
4142
+				__FUNCTION__,
4143
+				__LINE__
4144
+			);
4145
+			return false;
4146
+		}
4147
+		// activated
4148
+		if ($this->_template_args['data']['active_mts']) {
4149
+			EE_Error::overwrite_success();
4150
+			// activated a message type with the messenger
4151
+			if ($message_type instanceof EE_message_type) {
4152
+				EE_Error::add_success(
4153
+					sprintf(
4154
+						esc_html__(
4155
+							'%s message type has been successfully activated with the %s messenger',
4156
+							'event_espresso'
4157
+						),
4158
+						ucwords($message_type->label['singular']),
4159
+						ucwords($messenger->label['singular'])
4160
+					)
4161
+				);
4162
+
4163
+				// if message type was invoice then let's make sure we activate the invoice payment method.
4164
+				if ($message_type->name === 'invoice') {
4165
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
4166
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4167
+					if ($pm instanceof EE_Payment_Method) {
4168
+						EE_Error::add_attention(
4169
+							esc_html__(
4170
+								'Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
4171
+								'event_espresso'
4172
+							)
4173
+						);
4174
+					}
4175
+				}
4176
+				// just toggles the entire messenger
4177
+			} else {
4178
+				EE_Error::add_success(
4179
+					sprintf(
4180
+						esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4181
+						ucwords($messenger->label['singular'])
4182
+					)
4183
+				);
4184
+			}
4185
+
4186
+			return true;
4187
+
4188
+			// possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4189
+			// message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4190
+			// in which case we just give a success message for the messenger being successfully activated.
4191
+		} else {
4192
+			if (! $messenger->get_default_message_types()) {
4193
+				// messenger doesn't have any default message types so still a success.
4194
+				EE_Error::add_success(
4195
+					sprintf(
4196
+						esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4197
+						ucwords($messenger->label['singular'])
4198
+					)
4199
+				);
4200
+
4201
+				return true;
4202
+			} else {
4203
+				EE_Error::add_error(
4204
+					$message_type instanceof EE_message_type
4205
+						? sprintf(
4206
+							esc_html__(
4207
+								'%s message type was not successfully activated with the %s messenger',
4208
+								'event_espresso'
4209
+							),
4210
+							ucwords($message_type->label['singular']),
4211
+							ucwords($messenger->label['singular'])
4212
+						)
4213
+						: sprintf(
4214
+							esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4215
+							ucwords($messenger->label['singular'])
4216
+						),
4217
+					__FILE__,
4218
+					__FUNCTION__,
4219
+					__LINE__
4220
+				);
4221
+
4222
+				return false;
4223
+			}
4224
+		}
4225
+	}
4226
+
4227
+
4228
+	/**
4229
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
4230
+	 *
4231
+	 * @param EE_messenger         $messenger
4232
+	 * @param EE_message_type|null $message_type
4233
+	 * @return bool
4234
+	 * @throws DomainException
4235
+	 * @throws EE_Error
4236
+	 * @throws InvalidArgumentException
4237
+	 * @throws ReflectionException
4238
+	 * @throws InvalidDataTypeException
4239
+	 * @throws InvalidInterfaceException
4240
+	 */
4241
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4242
+		$messenger,
4243
+		EE_message_type $message_type = null
4244
+	) {
4245
+		EE_Error::overwrite_success();
4246
+
4247
+		// if $messenger isn't a valid messenger object then get out.
4248
+		if (! $messenger instanceof EE_Messenger) {
4249
+			EE_Error::add_error(
4250
+				esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4251
+				__FILE__,
4252
+				__FUNCTION__,
4253
+				__LINE__
4254
+			);
4255
+
4256
+			return false;
4257
+		}
4258
+
4259
+		if ($message_type instanceof EE_message_type) {
4260
+			$message_type_name = $message_type->name;
4261
+			EE_Error::add_success(
4262
+				sprintf(
4263
+					esc_html__(
4264
+						'%s message type has been successfully deactivated for the %s messenger.',
4265
+						'event_espresso'
4266
+					),
4267
+					ucwords($message_type->label['singular']),
4268
+					ucwords($messenger->label['singular'])
4269
+				)
4270
+			);
4271
+		} else {
4272
+			$message_type_name = '';
4273
+			EE_Error::add_success(
4274
+				sprintf(
4275
+					esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4276
+					ucwords($messenger->label['singular'])
4277
+				)
4278
+			);
4279
+		}
4280
+
4281
+		// if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4282
+		if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4283
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
4284
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4285
+			if ($count_updated > 0) {
4286
+				$msg = $message_type_name === 'invoice'
4287
+					? esc_html__(
4288
+						'Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
4289
+						'event_espresso'
4290
+					)
4291
+					: esc_html__(
4292
+						'Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
4293
+						'event_espresso'
4294
+					);
4295
+				EE_Error::add_attention($msg);
4296
+			}
4297
+		}
4298
+
4299
+		return true;
4300
+	}
4301
+
4302
+
4303
+	/**
4304
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4305
+	 *
4306
+	 * @throws DomainException
4307
+	 * @throws EE_Error
4308
+	 * @throws EE_Error
4309
+	 */
4310
+	public function update_mt_form()
4311
+	{
4312
+		if (! $this->_active_messenger_name || ! $this->_active_message_type_name) {
4313
+			EE_Error::add_error(
4314
+				esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4315
+				__FILE__,
4316
+				__FUNCTION__,
4317
+				__LINE__
4318
+			);
4319
+			$this->_return_json();
4320
+		}
4321
+
4322
+		$message_types = $this->get_installed_message_types();
4323
+		$message_type  = $message_types[ $this->_active_message_type_name ];
4324
+		$messenger     = $this->_message_resource_manager->get_active_messenger($this->_active_messenger_name);
4325
+		$content       = $this->_message_type_settings_content($message_type, $messenger, true);
4326
+
4327
+		$this->_template_args['success'] = true;
4328
+		$this->_template_args['content'] = $content;
4329
+		$this->_return_json();
4330
+	}
4331
+
4332
+
4333
+	/**
4334
+	 * this handles saving the settings for a messenger or message type
4335
+	 *
4336
+	 * @throws EE_Error
4337
+	 * @throws EE_Error
4338
+	 */
4339
+	public function save_settings()
4340
+	{
4341
+		$type = $this->request->getRequestParam('type');
4342
+		if (! $type) {
4343
+			EE_Error::add_error(
4344
+				esc_html__(
4345
+					'Cannot save settings because type is unknown (messenger settings or message type settings?)',
4346
+					'event_espresso'
4347
+				),
4348
+				__FILE__,
4349
+				__FUNCTION__,
4350
+				__LINE__
4351
+			);
4352
+			$this->_template_args['error'] = true;
4353
+			$this->_return_json();
4354
+		}
4355
+
4356
+
4357
+		if ($type === 'messenger') {
4358
+			// this should be an array.
4359
+			$settings  = $this->request->getRequestParam('messenger_settings', [], 'string', true);
4360
+			$messenger = $settings['messenger'];
4361
+			// remove messenger and message_types from settings array
4362
+			unset($settings['messenger'], $settings['message_types']);
4363
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4364
+		} elseif ($type === 'message_type') {
4365
+			$settings     = $this->request->getRequestParam('message_type_settings', [], 'string', true);
4366
+			$messenger    = $settings['messenger'];
4367
+			$message_type = $settings['message_type'];
4368
+			// remove messenger and message_types from settings array
4369
+			unset($settings['messenger'], $settings['message_types']);
4370
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4371
+		}
4372
+
4373
+		// okay we should have the data all setup.  Now we just update!
4374
+		$success = $this->_message_resource_manager->update_active_messengers_option();
4375
+
4376
+		if ($success) {
4377
+			EE_Error::add_success(esc_html__('Settings updated', 'event_espresso'));
4378
+		} else {
4379
+			EE_Error::add_error(
4380
+				esc_html__('Settings did not get updated', 'event_espresso'),
4381
+				__FILE__,
4382
+				__FUNCTION__,
4383
+				__LINE__
4384
+			);
4385
+		}
4386
+
4387
+		$this->_template_args['success'] = $success;
4388
+		$this->_return_json();
4389
+	}
4390
+
4391
+
4392
+
4393
+
4394
+	/**  EE MESSAGE PROCESSING ACTIONS **/
4395
+
4396
+
4397
+	/**
4398
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4399
+	 * However, this does not send immediately, it just queues for sending.
4400
+	 *
4401
+	 * @throws EE_Error
4402
+	 * @throws InvalidDataTypeException
4403
+	 * @throws InvalidInterfaceException
4404
+	 * @throws InvalidArgumentException
4405
+	 * @throws ReflectionException
4406
+	 * @since 4.9.0
4407
+	 */
4408
+	protected function _generate_now()
4409
+	{
4410
+		EED_Messages::generate_now($this->_get_msg_ids_from_request());
4411
+		$this->_redirect_after_action(false, '', '', [], true);
4412
+	}
4413
+
4414
+
4415
+	/**
4416
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4417
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
4418
+	 *
4419
+	 * @throws EE_Error
4420
+	 * @throws InvalidDataTypeException
4421
+	 * @throws InvalidInterfaceException
4422
+	 * @throws InvalidArgumentException
4423
+	 * @throws ReflectionException
4424
+	 * @since 4.9.0
4425
+	 */
4426
+	protected function _generate_and_send_now()
4427
+	{
4428
+		EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4429
+		$this->_redirect_after_action(false, '', '', [], true);
4430
+	}
4431
+
4432
+
4433
+	/**
4434
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4435
+	 *
4436
+	 * @throws EE_Error
4437
+	 * @throws InvalidDataTypeException
4438
+	 * @throws InvalidInterfaceException
4439
+	 * @throws InvalidArgumentException
4440
+	 * @throws ReflectionException
4441
+	 * @since 4.9.0
4442
+	 */
4443
+	protected function _queue_for_resending()
4444
+	{
4445
+		EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4446
+		$this->_redirect_after_action(false, '', '', [], true);
4447
+	}
4448
+
4449
+
4450
+	/**
4451
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4452
+	 *
4453
+	 * @throws EE_Error
4454
+	 * @throws InvalidDataTypeException
4455
+	 * @throws InvalidInterfaceException
4456
+	 * @throws InvalidArgumentException
4457
+	 * @throws ReflectionException
4458
+	 * @since 4.9.0
4459
+	 */
4460
+	protected function _send_now()
4461
+	{
4462
+		EED_Messages::send_now($this->_get_msg_ids_from_request());
4463
+		$this->_redirect_after_action(false, '', '', [], true);
4464
+	}
4465
+
4466
+
4467
+	/**
4468
+	 * Deletes EE_messages for IDs in the request.
4469
+	 *
4470
+	 * @throws EE_Error
4471
+	 * @throws InvalidDataTypeException
4472
+	 * @throws InvalidInterfaceException
4473
+	 * @throws InvalidArgumentException
4474
+	 * @since 4.9.0
4475
+	 */
4476
+	protected function _delete_ee_messages()
4477
+	{
4478
+		$MSG_IDs       = $this->_get_msg_ids_from_request();
4479
+		$deleted_count = 0;
4480
+		foreach ($MSG_IDs as $MSG_ID) {
4481
+			if (EEM_Message::instance()->delete_by_ID($MSG_ID)) {
4482
+				$deleted_count++;
4483
+			}
4484
+		}
4485
+		if ($deleted_count) {
4486
+			EE_Error::add_success(
4487
+				esc_html(
4488
+					_n(
4489
+						'Message successfully deleted',
4490
+						'Messages successfully deleted',
4491
+						$deleted_count,
4492
+						'event_espresso'
4493
+					)
4494
+				)
4495
+			);
4496
+		} else {
4497
+			EE_Error::add_error(
4498
+				_n('The message was not deleted.', 'The messages were not deleted', count($MSG_IDs), 'event_espresso'),
4499
+				__FILE__,
4500
+				__FUNCTION__,
4501
+				__LINE__
4502
+			);
4503
+		}
4504
+		$this->_redirect_after_action(false, '', '', [], true);
4505
+	}
4506
+
4507
+
4508
+	/**
4509
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4510
+	 *
4511
+	 * @return array
4512
+	 * @since 4.9.0
4513
+	 */
4514
+	protected function _get_msg_ids_from_request()
4515
+	{
4516
+		$MSG_IDs = $this->request->getRequestParam('MSG_ID', [], 'string', true);
4517
+		if (empty($MSG_IDs)) {
4518
+			return [];
4519
+		}
4520
+		// if 'MSG_ID' was just a single ID (not an array)
4521
+		// then $MSG_IDs will be something like [123] so $MSG_IDs[0] should be 123
4522
+		// otherwise, $MSG_IDs was already an array where message IDs were used as the keys
4523
+		return count($MSG_IDs) === 1 && isset($MSG_IDs[0])
4524
+			? $MSG_IDs
4525
+			: array_keys($MSG_IDs);
4526
+	}
4527 4527
 }
Please login to merge, or discard this patch.
Spacing   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -155,8 +155,8 @@  discard block
 block discarded – undo
155 155
         $i = 1;
156 156
         foreach ($active_messengers as $active_messenger) {
157 157
             if ($active_messenger instanceof EE_Message) {
158
-                $m_values[ $i ]['id']   = $active_messenger->messenger();
159
-                $m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
158
+                $m_values[$i]['id']   = $active_messenger->messenger();
159
+                $m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
160 160
                 $i++;
161 161
             }
162 162
         }
@@ -192,8 +192,8 @@  discard block
 block discarded – undo
192 192
         $i               = 1;
193 193
         foreach ($active_messages as $active_message) {
194 194
             if ($active_message instanceof EE_Message) {
195
-                $mt_values[ $i ]['id']   = $active_message->message_type();
196
-                $mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
195
+                $mt_values[$i]['id']   = $active_message->message_type();
196
+                $mt_values[$i]['text'] = ucwords($active_message->message_type_label());
197 197
                 $i++;
198 198
             }
199 199
         }
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
                 if ($message_type instanceof EE_message_type) {
233 233
                     $message_type_contexts = $message_type->get_contexts();
234 234
                     foreach ($message_type_contexts as $context => $context_details) {
235
-                        $contexts[ $context ] = $context_details['label'];
235
+                        $contexts[$context] = $context_details['label'];
236 236
                     }
237 237
                 }
238 238
             }
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
             ['none_selected' => esc_html__('Show All Messengers', 'event_espresso')],
266 266
             $messenger_options
267 267
         );
268
-        $input             = new EE_Select_Input(
268
+        $input = new EE_Select_Input(
269 269
             $messenger_options,
270 270
             [
271 271
                 'html_name'  => 'ee_messenger_filter_by',
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
             ['none_selected' => esc_html__('Show All Message Types', 'event_espresso')],
303 303
             $message_type_options
304 304
         );
305
-        $input                = new EE_Select_Input(
305
+        $input = new EE_Select_Input(
306 306
             $message_type_options,
307 307
             [
308 308
                 'html_name'  => 'ee_message_type_filter_by',
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
             ['none_selected' => esc_html__('Show all Contexts', 'event_espresso')],
340 340
             $context_options
341 341
         );
342
-        $input           = new EE_Select_Input(
342
+        $input = new EE_Select_Input(
343 343
             $context_options,
344 344
             [
345 345
                 'html_name'  => 'ee_context_filter_by',
@@ -721,53 +721,53 @@  discard block
 block discarded – undo
721 721
 
722 722
     public function messages_help_tab()
723 723
     {
724
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
724
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_help_tab.template.php');
725 725
     }
726 726
 
727 727
 
728 728
     public function messengers_help_tab()
729 729
     {
730
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
730
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messenger_help_tab.template.php');
731 731
     }
732 732
 
733 733
 
734 734
     public function message_types_help_tab()
735 735
     {
736
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
736
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_type_help_tab.template.php');
737 737
     }
738 738
 
739 739
 
740 740
     public function messages_overview_help_tab()
741 741
     {
742
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
742
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_overview_help_tab.template.php');
743 743
     }
744 744
 
745 745
 
746 746
     public function message_templates_help_tab()
747 747
     {
748
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
748
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_templates_help_tab.template.php');
749 749
     }
750 750
 
751 751
 
752 752
     public function edit_message_template_help_tab()
753 753
     {
754
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
754
+        $args['img1'] = '<img src="'.EE_MSG_ASSETS_URL.'images/editor.png'.'" alt="'
755 755
                         . esc_attr__('Editor Title', 'event_espresso')
756 756
                         . '" />';
757
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
757
+        $args['img2'] = '<img src="'.EE_MSG_ASSETS_URL.'images/switch-context.png'.'" alt="'
758 758
                         . esc_attr__('Context Switcher and Preview', 'event_espresso')
759 759
                         . '" />';
760
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
760
+        $args['img3'] = '<img class="left" src="'.EE_MSG_ASSETS_URL.'images/form-fields.png'.'" alt="'
761 761
                         . esc_attr__('Message Template Form Fields', 'event_espresso')
762 762
                         . '" />';
763
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
763
+        $args['img4'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/shortcodes-metabox.png'.'" alt="'
764 764
                         . esc_attr__('Shortcodes Metabox', 'event_espresso')
765 765
                         . '" />';
766
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
766
+        $args['img5'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/publish-meta-box.png'.'" alt="'
767 767
                         . esc_attr__('Publish Metabox', 'event_espresso')
768 768
                         . '" />';
769 769
         EEH_Template::display_template(
770
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
770
+            EE_MSG_TEMPLATE_PATH.'ee_msg_messages_templates_editor_help_tab.template.php',
771 771
             $args
772 772
         );
773 773
     }
@@ -782,7 +782,7 @@  discard block
 block discarded – undo
782 782
         $this->_set_shortcodes();
783 783
         $args['shortcodes'] = $this->_shortcodes;
784 784
         EEH_Template::display_template(
785
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
785
+            EE_MSG_TEMPLATE_PATH.'ee_msg_messages_shortcodes_help_tab.template.php',
786 786
             $args
787 787
         );
788 788
     }
@@ -790,16 +790,16 @@  discard block
 block discarded – undo
790 790
 
791 791
     public function preview_message_help_tab()
792 792
     {
793
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
793
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_preview_help_tab.template.php');
794 794
     }
795 795
 
796 796
 
797 797
     public function settings_help_tab()
798 798
     {
799
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
800
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
801
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
802
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
799
+        $args['img1'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-active.png'
800
+                        . '" alt="'.esc_attr__('Active Email Tab', 'event_espresso').'" />';
801
+        $args['img2'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-inactive.png'
802
+                        . '" alt="'.esc_attr__('Inactive Email Tab', 'event_espresso').'" />';
803 803
         $args['img3'] = '<div class="switch">'
804 804
                         . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
805 805
                         . ' type="checkbox" checked="checked">'
@@ -810,25 +810,25 @@  discard block
 block discarded – undo
810 810
                         . ' type="checkbox">'
811 811
                         . '<label for="ee-on-off-toggle-on"></label>'
812 812
                         . '</div>';
813
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
813
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_settings_help_tab.template.php', $args);
814 814
     }
815 815
 
816 816
 
817 817
     public function load_scripts_styles()
818 818
     {
819
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
819
+        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL.'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
820 820
         wp_enqueue_style('espresso_ee_msg');
821 821
 
822 822
         wp_register_script(
823 823
             'ee-messages-settings',
824
-            EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
824
+            EE_MSG_ASSETS_URL.'ee-messages-settings.js',
825 825
             ['jquery-ui-droppable', 'ee-serialize-full-array'],
826 826
             EVENT_ESPRESSO_VERSION,
827 827
             true
828 828
         );
829 829
         wp_register_script(
830 830
             'ee-msg-list-table-js',
831
-            EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
831
+            EE_MSG_ASSETS_URL.'ee_message_admin_list_table.js',
832 832
             ['ee-dialog'],
833 833
             EVENT_ESPRESSO_VERSION
834 834
         );
@@ -871,7 +871,7 @@  discard block
 block discarded – undo
871 871
 
872 872
         $this->_set_shortcodes();
873 873
 
874
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
874
+        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
875 875
             esc_html__(
876 876
                 'Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
877 877
                 'event_espresso'
@@ -883,14 +883,14 @@  discard block
 block discarded – undo
883 883
             'Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
884 884
             'event_espresso'
885 885
         );
886
-        EE_Registry::$i18n_js_strings['server_error']                 = esc_html__(
886
+        EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
887 887
             'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
888 888
             'event_espresso'
889 889
         );
890 890
 
891 891
         wp_register_script(
892 892
             'ee_msgs_edit_js',
893
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
893
+            EE_MSG_ASSETS_URL.'ee_message_editor.js',
894 894
             ['jquery'],
895 895
             EVENT_ESPRESSO_VERSION
896 896
         );
@@ -933,7 +933,7 @@  discard block
 block discarded – undo
933 933
     {
934 934
         wp_register_style(
935 935
             'ee-message-settings',
936
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
936
+            EE_MSG_ASSETS_URL.'ee_message_settings.css',
937 937
             [],
938 938
             EVENT_ESPRESSO_VERSION
939 939
         );
@@ -1019,7 +1019,7 @@  discard block
 block discarded – undo
1019 1019
             }
1020 1020
             $status_bulk_actions = $common_bulk_actions;
1021 1021
             // unset bulk actions not applying to status
1022
-            if (! empty($status_bulk_actions)) {
1022
+            if ( ! empty($status_bulk_actions)) {
1023 1023
                 switch ($status) {
1024 1024
                     case EEM_Message::status_idle:
1025 1025
                     case EEM_Message::status_resend:
@@ -1048,7 +1048,7 @@  discard block
 block discarded – undo
1048 1048
                 continue;
1049 1049
             }
1050 1050
 
1051
-            $this->_views[ strtolower($status) ] = [
1051
+            $this->_views[strtolower($status)] = [
1052 1052
                 'slug'        => strtolower($status),
1053 1053
                 'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1054 1054
                 'count'       => 0,
@@ -1097,7 +1097,7 @@  discard block
 block discarded – undo
1097 1097
             if ($action_item === 'see_notifications_for') {
1098 1098
                 continue;
1099 1099
             }
1100
-            $action_items[ $action_item ] = [
1100
+            $action_items[$action_item] = [
1101 1101
                 'class' => $action_details['css_class'],
1102 1102
                 'desc'  => $action_details['label'],
1103 1103
             ];
@@ -1106,37 +1106,37 @@  discard block
 block discarded – undo
1106 1106
         /** @var array $status_items status legend setup */
1107 1107
         $status_items = [
1108 1108
             'sent_status'                => [
1109
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1109
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_sent,
1110 1110
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1111 1111
             ],
1112 1112
             'idle_status'                => [
1113
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1113
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_idle,
1114 1114
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1115 1115
             ],
1116 1116
             'failed_status'              => [
1117
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1117
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_failed,
1118 1118
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1119 1119
             ],
1120 1120
             'messenger_executing_status' => [
1121
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1121
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_messenger_executing,
1122 1122
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1123 1123
             ],
1124 1124
             'resend_status'              => [
1125
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1125
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_resend,
1126 1126
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1127 1127
             ],
1128 1128
             'incomplete_status'          => [
1129
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1129
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_incomplete,
1130 1130
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1131 1131
             ],
1132 1132
             'retry_status'               => [
1133
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1133
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_retry,
1134 1134
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1135 1135
             ],
1136 1136
         ];
1137 1137
         if (EEM_Message::debug()) {
1138 1138
             $status_items['debug_only_status'] = [
1139
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1139
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_debug_only,
1140 1140
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1141 1141
             ];
1142 1142
         }
@@ -1151,11 +1151,11 @@  discard block
 block discarded – undo
1151 1151
     protected function _custom_mtps_preview()
1152 1152
     {
1153 1153
         $this->_admin_page_title              = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1154
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1155
-                                                . ' alt="' . esc_attr__(
1154
+        $this->_template_args['preview_img']  = '<img src="'.EE_MSG_ASSETS_URL.'images/custom_mtps_preview.png"'
1155
+                                                . ' alt="'.esc_attr__(
1156 1156
                                                     'Preview Custom Message Templates screenshot',
1157 1157
                                                     'event_espresso'
1158
-                                                ) . '" />';
1158
+                                                ).'" />';
1159 1159
         $this->_template_args['preview_text'] = '<strong>'
1160 1160
                                                 . esc_html__(
1161 1161
                                                     'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
@@ -1227,7 +1227,7 @@  discard block
 block discarded – undo
1227 1227
         $installed               = [];
1228 1228
 
1229 1229
         foreach ($installed_message_types as $message_type) {
1230
-            $installed[ $message_type->name ] = $message_type;
1230
+            $installed[$message_type->name] = $message_type;
1231 1231
         }
1232 1232
 
1233 1233
         return $installed;
@@ -1356,7 +1356,7 @@  discard block
 block discarded – undo
1356 1356
         // we need to assemble the title from Various details
1357 1357
         $context_label = sprintf(
1358 1358
             esc_html__('(%s %s)', 'event_espresso'),
1359
-            $c_config[ $context ]['label'],
1359
+            $c_config[$context]['label'],
1360 1360
             ucwords($c_label['label'])
1361 1361
         );
1362 1362
 
@@ -1378,7 +1378,7 @@  discard block
 block discarded – undo
1378 1378
             $message_template_group->message_type()
1379 1379
         );
1380 1380
 
1381
-        if (! $template_field_structure) {
1381
+        if ( ! $template_field_structure) {
1382 1382
             $template_field_structure = false;
1383 1383
             $template_fields          = esc_html__(
1384 1384
                 'There was an error in assembling the fields for this display (you should see an error message)',
@@ -1392,21 +1392,21 @@  discard block
 block discarded – undo
1392 1392
 
1393 1393
         // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1394 1394
         // will get handled in the "extra" array.
1395
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1396
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1397
-                unset($template_field_structure[ $context ][ $reference_field ]);
1395
+        if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1396
+            foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1397
+                unset($template_field_structure[$context][$reference_field]);
1398 1398
             }
1399 1399
         }
1400 1400
 
1401 1401
         // let's loop through the template_field_structure and actually assemble the input fields!
1402
-        if (! empty($template_field_structure)) {
1403
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1402
+        if ( ! empty($template_field_structure)) {
1403
+            foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1404 1404
                 // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1405 1405
                 // the extra array and reset them.
1406 1406
                 if ($template_field === 'extra') {
1407 1407
                     $this->_template_args['is_extra_fields'] = true;
1408 1408
                     foreach ($field_setup_array as $reference_field => $new_fields_array) {
1409
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1409
+                        $message_template = $message_templates[$context][$reference_field];
1410 1410
                         $content          = $message_template instanceof EE_Message_Template
1411 1411
                             ? $message_template->get('MTP_content')
1412 1412
                             : '';
@@ -1415,7 +1415,7 @@  discard block
 block discarded – undo
1415 1415
                             $continue = false;
1416 1416
                             if (isset($extra_array['shortcodes_required'])) {
1417 1417
                                 foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1418
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1418
+                                    if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1419 1419
                                         $continue = true;
1420 1420
                                     }
1421 1421
                                 }
@@ -1424,55 +1424,55 @@  discard block
 block discarded – undo
1424 1424
                                 }
1425 1425
                             }
1426 1426
 
1427
-                            $field_id                                  = $reference_field
1427
+                            $field_id = $reference_field
1428 1428
                                                                          . '-'
1429 1429
                                                                          . $extra_field
1430 1430
                                                                          . '-content';
1431
-                            $template_form_fields[ $field_id ]         = $extra_array;
1432
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1431
+                            $template_form_fields[$field_id]         = $extra_array;
1432
+                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields['
1433 1433
                                                                          . $reference_field
1434 1434
                                                                          . '][content]['
1435
-                                                                         . $extra_field . ']';
1436
-                            $css_class                                 = isset($extra_array['css_class'])
1435
+                                                                         . $extra_field.']';
1436
+                            $css_class = isset($extra_array['css_class'])
1437 1437
                                 ? $extra_array['css_class']
1438 1438
                                 : '';
1439 1439
 
1440
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1440
+                            $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1441 1441
                                                                               && in_array($extra_field, $v_fields, true)
1442 1442
                                                                               && (
1443
-                                                                                  is_array($validators[ $extra_field ])
1444
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1443
+                                                                                  is_array($validators[$extra_field])
1444
+                                                                                  && isset($validators[$extra_field]['msg'])
1445 1445
                                                                               )
1446
-                                ? 'validate-error ' . $css_class
1446
+                                ? 'validate-error '.$css_class
1447 1447
                                 : $css_class;
1448 1448
 
1449
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1450
-                                                                          && isset($content[ $extra_field ])
1451
-                                ? $content[ $extra_field ]
1449
+                            $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1450
+                                                                          && isset($content[$extra_field])
1451
+                                ? $content[$extra_field]
1452 1452
                                 : '';
1453 1453
 
1454 1454
                             // do we have a validation error?  if we do then let's use that value instead
1455
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1456
-                                ? $validators[ $extra_field ]['value']
1457
-                                : $template_form_fields[ $field_id ]['value'];
1455
+                            $template_form_fields[$field_id]['value'] = isset($validators[$extra_field])
1456
+                                ? $validators[$extra_field]['value']
1457
+                                : $template_form_fields[$field_id]['value'];
1458 1458
 
1459 1459
 
1460
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1460
+                            $template_form_fields[$field_id]['db-col'] = 'MTP_content';
1461 1461
 
1462 1462
                             // shortcode selector
1463 1463
                             $field_name_to_use                                   = $extra_field === 'main'
1464 1464
                                 ? 'content'
1465 1465
                                 : $extra_field;
1466
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1466
+                            $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1467 1467
                                 $field_name_to_use,
1468 1468
                                 $field_id
1469 1469
                             );
1470 1470
                         }
1471
-                        $template_field_MTP_id           = $reference_field . '-MTP_ID';
1472
-                        $template_field_template_name_id = $reference_field . '-name';
1471
+                        $template_field_MTP_id           = $reference_field.'-MTP_ID';
1472
+                        $template_field_template_name_id = $reference_field.'-name';
1473 1473
 
1474
-                        $template_form_fields[ $template_field_MTP_id ] = [
1475
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1474
+                        $template_form_fields[$template_field_MTP_id] = [
1475
+                            'name'       => 'MTP_template_fields['.$reference_field.'][MTP_ID]',
1476 1476
                             'label'      => null,
1477 1477
                             'input'      => 'hidden',
1478 1478
                             'type'       => 'int',
@@ -1484,8 +1484,8 @@  discard block
 block discarded – undo
1484 1484
                             'db-col'     => 'MTP_ID',
1485 1485
                         ];
1486 1486
 
1487
-                        $template_form_fields[ $template_field_template_name_id ] = [
1488
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1487
+                        $template_form_fields[$template_field_template_name_id] = [
1488
+                            'name'       => 'MTP_template_fields['.$reference_field.'][name]',
1489 1489
                             'label'      => null,
1490 1490
                             'input'      => 'hidden',
1491 1491
                             'type'       => 'string',
@@ -1499,38 +1499,38 @@  discard block
 block discarded – undo
1499 1499
                     }
1500 1500
                     continue; // skip the next stuff, we got the necessary fields here for this dataset.
1501 1501
                 } else {
1502
-                    $field_id                                   = $template_field . '-content';
1503
-                    $template_form_fields[ $field_id ]          = $field_setup_array;
1504
-                    $template_form_fields[ $field_id ]['name']  =
1505
-                        'MTP_template_fields[' . $template_field . '][content]';
1502
+                    $field_id                                   = $template_field.'-content';
1503
+                    $template_form_fields[$field_id]          = $field_setup_array;
1504
+                    $template_form_fields[$field_id]['name']  =
1505
+                        'MTP_template_fields['.$template_field.'][content]';
1506 1506
                     $message_template                           =
1507
-                        isset($message_templates[ $context ][ $template_field ])
1508
-                            ? $message_templates[ $context ][ $template_field ]
1507
+                        isset($message_templates[$context][$template_field])
1508
+                            ? $message_templates[$context][$template_field]
1509 1509
                             : null;
1510
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1511
-                                                                  && is_array($message_templates[ $context ])
1510
+                    $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1511
+                                                                  && is_array($message_templates[$context])
1512 1512
                                                                   && $message_template instanceof EE_Message_Template
1513 1513
                         ? $message_template->get('MTP_content')
1514 1514
                         : '';
1515 1515
 
1516 1516
                     // do we have a validator error for this field?  if we do then we'll use that value instead
1517
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1518
-                        ? $validators[ $template_field ]['value']
1519
-                        : $template_form_fields[ $field_id ]['value'];
1517
+                    $template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1518
+                        ? $validators[$template_field]['value']
1519
+                        : $template_form_fields[$field_id]['value'];
1520 1520
 
1521 1521
 
1522
-                    $template_form_fields[ $field_id ]['db-col']    = 'MTP_content';
1522
+                    $template_form_fields[$field_id]['db-col']    = 'MTP_content';
1523 1523
                     $css_class                                      = isset($field_setup_array['css_class'])
1524 1524
                         ? $field_setup_array['css_class']
1525 1525
                         : '';
1526
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1526
+                    $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1527 1527
                                                                       && in_array($template_field, $v_fields, true)
1528
-                                                                      && isset($validators[ $template_field ]['msg'])
1529
-                        ? 'validate-error ' . $css_class
1528
+                                                                      && isset($validators[$template_field]['msg'])
1529
+                        ? 'validate-error '.$css_class
1530 1530
                         : $css_class;
1531 1531
 
1532 1532
                     // shortcode selector
1533
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1533
+                    $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1534 1534
                         $template_field,
1535 1535
                         $field_id
1536 1536
                     );
@@ -1538,12 +1538,12 @@  discard block
 block discarded – undo
1538 1538
 
1539 1539
                 // k took care of content field(s) now let's take care of others.
1540 1540
 
1541
-                $template_field_MTP_id                 = $template_field . '-MTP_ID';
1542
-                $template_field_field_template_name_id = $template_field . '-name';
1541
+                $template_field_MTP_id                 = $template_field.'-MTP_ID';
1542
+                $template_field_field_template_name_id = $template_field.'-name';
1543 1543
 
1544 1544
                 // foreach template field there are actually two form fields created
1545
-                $template_form_fields[ $template_field_MTP_id ] = [
1546
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1545
+                $template_form_fields[$template_field_MTP_id] = [
1546
+                    'name'       => 'MTP_template_fields['.$template_field.'][MTP_ID]',
1547 1547
                     'label'      => null,
1548 1548
                     'input'      => 'hidden',
1549 1549
                     'type'       => 'int',
@@ -1555,8 +1555,8 @@  discard block
 block discarded – undo
1555 1555
                     'db-col'     => 'MTP_ID',
1556 1556
                 ];
1557 1557
 
1558
-                $template_form_fields[ $template_field_field_template_name_id ] = [
1559
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1558
+                $template_form_fields[$template_field_field_template_name_id] = [
1559
+                    'name'       => 'MTP_template_fields['.$template_field.'][name]',
1560 1560
                     'label'      => null,
1561 1561
                     'input'      => 'hidden',
1562 1562
                     'type'       => 'string',
@@ -1673,7 +1673,7 @@  discard block
 block discarded – undo
1673 1673
                 'format'     => '%d',
1674 1674
                 'db-col'     => 'MTP_deleted',
1675 1675
             ];
1676
-            $sidebar_form_fields['ee-msg-author']  = [
1676
+            $sidebar_form_fields['ee-msg-author'] = [
1677 1677
                 'name'       => 'MTP_user_id',
1678 1678
                 'label'      => esc_html__('Author', 'event_espresso'),
1679 1679
                 'input'      => 'hidden',
@@ -1692,17 +1692,17 @@  discard block
 block discarded – undo
1692 1692
                 'value' => $action,
1693 1693
             ];
1694 1694
 
1695
-            $sidebar_form_fields['ee-msg-id']        = [
1695
+            $sidebar_form_fields['ee-msg-id'] = [
1696 1696
                 'name'  => 'id',
1697 1697
                 'input' => 'hidden',
1698 1698
                 'type'  => 'int',
1699 1699
                 'value' => $GRP_ID,
1700 1700
             ];
1701 1701
             $sidebar_form_fields['ee-msg-evt-nonce'] = [
1702
-                'name'  => $action . '_nonce',
1702
+                'name'  => $action.'_nonce',
1703 1703
                 'input' => 'hidden',
1704 1704
                 'type'  => 'string',
1705
-                'value' => wp_create_nonce($action . '_nonce'),
1705
+                'value' => wp_create_nonce($action.'_nonce'),
1706 1706
             ];
1707 1707
 
1708 1708
             $template_switch = $this->request->getRequestParam('template_switch');
@@ -1733,7 +1733,7 @@  discard block
 block discarded – undo
1733 1733
         );
1734 1734
 
1735 1735
         // add preview button
1736
-        $preview_url    = parent::add_query_args_and_nonce(
1736
+        $preview_url = parent::add_query_args_and_nonce(
1737 1737
             [
1738 1738
                 'message_type' => $message_template_group->message_type(),
1739 1739
                 'messenger'    => $message_template_group->messenger(),
@@ -1744,7 +1744,7 @@  discard block
 block discarded – undo
1744 1744
             ],
1745 1745
             $this->_admin_base_url
1746 1746
         );
1747
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1747
+        $preview_button = '<a href="'.$preview_url.'" class="button-secondary messages-preview-button">'
1748 1748
                           . esc_html__('Preview', 'event_espresso')
1749 1749
                           . '</a>';
1750 1750
 
@@ -1778,11 +1778,11 @@  discard block
 block discarded – undo
1778 1778
             $context_label
1779 1779
         );
1780 1780
         $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1781
-        $this->_template_args['after_admin_page_content']  = $this->_add_form_element_after();
1781
+        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1782 1782
 
1783 1783
         $this->_template_path = $this->_template_args['GRP_ID']
1784 1784
             ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1785
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1785
+            : EE_MSG_TEMPLATE_PATH.'ee_msg_details_main_add_meta_box.template.php';
1786 1786
 
1787 1787
         // send along EE_Message_Template_Group object for further template use.
1788 1788
         $this->_template_args['MTP'] = $message_template_group;
@@ -1838,7 +1838,7 @@  discard block
 block discarded – undo
1838 1838
     ) {
1839 1839
         $template_args = [
1840 1840
             'context'                   => $context,
1841
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1841
+            'nonce'                     => wp_create_nonce('activate_'.$context.'_toggle_nonce'),
1842 1842
             'is_active'                 => $message_template_group->is_context_active($context),
1843 1843
             'on_off_action'             => $message_template_group->is_context_active($context)
1844 1844
                 ? 'context-off'
@@ -1847,7 +1847,7 @@  discard block
 block discarded – undo
1847 1847
             'message_template_group_id' => $message_template_group->ID(),
1848 1848
         ];
1849 1849
         return EEH_Template::display_template(
1850
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1850
+            EE_MSG_TEMPLATE_PATH.'ee_msg_editor_active_context_element.template.php',
1851 1851
             $template_args,
1852 1852
             true
1853 1853
         );
@@ -1904,7 +1904,7 @@  discard block
 block discarded – undo
1904 1904
         }
1905 1905
         $message_template_group_id = $this->request->getRequestParam('message_template_group_id', 0, 'int');
1906 1906
         $message_template_group    = EEM_Message_Template_Group::instance()->get_one_by_ID($message_template_group_id);
1907
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1907
+        if ( ! $message_template_group instanceof EE_Message_Template_Group) {
1908 1908
             EE_Error::add_error(
1909 1909
                 sprintf(
1910 1910
                     esc_html__(
@@ -2035,7 +2035,7 @@  discard block
 block discarded – undo
2035 2035
         $messenger    = $this->request->getRequestParam('msgr');
2036 2036
         $message_type = $this->request->getRequestParam('mt');
2037 2037
         // we need to make sure we've got the info we need.
2038
-        if (! ($GRP_ID && $messenger && $message_type)) {
2038
+        if ( ! ($GRP_ID && $messenger && $message_type)) {
2039 2039
             EE_Error::add_error(
2040 2040
                 esc_html__(
2041 2041
                     'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
@@ -2072,7 +2072,7 @@  discard block
 block discarded – undo
2072 2072
         }
2073 2073
 
2074 2074
         // any error messages?
2075
-        if (! $success) {
2075
+        if ( ! $success) {
2076 2076
             EE_Error::add_error(
2077 2077
                 esc_html__(
2078 2078
                     'Something went wrong with deleting existing templates. Unable to reset to default',
@@ -2122,7 +2122,7 @@  discard block
 block discarded – undo
2122 2122
     {
2123 2123
         // first make sure we've got the necessary parameters
2124 2124
         $GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
2125
-        if (! ($GRP_ID && $this->_active_messenger_name && $this->_active_message_type_name)) {
2125
+        if ( ! ($GRP_ID && $this->_active_messenger_name && $this->_active_message_type_name)) {
2126 2126
             EE_Error::add_error(
2127 2127
                 esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2128 2128
                 __FILE__,
@@ -2148,7 +2148,7 @@  discard block
 block discarded – undo
2148 2148
         $EVT_ID = $this->request->getRequestParam('evt_id', 0, 'int');
2149 2149
 
2150 2150
         // let's add a button to go back to the edit view
2151
-        $query_args             = [
2151
+        $query_args = [
2152 2152
             'id'      => $GRP_ID,
2153 2153
             'evt_id'  => $EVT_ID,
2154 2154
             'context' => $context,
@@ -2169,7 +2169,7 @@  discard block
 block discarded – undo
2169 2169
         $preview_title = sprintf(
2170 2170
             esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2171 2171
             $active_messenger_label,
2172
-            ucwords($message_types[ $this->_active_message_type_name ]->label['singular'])
2172
+            ucwords($message_types[$this->_active_message_type_name]->label['singular'])
2173 2173
         );
2174 2174
         if (empty($preview)) {
2175 2175
             $this->noEventsErrorMessage();
@@ -2177,7 +2177,7 @@  discard block
 block discarded – undo
2177 2177
         // setup display of preview.
2178 2178
         $this->_admin_page_title                    = $preview_title;
2179 2179
         $this->_template_args['admin_page_title']   = $preview_title;
2180
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2180
+        $this->_template_args['admin_page_content'] = $preview_button.'<br />'.$preview;
2181 2181
         $this->_template_args['data']['force_json'] = true;
2182 2182
 
2183 2183
         return '';
@@ -2198,7 +2198,7 @@  discard block
 block discarded – undo
2198 2198
             ],
2199 2199
             admin_url('admin.php')
2200 2200
         );
2201
-        $message    = $test_send
2201
+        $message = $test_send
2202 2202
             ? esc_html__(
2203 2203
                 'A test message could not be sent for this message template because there are no events created yet. The preview system uses actual events for generating the test message. %1$sGo see your events%2$s!',
2204 2204
                 'event_espresso'
@@ -2291,10 +2291,10 @@  discard block
 block discarded – undo
2291 2291
             // only include template packs that support this messenger and message type!
2292 2292
             $supports = $tp->get_supports();
2293 2293
             if (
2294
-                ! isset($supports[ $this->_message_template_group->messenger() ])
2294
+                ! isset($supports[$this->_message_template_group->messenger()])
2295 2295
                 || ! in_array(
2296 2296
                     $this->_message_template_group->message_type(),
2297
-                    $supports[ $this->_message_template_group->messenger() ],
2297
+                    $supports[$this->_message_template_group->messenger()],
2298 2298
                     true
2299 2299
                 )
2300 2300
             ) {
@@ -2318,7 +2318,7 @@  discard block
 block discarded – undo
2318 2318
         }
2319 2319
 
2320 2320
         // setup variation select values for the currently selected template.
2321
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
2321
+        $variations = $this->_message_template_group->get_template_pack()->get_variations(
2322 2322
             $this->_message_template_group->messenger(),
2323 2323
             $this->_message_template_group->message_type()
2324 2324
         );
@@ -2332,12 +2332,12 @@  discard block
 block discarded – undo
2332 2332
 
2333 2333
         $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2334 2334
 
2335
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
2335
+        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2336 2336
             'MTP_template_pack',
2337 2337
             $tp_select_values,
2338 2338
             $this->_message_template_group->get_template_pack_name()
2339 2339
         );
2340
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
2340
+        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
2341 2341
             'MTP_template_variation',
2342 2342
             $variations_select_values,
2343 2343
             $this->_message_template_group->get_template_pack_variation()
@@ -2347,7 +2347,7 @@  discard block
 block discarded – undo
2347 2347
         $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
2348 2348
         $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2349 2349
 
2350
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2350
+        $template = EE_MSG_TEMPLATE_PATH.'template_pack_and_variations_metabox.template.php';
2351 2351
 
2352 2352
         EEH_Template::display_template($template, $template_args);
2353 2353
     }
@@ -2373,33 +2373,33 @@  discard block
 block discarded – undo
2373 2373
         // first we need to see if there are any fields
2374 2374
         $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2375 2375
 
2376
-        if (! empty($fields)) {
2376
+        if ( ! empty($fields)) {
2377 2377
             // yup there be fields
2378 2378
             foreach ($fields as $field => $config) {
2379
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2379
+                $field_id = $this->_message_template_group->messenger().'_'.$field;
2380 2380
                 $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2381 2381
                 $default  = isset($config['default']) ? $config['default'] : '';
2382 2382
                 $default  = isset($config['value']) ? $config['value'] : $default;
2383 2383
 
2384 2384
                 // if type is hidden and the value is empty
2385 2385
                 // something may have gone wrong so let's correct with the defaults
2386
-                $fix                = $config['input'] === 'hidden'
2387
-                                      && isset($existing[ $field ])
2388
-                                      && empty($existing[ $field ])
2386
+                $fix = $config['input'] === 'hidden'
2387
+                                      && isset($existing[$field])
2388
+                                      && empty($existing[$field])
2389 2389
                     ? $default
2390 2390
                     : '';
2391
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2392
-                    ? $existing[ $field ]
2391
+                $existing[$field] = isset($existing[$field]) && empty($fix)
2392
+                    ? $existing[$field]
2393 2393
                     : $fix;
2394 2394
 
2395
-                $template_form_fields[ $field_id ] = [
2396
-                    'name'       => 'test_settings_fld[' . $field . ']',
2395
+                $template_form_fields[$field_id] = [
2396
+                    'name'       => 'test_settings_fld['.$field.']',
2397 2397
                     'label'      => $config['label'],
2398 2398
                     'input'      => $config['input'],
2399 2399
                     'type'       => $config['type'],
2400 2400
                     'required'   => $config['required'],
2401 2401
                     'validation' => $config['validation'],
2402
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2402
+                    'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2403 2403
                     'css_class'  => $config['css_class'],
2404 2404
                     'options'    => isset($config['options']) ? $config['options'] : [],
2405 2405
                     'default'    => $default,
@@ -2413,7 +2413,7 @@  discard block
 block discarded – undo
2413 2413
             : '';
2414 2414
 
2415 2415
         // print out $test_settings_fields
2416
-        if (! empty($test_settings_html)) {
2416
+        if ( ! empty($test_settings_html)) {
2417 2417
             $test_settings_html .= '<input type="submit" class="button-primary mtp-test-button alignright" ';
2418 2418
             $test_settings_html .= 'name="test_button" value="';
2419 2419
             $test_settings_html .= esc_html__('Test Send', 'event_espresso');
@@ -2459,7 +2459,7 @@  discard block
 block discarded – undo
2459 2459
         ];
2460 2460
 
2461 2461
         return EEH_Template::display_template(
2462
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2462
+            EE_MSG_TEMPLATE_PATH.'shortcode_selector_skeleton.template.php',
2463 2463
             $template_args,
2464 2464
             true
2465 2465
         );
@@ -2485,7 +2485,7 @@  discard block
 block discarded – undo
2485 2485
         // $messenger = $this->_message_template_group->messenger_obj();
2486 2486
         // now let's set the content depending on the status of the shortcodes array
2487 2487
         if (empty($shortcodes)) {
2488
-            echo '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2488
+            echo '<p>'.esc_html__('There are no valid shortcodes available', 'event_espresso').'</p>';
2489 2489
             return;
2490 2490
         }
2491 2491
         ?>
@@ -2521,7 +2521,7 @@  discard block
 block discarded – undo
2521 2521
     {
2522 2522
 
2523 2523
         // no need to run this if the property is already set
2524
-        if (! empty($this->_shortcodes)) {
2524
+        if ( ! empty($this->_shortcodes)) {
2525 2525
             return;
2526 2526
         }
2527 2527
 
@@ -2576,7 +2576,7 @@  discard block
 block discarded – undo
2576 2576
     protected function _set_message_template_group()
2577 2577
     {
2578 2578
 
2579
-        if (! empty($this->_message_template_group)) {
2579
+        if ( ! empty($this->_message_template_group)) {
2580 2580
             return;
2581 2581
         } //get out if this is already set.
2582 2582
 
@@ -2626,8 +2626,8 @@  discard block
 block discarded – undo
2626 2626
                     <?php
2627 2627
                 }
2628 2628
                 // setup nonce_url
2629
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2630
-                $id = 'ee-' . sanitize_key($context_label['label']) . '-select';
2629
+                wp_nonce_field($args['action'].'_nonce', $args['action'].'_nonce', false);
2630
+                $id = 'ee-'.sanitize_key($context_label['label']).'-select';
2631 2631
                 ?>
2632 2632
                 <label for='<?php echo esc_attr($id); ?>' class='screen-reader-text'>
2633 2633
                     <?php esc_html_e('message context options', 'event_espresso'); ?>
@@ -2640,7 +2640,7 @@  discard block
 block discarded – undo
2640 2640
                             $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2641 2641
                             ?>
2642 2642
                             <option value="<?php echo esc_attr($context); ?>" <?php echo esc_attr($checked); ?>>
2643
-                                <?php echo $context_details[ $context ]['label']; // already escaped ?>
2643
+                                <?php echo $context_details[$context]['label']; // already escaped ?>
2644 2644
                             </option>
2645 2645
                         <?php endforeach;
2646 2646
                     endif; ?>
@@ -2727,10 +2727,10 @@  discard block
 block discarded – undo
2727 2727
         $context_slug = $this->request->getRequestParam('MTP_context', '');
2728 2728
         $context      = ucwords(str_replace('_', ' ', $context_slug));
2729 2729
 
2730
-        $item_desc   = $messenger_label && $message_type_label
2731
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2730
+        $item_desc = $messenger_label && $message_type_label
2731
+            ? $messenger_label.' '.$message_type_label.' '.$context.' '
2732 2732
             : '';
2733
-        $item_desc   .= 'Message Template';
2733
+        $item_desc .= 'Message Template';
2734 2734
         $query_args  = [];
2735 2735
         $edit_array  = [];
2736 2736
         $action_desc = '';
@@ -2762,7 +2762,7 @@  discard block
 block discarded – undo
2762 2762
             // messages content is expected to be escaped
2763 2763
             $template_fields = EEH_Array::addSlashesRecursively($template_fields);
2764 2764
 
2765
-            if (! $template_fields) {
2765
+            if ( ! $template_fields) {
2766 2766
                 EE_Error::add_error(
2767 2767
                     esc_html__(
2768 2768
                         'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
@@ -2806,7 +2806,7 @@  discard block
 block discarded – undo
2806 2806
                 // if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2807 2807
                 // appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2808 2808
                 //  WE need to make sure there is no actual error messages in validates.
2809
-                if (! empty($validates)) {
2809
+                if ( ! empty($validates)) {
2810 2810
                     // add the transient so when the form loads we know which fields to highlight
2811 2811
                     $this->_add_transient('edit_message_template', $validates);
2812 2812
 
@@ -2826,7 +2826,7 @@  discard block
 block discarded – undo
2826 2826
                         $set_column_values = $this->_set_message_template_column_values($template_field);
2827 2827
 
2828 2828
                         // if they aren't allowed to use all JS, restrict them to just posty-y tags
2829
-                        if (! current_user_can('unfiltered_html')) {
2829
+                        if ( ! current_user_can('unfiltered_html')) {
2830 2830
                             $set_column_values['MTP_content'] = $this->sanitizeMessageTemplateContent(
2831 2831
                                 $set_column_values['MTP_content']
2832 2832
                             );
@@ -2968,7 +2968,7 @@  discard block
 block discarded – undo
2968 2968
     {
2969 2969
         if (is_array($content)) {
2970 2970
             foreach ($content as $key => $value) {
2971
-                $content[ $key ] = $this->sanitizeMessageTemplateContent($value);
2971
+                $content[$key] = $this->sanitizeMessageTemplateContent($value);
2972 2972
             }
2973 2973
             return $content;
2974 2974
         }
@@ -3109,7 +3109,7 @@  discard block
 block discarded – undo
3109 3109
         if ($all) {
3110 3110
             // Checkboxes
3111 3111
             $checkboxes = $this->request->getRequestParam('checkbox', [], 'int', true);
3112
-            if (! empty($checkboxes)) {
3112
+            if ( ! empty($checkboxes)) {
3113 3113
                 // if array has more than one element then success message should be plural.
3114 3114
                 // todo: what about nonce?
3115 3115
                 $success = count($checkboxes) > 1 ? 2 : 1;
@@ -3117,16 +3117,16 @@  discard block
 block discarded – undo
3117 3117
                 // cycle through checkboxes
3118 3118
                 while (list($GRP_ID, $value) = each($checkboxes)) {
3119 3119
                     $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3120
-                    if (! $trashed_or_restored) {
3120
+                    if ( ! $trashed_or_restored) {
3121 3121
                         $success = 0;
3122 3122
                     }
3123 3123
                 }
3124 3124
             } else {
3125 3125
                 // grab single GRP_ID and handle
3126 3126
                 $GRP_ID = $this->request->getRequestParam('id', 0, 'int');
3127
-                if (! empty($GRP_ID)) {
3127
+                if ( ! empty($GRP_ID)) {
3128 3128
                     $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3129
-                    if (! $trashed_or_restored) {
3129
+                    if ( ! $trashed_or_restored) {
3130 3130
                         $success = 0;
3131 3131
                     }
3132 3132
                 } else {
@@ -3174,7 +3174,7 @@  discard block
 block discarded – undo
3174 3174
 
3175 3175
         // checkboxes
3176 3176
         $checkboxes = $this->request->getRequestParam('checkbox', [], 'int', true);
3177
-        if (! empty($checkboxes)) {
3177
+        if ( ! empty($checkboxes)) {
3178 3178
             // if array has more than one element then success message should be plural
3179 3179
             $success = count($checkboxes) > 1 ? 2 : 1;
3180 3180
 
@@ -3279,7 +3279,7 @@  discard block
 block discarded – undo
3279 3279
     protected function _set_m_mt_settings()
3280 3280
     {
3281 3281
         // first if this is already set then lets get out no need to regenerate data.
3282
-        if (! empty($this->_m_mt_settings)) {
3282
+        if ( ! empty($this->_m_mt_settings)) {
3283 3283
             return;
3284 3284
         }
3285 3285
 
@@ -3291,7 +3291,7 @@  discard block
 block discarded – undo
3291 3291
         // assemble the array for the _tab_text_links helper
3292 3292
 
3293 3293
         foreach ($messengers as $messenger) {
3294
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = [
3294
+            $this->_m_mt_settings['messenger_tabs'][$messenger->name] = [
3295 3295
                 'label' => ucwords($messenger->label['singular']),
3296 3296
                 'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3297 3297
                     ? 'messenger-active'
@@ -3308,7 +3308,7 @@  discard block
 block discarded – undo
3308 3308
             foreach ($message_types as $message_type) {
3309 3309
                 // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3310 3310
                 // it shouldn't show in either the inactive OR active metabox.
3311
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3311
+                if ( ! in_array($message_type->name, $message_types_for_messenger, true)) {
3312 3312
                     continue;
3313 3313
                 }
3314 3314
 
@@ -3319,12 +3319,12 @@  discard block
 block discarded – undo
3319 3319
                     ? 'active'
3320 3320
                     : 'inactive';
3321 3321
 
3322
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = [
3322
+                $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = [
3323 3323
                     'label'    => ucwords($message_type->label['singular']),
3324
-                    'class'    => 'message-type-' . $a_or_i,
3325
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3326
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3327
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3324
+                    'class'    => 'message-type-'.$a_or_i,
3325
+                    'slug_id'  => $message_type->name.'-messagetype-'.$messenger->name,
3326
+                    'mt_nonce' => wp_create_nonce($message_type->name.'_nonce'),
3327
+                    'href'     => 'espresso_'.$message_type->name.'_message_type_settings',
3328 3328
                     'title'    => $a_or_i === 'active'
3329 3329
                         ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3330 3330
                         : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
@@ -3355,25 +3355,25 @@  discard block
 block discarded – undo
3355 3355
         $fields                                         = $message_type->get_admin_settings_fields();
3356 3356
         $settings_template_args['template_form_fields'] = '';
3357 3357
 
3358
-        if (! empty($fields) && $active) {
3358
+        if ( ! empty($fields) && $active) {
3359 3359
             $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3360 3360
             foreach ($fields as $fldname => $fldprops) {
3361
-                $field_id                         = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3362
-                $template_form_field[ $field_id ] = [
3363
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3361
+                $field_id                         = $messenger->name.'-'.$message_type->name.'-'.$fldname;
3362
+                $template_form_field[$field_id] = [
3363
+                    'name'       => 'message_type_settings['.$fldname.']',
3364 3364
                     'label'      => $fldprops['label'],
3365 3365
                     'input'      => $fldprops['field_type'],
3366 3366
                     'type'       => $fldprops['value_type'],
3367 3367
                     'required'   => $fldprops['required'],
3368 3368
                     'validation' => $fldprops['validation'],
3369
-                    'value'      => isset($existing_settings[ $fldname ])
3370
-                        ? $existing_settings[ $fldname ]
3369
+                    'value'      => isset($existing_settings[$fldname])
3370
+                        ? $existing_settings[$fldname]
3371 3371
                         : $fldprops['default'],
3372 3372
                     'options'    => isset($fldprops['options'])
3373 3373
                         ? $fldprops['options']
3374 3374
                         : [],
3375
-                    'default'    => isset($existing_settings[ $fldname ])
3376
-                        ? $existing_settings[ $fldname ]
3375
+                    'default'    => isset($existing_settings[$fldname])
3376
+                        ? $existing_settings[$fldname]
3377 3377
                         : $fldprops['default'],
3378 3378
                     'css_class'  => 'no-drag',
3379 3379
                     'format'     => $fldprops['format'],
@@ -3393,15 +3393,15 @@  discard block
 block discarded – undo
3393 3393
         $settings_template_args['description'] = $message_type->description;
3394 3394
         // we also need some hidden fields
3395 3395
         $hidden_fields = [
3396
-            'message_type_settings[messenger]' . $message_type->name    => [
3396
+            'message_type_settings[messenger]'.$message_type->name    => [
3397 3397
                 'type'  => 'hidden',
3398 3398
                 'value' => $messenger->name,
3399 3399
             ],
3400
-            'message_type_settings[message_type]' . $message_type->name => [
3400
+            'message_type_settings[message_type]'.$message_type->name => [
3401 3401
                 'type'  => 'hidden',
3402 3402
                 'value' => $message_type->name,
3403 3403
             ],
3404
-            'type' . $message_type->name                                => [
3404
+            'type'.$message_type->name                                => [
3405 3405
                 'type'  => 'hidden',
3406 3406
                 'value' => 'message_type',
3407 3407
             ],
@@ -3411,12 +3411,12 @@  discard block
 block discarded – undo
3411 3411
             $hidden_fields,
3412 3412
             'array'
3413 3413
         );
3414
-        $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields'])
3414
+        $settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3415 3415
             ? ' hidden'
3416 3416
             : '';
3417 3417
 
3418 3418
 
3419
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3419
+        $template = EE_MSG_TEMPLATE_PATH.'ee_msg_mt_settings_content.template.php';
3420 3420
         return EEH_Template::display_template($template, $settings_template_args, true);
3421 3421
     }
3422 3422
 
@@ -3444,21 +3444,21 @@  discard block
 block discarded – undo
3444 3444
 
3445 3445
                 // messenger meta boxes
3446 3446
                 $active         = $selected_messenger === $messenger;
3447
-                $active_mt_tabs = isset($this->_m_mt_settings['message_type_tabs'][ $messenger ]['active'])
3448
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3447
+                $active_mt_tabs = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
3448
+                    ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
3449 3449
                     : '';
3450 3450
 
3451
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3451
+                $m_boxes[$messenger.'_a_box'] = sprintf(
3452 3452
                     esc_html__('%s Settings', 'event_espresso'),
3453 3453
                     $tab_array['label']
3454 3454
                 );
3455 3455
 
3456
-                $m_template_args[ $messenger . '_a_box' ] = [
3456
+                $m_template_args[$messenger.'_a_box'] = [
3457 3457
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3458 3458
                     'inactive_message_types' => isset(
3459
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3459
+                        $this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
3460 3460
                     )
3461
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3461
+                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
3462 3462
                         : '',
3463 3463
                     'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3464 3464
                     'hidden'                 => $active ? '' : ' hidden',
@@ -3470,13 +3470,13 @@  discard block
 block discarded – undo
3470 3470
                 // message type meta boxes
3471 3471
                 // (which is really just the inactive container for each messenger
3472 3472
                 // showing inactive message types for that messenger)
3473
-                $mt_boxes[ $messenger . '_i_box' ]         = esc_html__('Inactive Message Types', 'event_espresso');
3474
-                $mt_template_args[ $messenger . '_i_box' ] = [
3473
+                $mt_boxes[$messenger.'_i_box']         = esc_html__('Inactive Message Types', 'event_espresso');
3474
+                $mt_template_args[$messenger.'_i_box'] = [
3475 3475
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3476 3476
                     'inactive_message_types' => isset(
3477
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3477
+                        $this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
3478 3478
                     )
3479
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3479
+                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
3480 3480
                         : '',
3481 3481
                     'hidden'                 => $active ? '' : ' hidden',
3482 3482
                     'hide_on_message'        => $hide_on_message,
@@ -3489,14 +3489,14 @@  discard block
 block discarded – undo
3489 3489
 
3490 3490
 
3491 3491
         // register messenger metaboxes
3492
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3492
+        $m_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_mt_meta_box.template.php';
3493 3493
         foreach ($m_boxes as $box => $label) {
3494
-            $callback_args = ['template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]];
3494
+            $callback_args = ['template_path' => $m_template_path, 'template_args' => $m_template_args[$box]];
3495 3495
             $msgr          = str_replace('_a_box', '', $box);
3496 3496
             add_meta_box(
3497
-                'espresso_' . $msgr . '_settings',
3497
+                'espresso_'.$msgr.'_settings',
3498 3498
                 $label,
3499
-                function ($post, $metabox) {
3499
+                function($post, $metabox) {
3500 3500
                     EEH_Template::display_template(
3501 3501
                         $metabox['args']['template_path'],
3502 3502
                         $metabox['args']['template_args']
@@ -3510,17 +3510,17 @@  discard block
 block discarded – undo
3510 3510
         }
3511 3511
 
3512 3512
         // register message type metaboxes
3513
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3513
+        $mt_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_meta_box.template.php';
3514 3514
         foreach ($mt_boxes as $box => $label) {
3515 3515
             $callback_args = [
3516 3516
                 'template_path' => $mt_template_path,
3517
-                'template_args' => $mt_template_args[ $box ],
3517
+                'template_args' => $mt_template_args[$box],
3518 3518
             ];
3519
-            $mt            = str_replace('_i_box', '', $box);
3519
+            $mt = str_replace('_i_box', '', $box);
3520 3520
             add_meta_box(
3521
-                'espresso_' . $mt . '_inactive_mts',
3521
+                'espresso_'.$mt.'_inactive_mts',
3522 3522
                 $label,
3523
-                function ($post, $metabox) {
3523
+                function($post, $metabox) {
3524 3524
                     EEH_Template::display_template(
3525 3525
                         $metabox['args']['template_path'],
3526 3526
                         $metabox['args']['template_args']
@@ -3665,7 +3665,7 @@  discard block
 block discarded – undo
3665 3665
             if ($form->is_valid()) {
3666 3666
                 $valid_data = $form->valid_data();
3667 3667
                 foreach ($valid_data as $property => $value) {
3668
-                    $setter = 'set_' . $property;
3668
+                    $setter = 'set_'.$property;
3669 3669
                     if (method_exists($network_config, $setter)) {
3670 3670
                         $network_config->{$setter}($value);
3671 3671
                     } elseif (
@@ -3701,7 +3701,7 @@  discard block
 block discarded – undo
3701 3701
     protected function _get_mt_tabs($tab_array)
3702 3702
     {
3703 3703
         $tab_array = (array) $tab_array;
3704
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3704
+        $template  = EE_MSG_TEMPLATE_PATH.'ee_msg_details_mt_settings_tab_item.template.php';
3705 3705
         $tabs      = '';
3706 3706
 
3707 3707
         foreach ($tab_array as $tab) {
@@ -3729,20 +3729,20 @@  discard block
 block discarded – undo
3729 3729
         $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3730 3730
 
3731 3731
 
3732
-        if (! empty($fields)) {
3732
+        if ( ! empty($fields)) {
3733 3733
             $existing_settings = $messenger->get_existing_admin_settings();
3734 3734
 
3735 3735
             foreach ($fields as $fldname => $fldprops) {
3736
-                $field_id                         = $messenger->name . '-' . $fldname;
3737
-                $template_form_field[ $field_id ] = [
3738
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3736
+                $field_id                         = $messenger->name.'-'.$fldname;
3737
+                $template_form_field[$field_id] = [
3738
+                    'name'       => 'messenger_settings['.$field_id.']',
3739 3739
                     'label'      => $fldprops['label'],
3740 3740
                     'input'      => $fldprops['field_type'],
3741 3741
                     'type'       => $fldprops['value_type'],
3742 3742
                     'required'   => $fldprops['required'],
3743 3743
                     'validation' => $fldprops['validation'],
3744
-                    'value'      => isset($existing_settings[ $field_id ])
3745
-                        ? $existing_settings[ $field_id ]
3744
+                    'value'      => isset($existing_settings[$field_id])
3745
+                        ? $existing_settings[$field_id]
3746 3746
                         : $fldprops['default'],
3747 3747
                     'css_class'  => '',
3748 3748
                     'format'     => $fldprops['format'],
@@ -3757,20 +3757,20 @@  discard block
 block discarded – undo
3757 3757
 
3758 3758
         // we also need some hidden fields
3759 3759
         $settings_template_args['hidden_fields'] = [
3760
-            'messenger_settings[messenger]' . $messenger->name => [
3760
+            'messenger_settings[messenger]'.$messenger->name => [
3761 3761
                 'type'  => 'hidden',
3762 3762
                 'value' => $messenger->name,
3763 3763
             ],
3764
-            'type' . $messenger->name                          => [
3764
+            'type'.$messenger->name                          => [
3765 3765
                 'type'  => 'hidden',
3766 3766
                 'value' => 'messenger',
3767 3767
             ],
3768 3768
         ];
3769 3769
 
3770 3770
         // make sure any active message types that are existing are included in the hidden fields
3771
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3772
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3773
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = [
3771
+        if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3772
+            foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3773
+                $settings_template_args['hidden_fields']['messenger_settings[message_types]['.$mt.']'] = [
3774 3774
                     'type'  => 'hidden',
3775 3775
                     'value' => $mt,
3776 3776
                 ];
@@ -3780,7 +3780,7 @@  discard block
 block discarded – undo
3780 3780
             $settings_template_args['hidden_fields'],
3781 3781
             'array'
3782 3782
         );
3783
-        $active                                  =
3783
+        $active =
3784 3784
             $this->_message_resource_manager->is_messenger_active($messenger->name);
3785 3785
 
3786 3786
         $settings_template_args['messenger']           = $messenger->name;
@@ -3800,9 +3800,9 @@  discard block
 block discarded – undo
3800 3800
 
3801 3801
 
3802 3802
         $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3803
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3803
+        $settings_template_args['nonce']         = wp_create_nonce('activate_'.$messenger->name.'_toggle_nonce');
3804 3804
         $settings_template_args['on_off_status'] = $active;
3805
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3805
+        $template                                = EE_MSG_TEMPLATE_PATH.'ee_msg_m_settings_content.template.php';
3806 3806
         return EEH_Template::display_template(
3807 3807
             $template,
3808 3808
             $settings_template_args,
@@ -3827,7 +3827,7 @@  discard block
 block discarded – undo
3827 3827
         $this->_prep_default_response_for_messenger_or_message_type_toggle();
3828 3828
         // let's check that we have required data
3829 3829
 
3830
-        if (! $this->_active_messenger_name) {
3830
+        if ( ! $this->_active_messenger_name) {
3831 3831
             EE_Error::add_error(
3832 3832
                 esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3833 3833
                 __FILE__,
@@ -3845,7 +3845,7 @@  discard block
 block discarded – undo
3845 3845
 
3846 3846
 
3847 3847
         $status = $this->request->getRequestParam('status');
3848
-        if (! $status) {
3848
+        if ( ! $status) {
3849 3849
             EE_Error::add_error(
3850 3850
                 esc_html__(
3851 3851
                     'Messenger status needed to know whether activation or deactivation is happening. No status is given',
@@ -3902,7 +3902,7 @@  discard block
 block discarded – undo
3902 3902
         $this->_prep_default_response_for_messenger_or_message_type_toggle();
3903 3903
 
3904 3904
         // let's make sure we have the necessary data
3905
-        if (! $this->_active_message_type_name) {
3905
+        if ( ! $this->_active_message_type_name) {
3906 3906
             EE_Error::add_error(
3907 3907
                 esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3908 3908
                 __FILE__,
@@ -3912,7 +3912,7 @@  discard block
 block discarded – undo
3912 3912
             $success = false;
3913 3913
         }
3914 3914
 
3915
-        if (! $this->_active_messenger_name) {
3915
+        if ( ! $this->_active_messenger_name) {
3916 3916
             EE_Error::add_error(
3917 3917
                 esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3918 3918
                 __FILE__,
@@ -3923,7 +3923,7 @@  discard block
 block discarded – undo
3923 3923
         }
3924 3924
 
3925 3925
         $status = $this->request->getRequestParam('status');
3926
-        if (! $status) {
3926
+        if ( ! $status) {
3927 3927
             EE_Error::add_error(
3928 3928
                 esc_html__(
3929 3929
                     'Messenger status needed to know whether activation or deactivation is happening. No status is given',
@@ -4135,7 +4135,7 @@  discard block
 block discarded – undo
4135 4135
         EE_Message_Type $message_type = null
4136 4136
     ) {
4137 4137
         // if $messenger isn't a valid messenger object then get out.
4138
-        if (! $messenger instanceof EE_Messenger) {
4138
+        if ( ! $messenger instanceof EE_Messenger) {
4139 4139
             EE_Error::add_error(
4140 4140
                 esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4141 4141
                 __FILE__,
@@ -4189,7 +4189,7 @@  discard block
 block discarded – undo
4189 4189
             // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4190 4190
             // in which case we just give a success message for the messenger being successfully activated.
4191 4191
         } else {
4192
-            if (! $messenger->get_default_message_types()) {
4192
+            if ( ! $messenger->get_default_message_types()) {
4193 4193
                 // messenger doesn't have any default message types so still a success.
4194 4194
                 EE_Error::add_success(
4195 4195
                     sprintf(
@@ -4245,7 +4245,7 @@  discard block
 block discarded – undo
4245 4245
         EE_Error::overwrite_success();
4246 4246
 
4247 4247
         // if $messenger isn't a valid messenger object then get out.
4248
-        if (! $messenger instanceof EE_Messenger) {
4248
+        if ( ! $messenger instanceof EE_Messenger) {
4249 4249
             EE_Error::add_error(
4250 4250
                 esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4251 4251
                 __FILE__,
@@ -4309,7 +4309,7 @@  discard block
 block discarded – undo
4309 4309
      */
4310 4310
     public function update_mt_form()
4311 4311
     {
4312
-        if (! $this->_active_messenger_name || ! $this->_active_message_type_name) {
4312
+        if ( ! $this->_active_messenger_name || ! $this->_active_message_type_name) {
4313 4313
             EE_Error::add_error(
4314 4314
                 esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4315 4315
                 __FILE__,
@@ -4320,7 +4320,7 @@  discard block
 block discarded – undo
4320 4320
         }
4321 4321
 
4322 4322
         $message_types = $this->get_installed_message_types();
4323
-        $message_type  = $message_types[ $this->_active_message_type_name ];
4323
+        $message_type  = $message_types[$this->_active_message_type_name];
4324 4324
         $messenger     = $this->_message_resource_manager->get_active_messenger($this->_active_messenger_name);
4325 4325
         $content       = $this->_message_type_settings_content($message_type, $messenger, true);
4326 4326
 
@@ -4339,7 +4339,7 @@  discard block
 block discarded – undo
4339 4339
     public function save_settings()
4340 4340
     {
4341 4341
         $type = $this->request->getRequestParam('type');
4342
-        if (! $type) {
4342
+        if ( ! $type) {
4343 4343
             EE_Error::add_error(
4344 4344
                 esc_html__(
4345 4345
                     'Cannot save settings because type is unknown (messenger settings or message type settings?)',
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -38,103 +38,103 @@
 block discarded – undo
38 38
  * @since           4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.6.2');
65
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.6.2');
65
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
-        /**
98
-         * espresso_version
99
-         * Returns the plugin version
100
-         *
101
-         * @return string
102
-         */
103
-        function espresso_version()
104
-        {
105
-            return apply_filters('FHEE__espresso__espresso_version', '4.10.26.rc.001');
106
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
+		/**
98
+		 * espresso_version
99
+		 * Returns the plugin version
100
+		 *
101
+		 * @return string
102
+		 */
103
+		function espresso_version()
104
+		{
105
+			return apply_filters('FHEE__espresso__espresso_version', '4.10.26.rc.001');
106
+		}
107 107
 
108
-        /**
109
-         * espresso_plugin_activation
110
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
-         */
112
-        function espresso_plugin_activation()
113
-        {
114
-            update_option('ee_espresso_activation', true);
115
-        }
108
+		/**
109
+		 * espresso_plugin_activation
110
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
+		 */
112
+		function espresso_plugin_activation()
113
+		{
114
+			update_option('ee_espresso_activation', true);
115
+		}
116 116
 
117
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
117
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118 118
 
119
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
120
-        bootstrap_espresso();
121
-    }
119
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
120
+		bootstrap_espresso();
121
+	}
122 122
 }
123 123
 if (! function_exists('espresso_deactivate_plugin')) {
124
-    /**
125
-     *    deactivate_plugin
126
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
-     *
128
-     * @access public
129
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
-     * @return    void
131
-     */
132
-    function espresso_deactivate_plugin($plugin_basename = '')
133
-    {
134
-        if (! function_exists('deactivate_plugins')) {
135
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
-        }
137
-        unset($_GET['activate'], $_REQUEST['activate']);
138
-        deactivate_plugins($plugin_basename);
139
-    }
124
+	/**
125
+	 *    deactivate_plugin
126
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
+	 *
128
+	 * @access public
129
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
+	 * @return    void
131
+	 */
132
+	function espresso_deactivate_plugin($plugin_basename = '')
133
+	{
134
+		if (! function_exists('deactivate_plugins')) {
135
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
+		}
137
+		unset($_GET['activate'], $_REQUEST['activate']);
138
+		deactivate_plugins($plugin_basename);
139
+	}
140 140
 }
Please login to merge, or discard this patch.